#web-development
2 messages ยท Page 198 of 1
obnoxious
still struggling django.db.utils.ProgrammingError: column "date_of_birth" of relation "Occupier_occupier" does not exist
using axios or just a flask request?
and by values do you mean the data sent? if so
request.data
anyone here good with HTTP request and responses?
oh how can i build it
Can someone help me please. I am trying to setup daphne with django in deployment. I already setup a supervisor config file, which launches both the gunicorn startup file and the daphne startup file. But for some reason, when I check the status of the supervisor, it says that gunicorn works fine, but daphne has a fatal status. Is there a way to check error logs? and what could possibly be the problem?
@native tide rdp?
No, RDP is not a webserver. Windows' web server is IIS
so vps i can host a django project
??
Yes, that's one way
No, I'm not going to Google that for you but pick a platform and I'm sure there are multiple tutorials out there (Heroku and PythonAnywhere are probably both good enough on free tier)
good evening
i move from w7 to w10, i reinstall python, flask, wtforms, etc but when i run flask it display an error like
error when uploading myproyect
any help on this error?
Error: while importing 'MyProyect', an error was raised.
FIXED! thanks for the help
hmmm do you also know django?
also what do you mean by back end?
what exactly does it comprise of?
How can I make a button interact with a django model?
Basically I'm making a mini web clicker game and i'm using a HTML button it's storing the amount of coins to your account
So what's wanted is when I click for it to update the django model which stores the coins and then increment it by 1
You'd have to make request to your api /backend and update the amount of coins
@opaque rivet hey wassup bro
hey guys!
so the thing is, i dont know how foreign keys work
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50)
#notes = models.ForeignKey(something)
class Note(models.Model):
body = models.TextField(null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.body[0:50]
i want the user to have a notes object linked to it
by using foreign keys
the notes variable will contain the ids of all the notes the user has created, and i should be able to acess the notes body, updated, and created through the user.
Put the user foreign key on the Note model, for example as "author". Then you can search for all the notes by "author" as the user's username, etc.
Notes.objects.filter(author="demi")
and it will point to the appropriate user object
so then you can do something like name_of_note.author.username
how do i do that?
im getting an error while trying to create a foreign key
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50)
class Note(models.Model):
body = models.TextField(null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.body[0:50]
heres the error :
django.db.utils.IntegrityError: NOT NULL constraint failed: new__api_note.author_id
Anyone here knows how to make it so I dont have to relunch my dev site every time I want to update something in bottle?
I set Debug to true but it doesn't work.
idk why but im unable to add my custom template at reset password
at reset password i can load template , btw all things are working fine
but in reset password done , the mail what we get n complete idk why i cant load tempaltes
the name is also correct
im in trouble from last 2 days
app_name='users'
urlpatterns = [
path('register/',views.register,name='register'),
path('login/',auth_views.LoginView.as_view(template_name='users/login.html'),name='login'),
path('profile/',views.profile,name='profile'),
path('profile-create',views.profile_create,name='profile-update'),
path('logout/',auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'),
path('password-reset/',auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'),name='password_reset'),
path('password-reset/done/',auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'),name='password_reset_done'),
path('password-reset-confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'),name='password_reset_confirm'),
path('password-reset-complete/',auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'),name='password_reset_complete'),
]```
app urls
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('index.urls')),
path('account/',include('users.urls')),
path('', include('django.contrib.auth.urls')),
]
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
``` main urls
btw in this tried changing the path also of django.contrib.auth.urls
I donโt actually know Django, and by the backend I mean the server/data management/everything except the actual html/css/js
so is it not possible to make full stack websites with flask/django?
Hi there, sorry to cut you off. I'm currently building a website for my concept art portfolio. I'm fairly new in website building and would like to ask if anyone has any recommendations for website hosting services? I'm looking into using Hostinger, though I've read some bad reviews about them. Thanks in advance! Sorry if this is a bit out of topic.
...
Django
If yes after form tag u didn't wrote csrf token n if written so incorrect syntax
What's even strange is the fact that this code worked before
Flask
Can anyone tell me, is it safe having my homepage capable of showing private information once logged in? (in Django)
is this bad practice or unsafe?
what type of private info @whole sierra
password n all?
u can show email , name contact no. profile info n all , not password
@dusk portal yeah, behind the login is names, email and phone no.
assuming people wont be able to crack the username and password login. Will these be in anyway visible?
also, I am unable to associate @login_required with functions that dont return a request (render). is this safe to leave without @login_required?
so the thing is
the frontend is making a post request
and the backend is giving an internal server error
@api_view(["POST"])
def createAccount(request):
data = request.data
body = data["body"]
print(body)
return Response()
im just testing it out
the urls.py path
path("sign-up/", views.createAccount, name="create-account")
@astral thistle
i have pip install flask_sqlalchemy but i dont work
its pip install flask-sqlalchemy
did you do that?
secondly, you have to import it like this
from flask_sqlalchemy import SQLAlchemy
Looks like the return response is empty
"A server error occurred. Please contact the administrator." is that the kind of error ur getting?
how can i upload it how
I still waiting ...
its working and my website is finished
Hey I'm figuring that this is a terrible question but I'm asking anyway
Is there a course anyone knows that teaches one web-development until the point of an entry-level-job knowledge?
Trying to add Google maps into a project, anyone has done this before on python??? What's api key for Google maps thinking? Didn't get it.. I did something similar on c# but it was a little bit different...
Well aware that experience, projects, and portfolios matter the most, just wanna know the people's input on this
I'm guessing you mean free and online course?
Online? yes, free? Would be nice, but not limited to
I'd pay some solid cash for good education
I consider it an investment, of course I can study material by myself for free but definitely not in the same timeframe as a course would
Not me at least
I'm sure that there are ultra-geniuses here that can learn intermediate-level Django in a month but I'm not one of them.
that's okay. you don't have to be one
that said, I honestly don't know
what good paid courses there are.
my thought process, though, if you really feel this way
is to get a private tutor/instructor
Hm, that is a good idea
I just saw there are pretty good online courses on Udemy/Coursera for not much money, I was wondering if anyone here has some experience with those
how can i change my text position in flask
I didnt think about taking actual lessons though, I'll check if there are any where i live
I believe the vast majority of people do not do paid courses
fair warning, though
a good instructor will not be cheap
Yeah I figured, 15 bucks for a course seems pretty tempting
like, really not cheap
Yeah, I guess that's the main con
I figured I could probably, maybe, do something better with my money
you could.
I'm good at studying by myself, It's just that web development specifically has some really complex concepts "behind the hood" and I would like to get a basic grasp on those too
Any ideas?
doing that kinda thing is really a "long-run" thing
that kinda thing = getting an actual person to teach you
like?
what are you thinking of
Umm... Let me see
I'll give an example as I'm trying to learn bottle right now after encountering some issues with Flask
Alright, here
I think that's a decent example:
So cookies - I know what they are, and generally speaking what they do.
I would like some practical knowledge on them - How they're used in modern technology, where they're stored, how they're ordered, how to access them properly
ah
you want the surrounding knowledge
for example, the fact that a HttpOnly cookie is not accessible to JS
See, I barely even know what you said
You're telling me there are types of cookies?
there is basically
a flag you can set
to tell the browser
"don't let JS touch this"
Right, and maybe the doc explains it further down the line
I just cant get my head around it if I dont know its basic mechanics
It's hard to accept that there is just text that I can save and access behind a user's browser
Because I don't really know what to do with that knowledge and I cant get it inside my head.
And bottle is, and this is an understatement, not very supported. So I cant really find exercises* to test my knowledge on - so I invent my own experiments
mhm?
with mentors basically being private tutors
Oh, so?
a private tutor teaches you what you tell them to teach you
and then some
a mentor guides you in setting goals, reviews your progress, gives advice, etc.
they may also teach you specific stuff
but a lot of it goes towards easing the process of learning
Uh, do people actually get paid to be mentors?
it...depends
To me it sounds like you might as well be a private tutor with that knowledge - they could probably offer the same services and then some.
hello everyone
the canonical case is
someone senior (in terms of ability) to you
whom you know from work or socially
not necessarily.
because private tutors focus on the technical material
but I sense that's not all you're looking for
you also want the big picture
things like industrial applicability?
Um, I honestly don't know what that means*
I just don't want to learn things "like a parrot" - To know that X code does Y and apply it
I really believe some basic background understanding is required in order to really understand what you're doing
I could have a completely false understanding of what web development actually is. Maybe the correct way, so to speak, is to just know what code does and that's it
I could just be delving into it a little too much, I'm not even sure if web development is what I want to do. You can correct me if I'm wrong
yeah
ah
you don't just want someone to teach you webdev
@vestal hound pls help me
you want someone to help you chart your path, right
?
so rn, my "create a note view" in my django app doesnt need authentication.
basically what happened was
i built the authentication part after the app itself
so its getting kinda complicated
๐
that's the hard part, isn't it
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, primary_key=True, verbose_name="user", related_name="profile", on_delete=models.CASCADE)
name = models.CharField(max_length=30, blank=True, null=True)
bio = models.CharField(max_length=500, blank=True, null=True)
location = models.CharField(max_length=100, blank=True, null=True)
class Note(models.Model):
body = models.TextField(null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
def __str__(self):
return self.body[0:50]
this is my models.py
@api_view(['POST'])
def createNote(request):
data = request.data
note = Note.objects.create(
body=data['body']
)
serializer = NoteSerializer(note, many=False)
return Response(serializer.data)
this is the view that creates the note.
right now it doesnt need authentication as you can see.
what code should i add so that a certain user's note only appears to him
I honestly have no idea, is it? :(
I'm not sure but you can try something like
like I said, normally a mentor is someone you already know from somewhere
@login_required(login_url='login')
def createNote(request):
data = request.data
note = Note.objects.create(
body=data['body']
)
serializer = NoteSerializer(note, many=False)
return Response(serializer.data)```
Ah, time to make some new friends I guess
You have to be logged in to be able to create a note and once you do that, use the pk of a the user to filter the notes when a user want to see only his notes
you mean in the GET?
you can do that @ filter level
as a substitute
you can ask that kinda question around here
how to make a working search bar with python that displays a page with the search results?(like https://udemy.com/)
that has a complicated answer
how do you build a car?
pay someone to do it ๐ ezz
actually I have a more simple problem that I resolved once but forgot how to do it again in django, can you help guys ?
yeah, so if you think that way, pay someone to make that for you
but the problem is that im broke
then learn
yesss
am doing that
but what should i use
like django?
or anything else?
you're not @ the point you need to measure tech tradeoffs I think
I have an app where users can see album and photos, but they have to be authenticated to be able to do that. In views.pyโจโจpython @login_required(login_url='login') def index(request): if request.user.is_authenticated: user = request.user username = request.user.pk album = Album.objects.filter(owner_id=username) contexts = { 'album': album, 'user': user } return render(request, 'client/index.html', contexts) else: return render(request, 'client/login.html')โจโจโจindex.html
{% if album %}
<h2> Hi, {{ user.first_name }}. You have some photos to choose from.
</h2>
<div>
Click <a href="
{% url 'client:album_details' album.id %}">here</a> </div>
{% else %}
<h2>
Hi, {{ user.first_name }}. You don't have any photos uploaded yet.</h2>
<div>
Wanna book me ? Click <a href="{% url 'client:bookme' %}">here</a> </div>
{% endif %}
url(r'^user/(?P<pk>[0-9]+)/$', user_album_details, name='album_details'),
last but not least, the call to the user_album_details functions in views.py is :
@login_required(login_url='login')
def user_album_details(request, pk):
album = get_object_or_404(Album, id=pk)
return render(request, 'client/photo_details.html', {'album': album})```โจโจThe error :
NoReverseMatch at /client/user/
Reverse for 'album_details' with arguments '('',)' not found. 1 pattern(s) tried: ['client/user/(?P<pk>[0-9]+)/$']```
Partial solution:
if I replace album.id in index.html as follow :
<div>Click <a href="{% url 'client:album_details' 1 %}">here</a> </div>```
it works but with album.id or album.pk or even album_id, it doesn't work
What kind of question? Just any questions you mean?
yea
h
might not get na naswer but
@ leasty ou tried
๐
I use that phrase way too often. ๐
is defining STATICFILES_DIRS necessary? I havent defined it, and my image wouldnt show. Heres my code
{% load static %}
<img src="{% static 'base_app/image.jpg' %}"
alt="My naruto">
image is in base_app/static/base_app/image.jpg
how can i change my text position
could anyone tell me how to add otp to an already establish login.html page. I.e. I've already configured the rest framework auth
is there a way to send a request to another route internally? Flask/Quart
Django rest framework question ```py
class SignupSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ("id", "username", "email", "password")
extra_kwargs = {"password": {"write_only": True}}
def create(self, user_data):
return User.objects.create_user(user_data["username"], user_data["email"], user_data["password"])
``` I have this serializer, how can I dynamically add key to the serializers data?. I want to add a tokens key to the data which will contain the access and refresh token. Thanks
Imo it should be a separate serializer, why do you want to put tokens into user one?
Because, when a user signs up it will return the necessary tokens for them to do an action
It's usually done via separate endpoint though
Is anyone good at deciphering django error messages? I installed and configured django-rest-auth, double checked everything and still getting this error? I have the same set up on other recent projects and have not encountered this.
`Cannot import name "patterns" from "django.conf.urls" ๐
It says it's coming from within the rest-auth code though
which is hidden
since it is a package
Can you send it's github/pypi page?
It wasn't updated for 3 years though
And it probably doesn't support django 2 and 3
yeah that is a red flag, but I've made several recent projects using it andhavent had this problem
even used it last week
i would try a different package or version normally, but kinda mind boggled at how it worked with the same set up last week, which is making me think its something else i did
ive only been learnin django for the last month so still getting used to debugging it. its hard
Do I need to know a web server (apache nginx) for a django app?
If you want to deploy your app you'd probably need to set up nginx
For development built-in dev server would do
What's the way to set the flexbox width to it's children width
Parent containers should expand if children elements can't fit into it though ๐ค
currently my flexbox is being set to 100% width of the page tho
If you remove width rule then it should take width of largest child element
there isn't one tho
const InputContainer = styled.div`
height: 300px;
background-color: #00003F;
display: flex;
flex-direction: column;
flex-basis: 0;
align-items: center;
justify-content: center;
margin-left: 30px;
`
still being 100% width of the page
Which one is better:
https://www.udemy.com/course/the-complete-web-development-bootcamp/
https://www.udemy.com/course/the-web-developer-bootcamp/
@hushed cloud You can really learn all of that by yourself ๐คท
๐ฎ where
there are a bunch of free web tutorials
wait by myself 
oh that too, any reccomendations for that then
you really dont need udemy trust me
The Odin Project is pretty good
If you need to pass data into your templates, just pass it as context when using render_template
Context processors inject variables automatically, so it might be helpful for something global e.g. functions or configs
I guess just to keep your code dry ๐
As i see you can pass keyword arguments into render_template and they'll be available in your template
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
question, what is the best option to get the remote tcpip?
request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
or just
request.remote_addr
?
@orchid olive
I believe if you're running behind a proxy remote_addr would be that proxy ip ๐
so? first or second?
Depends on if you have a proxy server and it's setup ๐
Hello guys , please ,can someone explain to me how can I make my website online ?
Hey so I wish I could make a more targeted question, though async requests seem really complex and I need some advice around how to start and what the steps more or less are for me to implement them. My goal is when someone clicks process on a form, the inputs are taken and some calculations occur, then the existing page will be updated with the result (rather than my current approach of refreshing the entire page and specifying the inputs again via Jinja HTML logic).
Here is the Flask back-end stuff currently:
# 101Cipher.
from validation import Cipher101Form
@app.route("/encryption/101cipher", methods=['GET', 'POST'])
def cipher101():
form = Cipher101Form()
if request.method == 'POST':
if form.validate_on_submit():
key = form.key.data
number = form.number.data
try:
if form.encrypt.data:
result = encrypt_101(key, number)
elif form.decrypt.data:
result = decrypt_101(key, number)
except:
result = "Process Execution Failed"
data = {"key": key, "number": number, "result": result}
return render_template('encryption/101cipher.html', title="101Cipher", form="submitted", data=data)
else:
errors = form.errors
for form_value in errors:
errors[form_value] = errors[form_value][0]
return render_template('encryption/101cipher.html', title="101Cipher", form="failed", errors=errors)
else:
return render_template('encryption/101cipher.html', title="101Cipher", form=None)
The validation (for context):
# 101Cipher.
class Cipher101Form(FlaskForm):
encrypt = SubmitField('encrypt', validators=[Optional()])
decrypt = SubmitField('decrypt', validators=[Optional()])
key = StringField('key', validators=[InputRequired(), Regexp('^[1-9]\d*$',
message="Field must be a positive integer."),
length(max=101, message="Field cannot be longer than 101 digits")])
number = StringField('number', validators=[InputRequired(), Regexp('^[1-9]\d*$',
message="Field must be a positive integer."),
length(max=135, message="Field cannot be longer than 135 digits")])
So can anyone point me in the right direction please as far as how I can move away from this page re-rendering with parsed variables to dynamically updating the existing page?
I would greatly appreciate any help that can be provided here. ๐
there are many approaches to this. I guess the basic idea is to have an internal API endpoint that can be called by the front end when updating elements on the site on demand. https://htmx.org/ works well with flask, but you could also just use javascript to fetch the backend to get the data that should be updated to, then grab an element on the page to update it.
!p django
Converting to "int" failed for parameter "pep_number".
-p django
!pypi -> #bot-commands
hey guys for model forms is there a way to make it so a select box will only show options depending on what group a user is in
for django
Thanks for the link!
Didn't find this option myself.
Token-Based vs JWT vs Django-Knox for Authentication. What is the best to use in case of security?
we can create a bot for discord, ok
can we create a bot for MS-Teams?
one google request, and no magic: https://stackoverflow.com/questions/60269902/how-to-build-a-python-bot-for-teams-how-to-deploy-the-same-in-my-prod-server
thanks a lot, i look into that
I know this is a stupid question, but my django secret key was leaked. Considering I'm going to just generate another one, that shouldn't matter at all once the site is live right?
if the site was not live, then it does not matter.
usually the secret is used by you directly or indirectly in order for user authentification and other similar stuff where any encryption participates, for password hashes, temporal tokens (JWT?) and e.t.c.
if site was not live, then you had no users which authentificated with this secret key, and you would not care if somebody could impersonate them
if your site is not using secret key in anyway, you could just make it randomly generated at every start ;b
import secrets
SECRET_KEY = secrets.token_hex(16)
Hey guys! My Django wesbite is running on an EC2 Windows instance and I want to get SSL certification for it. What is the best course of action for me to follow?
letโs encrypt maybe ?
I was trying to get AWS Certificate Manager but couldn't connect it to my EC2 instance
Specifically rerouting it to my domain
what type are current_user.role and roles.user?
if one is RoleEnum.user and the other is RoleEnum.admin then the condition won't be met
can you try
{% if current_user.role|string() == roles.user|string() %}
first answer on google
flask uses jinja2
as its template rendering framework
so if you have any questions regarding rendering of the templates just look it up and append "jinja2" to your search query
was they were not of the same type
that's why i asked you to verify the types of objects
i assume by default __repr__() method is called of current_user.role object
when you just reference it as current_user.role
in the template
you can read more into __repr__() and other special methods of objects online
whereas string() made it call __str__() instead
which returned the string identical
to what roles.user|string() returned
Hi,
I have users who can be reported and I need to save information of the report.
So my user report model looks like this
class UserReportLog(models.Model):
ย ย reported_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
ย ย reported_at = models.DateTimeField(auto_now_add=True)
should I add another foreign key to the user who was reported ? which will make it
class UserReportLog(models.Model):
reported_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
ย ย reported_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
ย ย reported_at = models.DateTimeField(auto_now_add=True)
Currently there's a many to many field in the user model
userReportBy = models.ManyToManyField(
ย ย ย ย UserReportLog, related_name="userReported", blank=True
ย ย )
I'm not sure which is the best practice
hey guys, im building a backend using flask and a frontend using react right. i dont have issues im asking for advice because the last time i kept going without planning i screwed up really badly with oauth. im using flask therefore my best guess is to use flask login but im not sure its not secure enough. what is the best system for authentication. also, how can i maximise the utilisation of sessions because im sure thats required in a application
idk if this is right place to ask, my ques is related to getting image from google
i am making a bot, which would post a quote, and post the author's photo
i am making the photo part
this is my code- https://paste.pythondiscord.com/yolaralura.py
but, if i replace the https://www.google.com/search with https://www.google.com/imghp?hl=en it won't work
can anyone help?
You can try .net or spring boot for robust backends
why would i use them, i find them horribly unintuitive
plus, im positive i have more flexibility using python
if you can sell me, i'll consider it because ive been doing flask for a solid year now and i've produced 3 complete applications
At first everything seems unintuitive but later when you use it daily it really get handy
therefore im solid in flask
Great ๐ฅ
well, i didnt find spring boot kinda cool but its so bulky to me i feel like
What exactly those applications are used for ?
xD i cant lie they are trash, just crud but i guess its the most that flask is required to display the main features of flask
im curious now because im building a actual applicaiton indented for the market
i feel like i should try spring boot
but idk, which one do you personally reccomend
I think you should consider those technologies because most of the companies shifted there backends written in some other languages to java based and .net technologies. That's why I'm saying to use those.
which one do you think would be the best
in your opinion
im hoping you say spring boot becasue i cant stand c#
According to me each tech stack has its benefits and cons, like the learning curve and support. Tech giant use java and .net because of there support by Oracle and Microsoft.
well, i dont have a oracle or azure cloud services
XD yeah, you can go with spring boot, even I'm also thinking to learn spring boot for upcoming projects.
man this is such a huge leap of faith, im hoping you know that
There's no need to have such services ๐
like ive done so much work within flask its insane
making a transfer is gonna be huge
i'll do it if it benifits me
Look I haved worked with j2ee ecosystem and did some projects on spring as well, but it's 5 years back when I did those. Now I have to start it again as things have changed now
What exactly you're building?
im building a ai based note-taking suite
on the fly kinda thing
another reason for python
anyone ?
the best java has to offer for ai is deep java library
Okay, then you can use firebase for db and create a background service for the ai part
i was hoping to handle that using the flask server
Anyone have any experience using Apple M1 for development specially when deploying to x86 Linux Architecture?
System Monitoring Webapp build using FastAPI
A simple System Monitoring WebApp!
Tech Stack used -> FastAPI, JS and cgi-programming
Github link -> https://lnkd.in/dgkW2RCe
(Give a star if you like...
Some. Depending on what you use, docker is your friend here.
It's just that most cloud platforms today are on x86 architecture so arm is pretty new to the space and was wondering if there will be any issues with libraries as in the past I faced issues before in a team that used Linux as their development machines where some libraries behaved differently on Mac and needed special tweaks in our docker scripts to be able to run correctly!
For example PyTorch is a big miss on M1.
I see when most people talk about Python development on M1, I feel like they are talking to the Junior developers that are trying to create a ToDo list. Yet as you get deeper the gap becomes bigger!
Another example not related to M1 but to macOS is that Apple stopped supporting "tap" drivers for VPN's which made our IT department have to switch to "tun" drivers so everyone can access the VPN!
It will only matter for things that are compiled. For instance, PyTorch isn't pure python afaik.
And the m1 is so new, but at end of day it is still ARM underneath (ARM 8 iirc). I've run into some problems with dependencies not working on M1s and .. well, will just have to wait for them to catch up.
It feels like over time Apple will soon start blocking a lot of things and lock things only to their frameworks!
I mean, sure I guess. They do love their walled gardens.
They also dropped a shit ton of ports for a while and brought them back to newest laptops and called it innovation haha.
@warm igloo Are you on M1?
Nah, avoiding it for now, but we've had issues at work with a client or two because of it.
Can you explain?
I just started converting a personal project to all docker containers. My containers are aarch64
But running on an M1 mac
buildx is nice for this
We have a client having issues getting the OSS they have built a company around running on a M1. We're working on it with them a little, but its not exactly an emergency cause sure devs can't run it on an M1 but none of their clients are trying to get it running on that hardware for real. So it'll eventually get fixed.
So for now we're just not buying M1s if new folks join (and we're hiring quite a bit). Eventually maybe, but I always like waiting out new things from Apple anyway.
If I have my way, I'll be leaving my Mac behind anyway and going to a Linux dev machine which I haven't used professionally since OSX debuted.
I mean: I use Linux daily, just not as my dev machine.
Yea I've been using macOS for a long time now, but after all this Apple Silicon stuff I started to think the server space isn't going to catch up any time soon. And this makes maintenance issues as arm architecture has to be supported. So I sold my MacBook Pro and have been working on a Linux box for a couple of months now and its been smooth sailing TBH. Yet I was also looking at WSL2 specially on Windows 11 with Linux GUI apps and GPU pass-through looks really nice!
The only thing I like about the new MacBook's so far is the battery life and how quite they are!
I need help with Django in #help-avocado
What the best Library for Web Develop? (Atleast for beginner)
hi, anyone knows how to check when was a page's code changed last?
basically, i have a url from a specific, high profile page
and a little bit of code was added
and if i can confirm the date it was added, i may make a lot of money out of it. so, anyone knows?
can i check the code with wayback? i thought it was mostly to check how a page looks
This reminds me a Digimon from the start of the Digimon Movie.
hello
i am using tailwinds css
to make my website
i want to replace
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
class="w-10 h-10 text-white p-2 bg-indigo-500 rounded-full"
viewBox="0 0 24 24"
>
<path
d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"
></path>
</svg>
the tailblocks stock image
with this
where should i?\
oh nvm
figured it
oit
out*
im missing something. do you want peoples back end for any time in history? ya that would make you rich
i mean you could compare the source code for the frontend pages thru wayback
anyone know why my navbar at the top does not fully show up on mobile
computer:
Mobile:
code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="/">Home</a>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="/bin">Lowest BIN</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/username">Username checker</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/thesaurus">Thesaurus</a>
</li>
</ul>
</div>
</nav>
<p></p>
<h1 style="text-align:center;font-family:Goudy Stout">
<font color = "#003078">
{% block heading %}{% endblock %}
</font>
</h1>
{% block content %}
{% endblock %}
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
For fastapi testing, how do you generate responses via schemas?
or any good tutorials for testing fatsapis beyond the docs?
jinja2.exceptions.UndefinedError: 'form' is undefined
<!-- Form rendering is simple and easy if using bootstrap -->
<div class="col-md-6 ml-5">
{{wtf.quick_form(form)}}
</div>
anyone know why I get this error?
I did do {% import "bootstrap/wtf.html" as wtf %}
but still get this error
headers = {'Authorization': 'Bearer ' + accessToken, 'Content-Type': 'application/json'} r = requests.post('https://www.googleapis.com/upload/drive/v3/files?uploadType=media' , headers=headers, files={"test2.pdf":fileData.getvalue()})
I am trying to upload a bytesIO file object to google drive as pdf
It is being uploaded in this wrong format ... but file size is correct
I can't figure out in which format should i convert ... any idea??
Thanks
Hi everyone, is there anyone who works with FastAPI?
I am working on the development of register-api for that I use fastapi, Python-Keycloak and docker, I am currently learning middleware and I am interested in where you would use middleware and why?
I hope the question is not stupid ๐
Hey . I have been using it for around 6 months now.
this is the view that creates an account
@api_view(["POST"])
def signUp(request):
data = request.data
username = data["username"]
email = data["email"]
password = data["password"]
user = User.objects.create_user(username=username,
email=email,
password=password)
return Response("Account Created!")
im getting an error saying 403 forbidden
I need some quick help
need someone to register an account on my website for this new authentication, ive run out of gmail accounts to test myself
please ping me for the link
use temp-mail
just remove the previous users from ur database
im on my mobile rn
Its in my about me incase you can help test
like this: ```html
<script src="utils.js" />
i mean, its first element
Failed to load resource: the server responded with a status of 404 ()
Click it and check if the location is correct
I heard that python is not that much used in web dev, m I wrong?
Click it in the network tab. You may need to refresh
aright i changed it, now this is there Uncaught SyntaxError: Unexpected token '<'
because hashes don't get sent to the server.
You're basically asking for the same page
i want to add an image on the blank right side
where can i add the code
i will send you the html and css
<img style="float: right">
or if the left side is in a div, add a inline-block div after it.
Are you using flask?
yes
use <script src="{{ url_for('static', "js/utils.js') }}" />
assuming utils.js is in static/js/utils.js
it came on top
You didn't make it inline-block, and you didn't put it on the bottom
this is assuming you aren't using any fancy flexboxes
put the img tag after the article tag
and style it with style="display: inline-block;"
const chat = document.getElementById('myChart').getContext('2d');
jinja2.exceptions.TemplateSyntaxError: expected token ',', got 'chat'
i have to go
i will come back later
You wrote javascript when the template language expects python
not working
this is the code ( it doesnt have the things you asked to add)
can you tell where exactly should i add and what to add
should be after </article>
What's with </aside>?
That's not a valid tag
and you never open it
aside is a valid tag though
It's still never opened
But it's valid ๐
Dang. It isn't even html5. it's old
!voiceverify
Is it easier to use python to write a web app that gathers data from clients
or is it easier to do that with Google Apps Script?
The website already has an front-end and they used React
aside was added to the specs as part of html5
https://html.com/document/#New_Semantic_Tags_Added_by_HTML5
does border bottem transition work in css
Anyone who knows threaded data dumping?
Hey, can someone send me a config file for the daphne startup file, which would work well with django?
Because what I have doesn't seem to work:
#!/bin/bash
NAME="project-daphne" # Name of the application
DJANGODIR=/home/admin/code/project/mysite# Django project directory
DJANGOENVDIR=/home/admin/code/project/env # Django project env
echo "Starting $NAME as `whoami`"
# Activate the virtual environment
cd $DJANGODIR
source /home/admin/code/project/env/bin/activate
source /home/admin/code/project/mysite/.env
export PYTHONPATH=$DJANGODIR:$PYTHONPATH
# Start daphne
exec ${DJANGOENVDIR}/bin/daphne -u /home/admin/code/project/env/run/daphne.sock --access-log - --proxy-headers mysite.asgi:application
Depends. What sort of site?
But SSL can often be free via LetsEncrypt depending on your setup.
our org is paying for a wordpress host, the company hosting is not doing website maintenance
I'm only paying like 10$ per year for my ssl certificates
I feel like they're basically stealing from you for the SSL since you can get it free. The hosting fee is okay at $20 a month but depending on the host plan, you could be on shared hosting which is pretty "meh". So again depends on all that you get for that $20.
There are cheaper ways. There are more expensive ways too.
thanks, ill probably let it slide as this company that we are hosting from built the website using wordpress. I have been able to get away with updating the site myself but prob isnt worth burning a bridge incase something horrible goes wrong with the site, as I'm swamped with work and itd be cheaper to outsource to them in the future
just wanted to make sure were werent getting horribly shafted
Some genius here that already had contact with DRF and NGINX JWT Authentication (subrequest calls against auth service). Please also see:
Could someone please recommend an authentication system for a web app I'm building? I don't know whether I should use flask-login or do my own implementation. I feel like I might learn more doing it myself, but I'm worried about security and I probably shouldn't reinvent the wheel.
If I am to go with flask-login, should I learn and use flask-sqlalchemy or use plain old sqlalchemy instead (or even sqlite3 or similar)? Online, I've found some contradicting info on this from some pretty reputable sources.
Thanks in advance!
hello im bad at coding so you should probably ignore this but personally i use a firebase database to get and post the users password and username but i encode them before post request
That's completely up to you. If you prefer the apis one or the other provides, then use that.
As for the login, it's pretty easy to get it secure, just hash things with a proper algorithm (like bcrypt for passwords)
I wouldn't use a library myself
where would you normlly store user data
In a database like postgres
Ok, thanks! Would you recommend using sqlalchemy or sqlite3/aiosqlite? I don't want to go down the wrong route and shoot myself in the foot, and I'm still relatively new to SQL
interesting i prefer not static databse
I'd use sqlite only if it's a rather small project
i prefer json style database
i know its not a good think but i find it more flexible in projects
You prefer NoSQL? I love relations myself.
yh noSQL i started learning databases a few days ago and i didnt do too much sql before i realised it was really easy but the flexibilty was low
I'd hardly say it's inflexible, you can do quite a lot with SQL databases
I doubt it'll ever end up as anything big ||(i never actually finish anything)||, but it's good to have scalability, I guess? What's the issue with using sqlite?
interesting
nothing
its weird how it works for me
so i go noSQL
Sqlite stores everything in a single file, so it can get messy and slow with large amounts of data, but if you don't expect to have too much, sqlite is fine
wait what if i have a website to do this and im using sql doesnt that mean i need a special hosting plan
according to mmy website host its harder to host dynamic websites than static ones
You'd need that for a website with a server too
That's correct, yes
yh so thats among few reasons why i preffer no SQL but all in all SQL is much better in performance
if you use a firebase instance no it doesnt really need it
firebase
That's false. It's just that firebase is hosting it for you.
yes thats what i mean
But there are sql hosting plans like that, such as https://supabase.io
so i dont have to set it up myslelf
wait wait wait wait wait
where were you all these dayss
thank you so much
bruhhhhhhhhhh
i thought these never existed
im too used to noSQL to go to this but its on my learning chat
Yeah, dynamic websites require code execution whereas static websites are just serving files
oh wait, I've replied ultra late
i blame bugcord
yes yes
no its fine
i hope you can make youre website in peace now
knowing ddifferent opinions on a topic
Thanks! I'll have a shot with sqlite
haave fun
...just checking, it is fine to use sqlite3 instead of aiosqlite, right? Do web apps have to be asynchronous?
Logically I feel like yes, they do, but I haven't seen any async syntax yet
again im bad at coding so i will think that async means running diff processes at once
but im not the guy for the sql questions
gn my kind sir
Thanks a lot!
Do web apps have to be asynchronous?
No, but they typically are
How does Flask handle that? I haven't seen any asynchronous syntax, like with Discord bots for example
Guys - I'm really in two minds of whether I should use Supabase with FastAPI - Or I should completely ditch Supabase and build authentication and stuff directly in FastAPI
Can someone come with some inputs in that decision? โค๏ธ
That's really up to you. Do you like Supabase's way of handling auth, or would you prefer rolling custom?
I haven't worked a lot with Supabase - But I suppose they take a lot of the headaches out of it?
They do make it slightly easier, so here's my input. If you want to go with OAuth providers or magic links, go with Supabase Auth. If you'd rather use the traditional email/password approach, roll your own as per the FastAPI tutorial.
Alright - Thanks. I think I'll go with Supabase then. Hopefully changing it won't be too hard, if I decide so (even though I've heard otherwise)
so what should be there?
It depends
ah, i still cant import it
whats wrooooooooong
i am stuck on this for like 3 days
Post your template file
I don't think browser supports exports
Everything just gets added to the global namespace
You also shouldn't mix src with a script body
It depends on what utils does
Can't use imports in the browser.
You'll need to build it using a tool like webpack
To export functions with that, just set it on window
uh, what?
window.foo = foo;
where should i put that?
ahh, i am just trying to implement this graph https://www.chartjs.org/docs/latest/samples/line/line.html?fbclid=IwAR0Kerue8MBqr02qY_F4H7xjowNXdGRteeaqP46oRiCi3dv_bh4-RI3o4Bo to my code
Open source HTML5 Charts for your website
why its so complicated
Use the cdn. https://www.jsdelivr.com/package/npm/chart.js
No webpack or node/npm needed
I need help with this please help with this web development help
can you paste the full code please? the basic idea is to have chartjs's utils.js source (you can find it by searching utils on their docs) and put it in a file. Then in your previous <script> where you made the graph you have to use import to import the file and have the module accessible in Utils. It won't work if you only have a single <script src=.../>
why print statements inside django doesnt print anything , what makes em not print stuffs
hello
does anyone here use a webbuilder then externally change the code by adding in javascript file
wait what if i wanna code an auth system that sends post and get request to a firebase databases .Is this a good idea?
ask away
Can someone explain me why should one use celery +rabbitmq instead of using just fastapi background task
celery master that takes orders can be one Server. Master just puts the task in a job queue.
and Workers that process tasks can be N amount of other servers. They just watch the queue and complete the tasks based on the availability
workload quite good distributed between multiple servers. Better scalability for serious business ๐
Plus all the code written for the background task being as comfortable as possible.
With reporting its intermediate progress and results.
Thanks a lot for your response, so It would be nice to use celery+rabbitmq, right?
quite. I use right now
Would you mind sharing the celery part with me?
yeah, I would mind. I use it at work
Okay, I see. Thanks
I could rip the necessary code parts though
hmm, too much to rip
or not
anyway, the core is folder with django settings
from .celery import REDIS_HOST_RESULT, REDIS_PASS
# django setting.
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": f"redis://{REDIS_HOST_RESULT}:6379/0",
"OPTIONS": {
"PASSOWRD": REDIS_PASS,
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"IGNORE_EXCEPTIONS": True,
},
}
}
CELERY_TASK_TRACK_STARTED = True
CELERY_TASK_TIME_LIMIT = 30 * 60
file celery.py
import os
from celery import Celery
import time
import secrets
import subprocess
import sys
import redis
import base64
import json
# from .settings import CELERY_CACHE_BACKEND
# Set the default Django settings module for the 'celery' program.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings")
from dotenv import load_dotenv
from pathlib import Path
import secrets
import contextlib
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
load_dotenv(os.path.join(BASE_DIR, ".env"))
REDIS_PASS = os.environ["password"]
REDIS_HOST_QUEUE = os.environ["queue"]
REDIS_HOST_RESULT = os.environ["result"]
# celery setting.
CELERY_CACHE_BACKEND = f"redis://:{REDIS_PASS}@{REDIS_HOST_QUEUE}:6379/0" # 'default'
app = Celery("core", broker=CELERY_CACHE_BACKEND)
app.config_from_object("django.conf:settings", namespace="CELERY")
REDIS_RESULT_FULL_ADDRESS = f"redis://:{REDIS_PASS}@{REDIS_HOST_RESULT}:6379/0"
app.conf.result_backend = REDIS_RESULT_FULL_ADDRESS
app.autodiscover_tasks()
# custom redis
redis_conn = redis.Redis(host=REDIS_HOST_RESULT, password=REDIS_PASS, port=6379, db=0)
@app.task(bind=True)
def debug_task(self):
print("starting task")
time.sleep(1)
self.update_state(state="PROGRESS")
return "123"
you add tasks to it in your views
from core.celery import debug_task
@api_view(["GET"])
def get_ping(request):
task = debug_task.delay()
return Response({"message": "pong!"})
master and worker nodes are initialized differently at different servers, but essentially to the same project
master:
venv/bin/gunicorn core.wsgi -b 0.0.0.0:8000
slave:
venv/bin/celery -A core worker -l INFO
@foggy bramble boop
Huge thanks, for your help, I really appreciate
u a welcome. https://docs.celeryproject.org/en/stable/getting-started/introduction.html
official documentation is more than enough to get started
I used only official docs
using RabbitMQ is more preferable than Redis, but I just used already Redis before so decided to less learn a bit
That's fine
Ok can someone help me learn we development I need help iam a lil new
Hi all. I am trying to make a flask app where I have toggle button which when clicked will change an entry in the database. How would I go about doing that?
All I can do currently is take input from a (text) form and change database based on that.
I am trying to make a part of my website automatically change each day. I am trying to pass the home page function a list but dont know if its possible. Would storing the list as a file be the best option
Thanks, this certainly helps! But I am trying to get a toggle button instead of two separate buttons.
yeah
Do i need to create database table manually in mysql database or below code in fastapi will create the database table if it doesn't exist?
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
email = Column(String, unique=True, index=True)
hashed_password = Column(String)
is_active = Column(Boolean, default=True)
items = relationship("Item", back_populates="owner")
yeye i gotchu, fire fit btw
Is knowing HTML CSS and JS useful for web development or can you do without em'?
In the context of Python frameworks*
short answer- yes
Dont spare me any details if you can
long answer, you always need some sort of css or html, in python context. js is needed if you need to get html information but for you, its not needed as python is handling everything through the jinja templating. css is sometimes needed but nowadays we have things like bootstrap, tailwind and bulma where you can produce bare css with just defining class names. html is needed to structure your site as python doesnt have a frontend framework but if you use react then you'll need the most bare amount of html otherwise if you're doing backend serving then you need to know html and css but then again
@swift wren when can we start ?
as soon as you ask the question
@swift wren Huh, so if you know Jinja and Bootstrap, HTML will do fine?
if you're using jinja to render your html, the template is gonna be static so yeah basically
I've been looking at tutorials and they always end up copying and pasting Gibbirish-looking blocks of code made out of the aforementioned languages
@swift wren Oh, thats pretty limiting though, no?
learn flask. the best webdev framework imo
and i've worked with django and spring boot, spring boot is fire compared to django but its java based and java doesnt have a whole lot of python-esk toolkit
for me personally in a certain circumstance
but still, flask has been the easiest and to-the-point framework
its so good
and it has like insane extension modules
Dont you reckon that if, at some point, you'll want a career in web development, you're better off just doing JS with Node.JS?
justify that
Hm?
justify it, why do you think that
db.create_all
meta.create_all(engine) does the job
Yea thanx i just missed to type it
Because if websites are built out of HTML, CSS and JS, those have the homefield advantage so to speak.
What I mean by that is that, if you're new to the field, the learning curve will be a lot more linear.
You make the template with HTML
Stylize them with CSS
and make interactions with JS
whereas with Python you'll first need to learn Python, and then Flask, and while you learn Flask you'll need to learn Jinja and bootstrap
So essentially you're first learning the backend, and then the frontend
Yea
Sorry about the block of text
thats not correct
i can see your perspective and its personal as well but its just fallacy talking about learning curves as node.js and js in general has a steeper learning curve than flask and jinja
the complexity difficulty is abhorrent compared to node.js when producing complex web applications
with js you need to require like 12 different modules where as a simple flask import gives you all the tools necessary to produce a enterprise application
Hm, I honestly dont know the slightest thing about Node.js, so I'll take your word for it
So in that case, wouldn't you agree that its still easier to learn HTML, then CSS, then JS and then* if you want, Flask or Django?
i would never use node
Yeah, no node
i would never use express or http. just digusting tbh, im using react tho, react is kinda fire cos i hate writing html and i have to use axios to make requests.
i've produced mad applicaitons using flask and html
but now im using flask as a api backend and using react for frontend
makes everything lighter and faster
Node.js uses react too no?
no react uses js
Oh
wait
the thing is node is a runtime for js
there is v8 engine and there is node.js engine
but node comes pre installed with http library which gives node its label
but node.js is local js runtime
Woah you lost me, this is way beyond my bracket of knowledge
Its interesting to know there are alternatives to JS and stuff, didnt know
dw, js is the most sacriligious language ever. id reccomend you learn flask straight up. just generally stay away from js.
js is a bunch of rules that much be followed by a runtime
where has python, cpp and java have thier own compilers and interpreters
ok iam ready what software do i need
idfk
man i thought u was gone help me
hey could i jump in and ask a question?
yea
ok,
so i need to build a web project that generates word reports for this department at work
it takes in input for the document through forms asking the various questions
the project is supposed to have these features:
- user logins and different privileges depending on rank,
- allow multiple people to work on the same project at the same time, and
- have a log of what changes were made and by whom
so I know a HTML and CSS, plus a little bit of PHP
the main question is should i build the backend of this in PHP or Django or something like Go?
go and see which library/framework looks easier to write
imo php is the easier out of those options
but im a huge advocate for flask
you can make whole applications in just one file
yeah, this guy at work says that Django and flask should be pretty useful
plus i know some python already
@swift wren can u hit me in the dm or help me here or some one i need to know how to do this or does any one know how to make a sneaker bot i need this done before December
if you're a beginner, django is a death wish
flask is the be all and end all for beginner and intermediate developers
also advance but im sure they venture way further away from vanilla flask
you should be able to figure it out
django and flask are wsgi
its not a software its a frameowrk
all the logic comes internally, there isnt really any framework that does things for you
makes sense
let me look into flask some more
Hey is there a way I can (using a Flash backend) update colours in CSS?
not css but js.
I want to avoid specifying colour in style on all HTML and then passing colour variable.
thanks @swift wren
@grave nexus
From my experience I can say that Django was indeed too much for a beginner, but Flask was easy to learn and very effective. Not sure how to do dynamic updates (e.g. when 2 people work on a document you can see the other person type like in Google Docs), but everything you mentioned is easily doable. Setting up models in quite easy too as long as you don't have too complex relationships.
As in using JS to write to update the CSS>
nah its just values
ok, thanks
plus i'm sure i could come through and ask if i get seriously stuck
If you want to link Python and JS I recommend you expose your functions using a library like Eel, I don't think Flask has built-in functionality for that.
Hey @swift wren!
It looks like you tried to attach file type(s) that we do not allow (.html). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a.
Feel free to ask in #community-meta if you think this is a mistake.
That would require hard-coding every value though?
it was 3am, i was done with life. just wanted it finished
With Eel you can directly pass variables between JS and Python, just set up 2 functions and you're good.
but you could have a array with the color values and just index and feed that to the iteration
I have like no JS knowledge. All I know is I have my python backend which serves HTML templates which have associated colours defined in CSS.
why would you use js
Yes I see that I can manually specify style variables everywhere and pass a variable for the colour that way. Wouldn't it be more logical to update the CSS somehow?
Something like this? https://www.w3schools.com/css/css3_variables.asp
Yes, as I said you set up a JS function that accepts a variable and modifies the CSS of an element, expose that function to the Python side using Eel and on the Python side have an exposed function that sends the color variable over to the JS side. https://github.com/ChrisKnott/Eel
I'm not sure if this will work, but I recommend you give it a try. If not, you might have to stick with hardcoding.
You might also be able to use https://htmx.org/
So know one can tech me how to code or make a sneaker bot ?
im being very helpful #WILL BE A HELPER SOON XD
no, no one can teach you to code through a chat window, but there are many tutorials to start with online. if youre just looking to buy sneakers then you might be underestimating the complexity of your task
iam looking to do all lot of things with coding thats just one of my goals
awesome, so you need an intro to programming in python course. i linked you to the lobby channel with pinned intro courses there @sharp valley
im confused as heck
yesterday my site worked perfect
today the background image wont show up
it's in the folder with all the other images but
but flask wont serve it
wait nvm
@solar obsidian, did you fix it?
yes but no
it turned out i replaced a css file which had a 1 at the end of the name
but i changed that and it's still looking for the file with a 1
@solar obsidian, hmmm... have you tried making any changes in your code itself, so that it's no longer looking for a file with a '1' at the end of its name??
if add a 1 to the end of the name it works
but i cannot find anywhere where it's referencing 1
ahhh it's a cache
chrome is showing the old css
now it works
@solar obsidian, yeah, try cleaning your cache and refreshing the page, see what happens
very nice ๐
ctrl+shift+r to refresh without cache.
If your networking debug tab is open, cache is disabled by default
in firefox at least
how do you make a debug tab
oh that just shows inspect element
well yeah it opens all that
how to execute console js through python?
How do I set the environment for flask
just downloaded yesterday using pip
?
Any one here
All I see is water
use environment variables.
in bash, it's as simple as FLASK_APP=your_app flask run
Hey everyone
@app.websocket("/")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
connection = mysql.connector.connect(host='localhost',
database='survey',
user='....',
password='...')
data = "select Question_answer from user_questions where question_id = 2"
data_cursor = connection.cursor()
data_cursor.execute(data)
query_data= data_cursor.fetchall()
df = pd.DataFrame( [[ij for ij in i] for i in query_data] )
df.rename(columns={0: 'Name', 1: 'Players'}, inplace=True)
df['counts'] = df['Name'].map(df['Name'].value_counts())
structured_df=df.drop_duplicates(subset=['Name'])
data = structured_df.to_json(orient='records')
print(data)
time.sleep(10)
await websocket.send_text(data)
what I'm trying to do is, keep the connection alive so when new data comes, It sends it to the server to update, however what's happening is once I establish connection in this function it'll always be running HERE, only. I have another page, with a normal GET request, if I go there the data I'm sending in the other page won't be there bec it's stuck in this while loop
Yo i meant to ask since Idk where webscraping and API fetching goes in but, does anybody know public APIs with job offers?
stupid question here but cant you just open the connection when you need it ?
scraping and API are super different right ? but indeed is easy to scrape and they dont care if youre not republishing as far as i can remember, but check with them first
hmmmm check if I need to open a connection means I'll wait for something, something like a GET request right? is that do-able inside a websocket function?
no idea. but read data, close data, prompt user, open data again to write... break up the function maybe..
Yeah webscraping is kinda like building your own API over a website while API fetching is just taking the responses according to your request query parameters
Thanks
I am front end developer with 1 year of experience and i am new to python.
I use python because i am working on side project which depends on open source which built on python
my question what is the right path to become python web developer.
first getting comfortable at python basics, then going through some crash course on the way websites work (even some front-end developers with experience dont have a clear idea), then choosing python library for full stack development and learning it, while making some simple test websites
most prevalent ones are django and flask
you can go with either one, personally i'd say flask is easier
you can find free python course on udemy
should be first link when you just search "free python"
i know there are some good ones on yt
find some playlist
literally search "how websites work"
and find one that goes at least semi in depth
thanks
hi! i'm using django for a small project... should I reuse the same venv for other projects too ? or does each project need a new venv?
It's best to make a venv for each project
Typically, you can put the venv directory inside the directory in which you hold the code, then exclude it from git with your .gitignore file.
If you do it that way, VS Code (and probably other editors) will detect the venv as being in the project and use it as the python interpreter.
it seems to get confused and if I activate one venv, then try to switch project to another it saying that python or other modules aren't found
so you need to install all the requirements and packages fresh on every venv or can they share?
Its best if you do it fresh for each project, that way if you need to change modules in your venv you don't mess with any of the other projects
If you have your requirements saved to a file, you can have pip load them up all at once by running pip -r <filename>
ok thanks! my projects folder are a bit all over the place good reason to tidy it up
i used a list of like ~400 packages that were listed in anaconda environment so it took a long time to set up the one venv
Definitely a good habit to get into! I make a directory called "Code" and put all of my projects in there. Each project has a git repo associated with it, with the requirements.txt file so it's easy to set up again later.
but maybe only installing those in use would be better
Yeah, that could take a while. Definitely better to keep clean!
i've made it a bit too complicated like.. i have set up the one /code/venv ... then set up some folders like /code/python/frameworks/django/project/files/etc
should be simpler!
Hello guys , How can I get a free domain for my website ?
Unlikely if you want a decent top level domain, but you could try googling it. My guess is you'll get less than good results.
i copied a html file and renamed it
but flask isn't serving the css or images
for that page
but it serves just fine for the original
how to put range here ??
Is there anyway to set-up django to automatically set the size of admin formfields based on the model field's max-length? Instead of manually adjusting it for every charfield?
Not 100% sure, but google django template loops. You can do stuff like this if forloop.counter|divisibleby:5
And there are others
okay thx ill do it rightnow
BRUH
it doesn't serve anything
even if i set it to the EXACT same html file
it doesn't serve the images or css
just this page
everything else works fine
Did you look at how to serve static files with flask?
You have to serve them differently than templates if I recall
i put the htmls in the templates
and the assets such as images and css in static
everything works
but not this one page
even if i serve the same html file
maybe relative paths or something
is the html file in a different path relative to the static stuff
oh hard refresh in the browser so you don't use cache
i have
even opened other browsers
@app.route("/dashboard")
async def dashboard():
if not await discord.authorized:
return redirect(url_for("login"))
user_guilds = await discord.fetch_guilds()
guild_count = await ipc_client.request("get_guild_count")
guild_ids = await ipc_client.request("get_guild_ids")
guilds = []
for guild in user_guilds:
if guild.permissions.administrator:
guild.class_color = "green-border" if guild.id in guild_ids else "red-border"
guilds.append(guild)
guilds.sort(key = lambda x: x.class_color == "red-border")
name = (await discord.fetch_user()).name
return await render_template("dashboard.html", guild_count = guild_count, guilds = guilds, username=name)
@app.route("/dashboard/<int:guild_id>")
async def dashboard_server(guild_id):
if not await discord.authorized:
return redirect(url_for("login"))
guild = await ipc_client.request("get_guild", guild_id = guild_id)
if guild is None:
return redirect(f'https://discord.com/oauth2/authorize?&client_id={app.config["DISCORD_CLIENT_ID"]}&scope=bot&permissions=8&guild_id={guild_id}&response_type=code&redirect_uri={app.config["DISCORD_REDIRECT_URI"]}')
return await render_template("dashboard.html")``` take a look
ignore the fact i dont send the variables
that shouldn't be a problem
and what's the template?
presumably it has paths to css and images and that's what isn't loading, right?
yeah
but it's the same html requesting the same css
unless it's because it's dashboard/guild_id
I'd say if the template needs variables, you should pass them. and you're sure the first one isn't cached and that's why it "works"
i tried passing
same thing
ahhh dang i was right
when you view source on both does it show that it's looking for css in the same place
it's looking for the folder dashboard/static
just because that's the url why does it have to
i wish i could make it relative to the py file
i did it thx
the best
I think there is a way to serve all static from one location and point everything at that. Not sure how flask does that now, since I mostly live in the django world.
Thanks
Using dockerfile for the first time.. when running the command docker-compose up I get the error:
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
Yet when I run django-admin --version I get proper feedback.. any ideas anyone?
did you specify correctly the context in docker-compose.yml?
Hmm, I'm following the Django for professionals book and this is the yml file they listed:
version: '3.8'
services:
web:
build: .
command: python /code/manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- 8000:8000
confusing
do you actually install python modules in your docker container?
can you show Dockerfile?
Sure
# Pull base image
FROM python:3.9.6
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# Set work directory
WORKDIR /code
# Install dependencies
COPY Pipfile Pipfile.lock /code/
RUN pip3 install pipenv && pipenv install --system
# Copy project
COPY . /code/
check in the container, if your django is installed
I am not sure what pipenv install does
It's installing what is in the pipfile
do you have django in the pipfile
But...it makes a virtual environment
yes
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"
[packages]
django = "*"
[dev-packages]
[requires]
python_version = "3.9"
so you can activate it in your build or try changing your command to:
pipenv run python ...
or at the end of your docker file you can try:
pipenv shell to activate it
I tried that, I wonder if this has anything to do with it:
When I run django-admin --version I get this at the end
Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.).
I do not know if it is related, but it is a problem
I would not use pipenv in general
simple venv + pip-tools work better for me
frustrated by pipenv or just generally better to go with a container?
My take is if you're using a container, you already have an isolated environment, so no need for the virtualenv
pipenv combines pip and virtualenv
you can just install the requirements directly with pip and and skip the virtualenv, but yes, you probably need to use settings as well.
I typically use poetry for everything, but when in containers, I disable the creation of a venv by poetry
frustrated, for sure. Docker use in the cases, if I need to have multiple services running a the same time, such as django, db, frontend, redis, nginx etc. pip complains, if not using venv, so I do it just to avoid warnings
this is the code
any ideas?
Where to ask html javascript?
this channel? or off topic channel?
str='[(AA01, None), (AA02, P639997(3))]'```
How to turn this string to json in js?
Question about Flask
I notice people hardcode IPs following the pattern of having Config classes in config.py
Wouldn't it be better to programmatically get the IP address?
i'm looking to build a website. I've decided to use React, Next.js, and Express for it. It will be a simple site for groups to vote on polls, but also involve using locations (google API?). I'm very new to building websites and web apps so I was wondering if anyone has advice for:
1.What database and any other specific frameworks (e.g.., Express) I should use
2.what steps I could/should take from start to finish (I'm having trouble figuring out how to get started)
- firstly I would start from thinking to remove React or Next.js, because they fulfill the same roles and there is no point to have them both at the same time
- if you are going to use database, PostgreSQL database will work in average for everything backend related
- a) Yeah, probably starting from choosing technologies could be good
b) then it would be a good place to start from "Use cases"
writing/thinking which interacting scenarios user will have with your web site
c) Optionally extending, use cases how they would be looking in data flow diagramms, how use cases would affect data flows in your applications with programming parts
d) modelling which tables and relationship your database will have
f) architecture, which servers and what's installed on them? how independent applications will interact with each other?
e) how your web site will look like, design, user interface
g) then planning implementation details / or just already going to coding.
for additional information I could recommend, System Analysis & Design 6th edition by Dennis, Wixom, Roth
@inland oak hey bro have u ever used cpanel?
ohk
GUI to contorl server? urgh.
never going to use it, because it is against of InfrastructureAsCode principles
oh
It could be fine for you, it looks like it simplifying things for regular user
but I chose being DevOps as second specialization, this specialization has certain philosophies to follow
Question
What happens if you make an HTTP request during handling of a request in a Flask route function?
Would the entire application pause?
if u are writing in Sync (default), yes.
if you are writing Async, u have more flexibility i think (example, handle additional 100 requests at the same time instead of in sequence)
Also you could be using.... Multithreading or multiprocessing to handle the flow differently
I see :) thank you!
Question, how do geolocation APIs that once GET'd get you your city, etc, actually know your city?
in both choices (but not in Sync), you could fire your additional request in a "Fire and forget" mode for example
it is inited and will be handler later or in parallel, but you already go for other stuff in your main request body
That's quite useful to know, thank you very much!
Bumping question: how do geolocation APIs that once GET'd get you your city, etc, actually know your city?
it depends on which API you mean, but if you mean APIs that do it by IP address, then answer is...
every IP address belongs to some Internet Service Provider company, and every static IP is already accounted in each town is it located.
So.... with matching your IP address, we could point to a region or town where this IP address is used. In most cases it is enough to locate city.
So basically they have access to database where public IP addreses are registered
If we talk about Mobile Apps, then applications could be having access to your geolocating modules for more precise coordinates
Awesome! Thank you very much :))
Let me bring you an example
That api is used by this module
Which works like this
simple_geoip = SimpleGeoIP(app)
@app.route('/')
def test():
# Retrieve geoip data for the given requester
geoip_data = simple_geoip.get_geoip_data()
return jsonify(data=geoip_data)
It returns this:
{
"ip": "8.8.8.8",
"location": {
"country": "US",
"region": "California",
"city": "Mountain View",
"lat": 37.40599,
"lng": -122.078514,
"postalCode": "94043",
"timezone": "-08:00"
}
}
it is IP address locator, which i mentioed first
but if you mean APIs that do it by IP address, then answer is
So that'd be that type of API?
they provide access to their database with their API
so you could use their data, but did not have abilities to download their database
Software as a Service (SaaS)
Awesome, how do these guys access to such database of public IPs?
No idea. As first and simpliest idea, they copied from other guys who identified people
It is all coming, where the first person found the data about it? ๐ค
no idea.
Ohh, I see
Ok, so I make a HTTP GET to that API with their API key
They receive it
And they get my IP from my HTTP GET request
I was able to find some public databases regarding it before btw
just a matter of googling
Now, once they get my IP, the obtained IP is public right?
The IP of mine that figures in the HTTP headers
yes they obtain your public IP