#web-development
2 messages ยท Page 215 of 1
wait i need to encode that too?
response = response.encode() + data.encode()
AttributeError: 'bytes' object has no attribute 'encode'
thats what i thought will happen
let me search how to convert byte to base64
https://stackabuse.com/encoding-and-decoding-base64-strings-in-python/
import base64
encoded = base64.b64encode(b'data to be encoded')
print(encoded)
can base64 be concatenated with string object?
sure
!eval
import base64
encoded = base64.b64encode(b'data to be encoded')
print(encoded)
@inland oak :white_check_mark: Your eval job has completed with return code 0.
b'ZGF0YSB0byBiZSBlbmNvZGVk'
or may be not
response += base64.b64encode(data)
TypeError: can only concatenate str (not "bytes") to str
!eval
import base64
encoded = (base64.b64encode(b'data to be encoded')).decode("utf-8")
print(encoded)
@inland oak :white_check_mark: Your eval job has completed with return code 0.
ZGF0YSB0byBiZSBlbmNvZGVk
wait
here you go
yes
where does the icon display
like on leftmost point of the website tab?
@inland oak
in the tabs
it isn't displaying
open Network tab of chrome tools
with open(f"htdocs/{filename}", "rb") as f:
data = f.read()
response += f"Content-Length: {len(data)}\nContent-Type: image/x-icon\n\n"
response += (base64.b64encode(data)).decode('utf-8')
print(response)
client_connection.sendall(response.encode())
@inland oak
$ curl -v http://www.columbia.edu/favicon.ico --output 123.txt
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying 128.59.105.24:80...
* TCP_NODELAY set
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Connected to www.columbia.edu (128.59.105.24) port 80 (#0)
> GET /favicon.ico HTTP/1.1
> Host: www.columbia.edu
> User-Agent: curl/7.68.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Date: Sat, 05 Feb 2022 12:42:54 GMT
< Server: Apache
< Last-Modified: Tue, 09 Jan 2018 21:34:31 GMT
< Accept-Ranges: bytes
< Content-Length: 5430
< Vary: User-Agent
< Content-Type: image/x-icon
< Set-Cookie: BIGipServer~CUIT~www.columbia.edu-80-pool=1311259520.20480.0000; expires=Sat, 05-Feb-2022 18:42:54 GMT; path=/; Httponly
<
{ [2816 bytes data]
100 5430 100 5430 0 0 11986 0 --:--:-- --:--:-- --:--:-- 11960
* Connection #0 to host www.columbia.edu left intact
okay?
the point is, we can play with curl to render the response in a detailed fashion what you need to send
so you can compare with what you are sending
do i need to send data cookie server
nah, certainly not
not this
i even specified the type in index.html
<head>
<meta charset="UTF-8">
<title>Index</title>
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"/>
</head>
ah wait
still not
even though it is x-icon
perhaps this could be some sort of help
>>> import requests
>>> resp = requests.get("http://www.columbia.edu/favicon.ico")
we can query in details what is in resp
resp.headers
resp.content
resp.text
dir(resp) what is existing in response
try to debug your thing to compare
render the resp.headers, resp.content, resp.text for your built thing
okay
@inland oak it seems like the favicon.ico sends a white image
even though it is this
these are my headers
{'Content-Type': 'image/x-icon', 'Content-Length': '1150'}
Woohoo. You are getting closer
btw, it is a task in university? Imagine you would be the only one who was able to pass it ๐
nah its not
i almost finished my own homework too. as part of self studies learning some stuff too.
if it was they probably would have listed some resources you know
nah
they teach how to learn on your own ;b
drop in the ocean, and swim
hmmmmm yess
i am for shit and giggles going through the book that teaches minimal viable package to wield golang
gods, it is quite good one in some things
its package managing system, where to publish package we need just to save to git repository? It is awesome!
hmm i ordered Effective C++ to improve my c++
too bad python publishing it not that easy
only for public repositories python publishing is easy
for private ones it would be a bit tougher
xD, too low level for me. Hopefully never going to touch C++ again.
we were teached for 2 years in university in C++
if c++ is too lowel then what is C
switched to C# without regrets
or assembly?
during university we were writing stuff even in assembly
a bit too much effort for simple program ;b
i am never gonna learn assembly
the only new language i will learn is haskell
and maybe do more c# and js
i wish to learn only web related stuff
alright now back to this
do you want the full code so you know you can check it on your own system?
nah, I think it is already enough for me, I need to finish my own studies
okay
i am gonna take this to stackoverflow then thanks for the help
and good luck in your studies
hi can someone help with something
i have to finish this for tommorow
but its not working
OperationalError at /admin/products/product/add/
no such table: main.auth_user__old
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/products/product/add/
Django Version: 2.1.5
Exception Type: OperationalError
Exception Value:
no such table: main.auth_user__old
Exception Location: C:\Users\ramia\PycharmProjects\PyShop\venv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 298
Python Executable: C:\Users\ramia\PycharmProjects\PyShop\venv\Scripts\python.exe
Python Version: 3.10.2
Python Path:
['C:\Users\ramia\PycharmProjects\PyShop',
'C:\Users\ramia\AppData\Local\Programs\Python\Python310\python310.zip',
'C:\Users\ramia\AppData\Local\Programs\Python\Python310\DLLs',
'C:\Users\ramia\AppData\Local\Programs\Python\Python310\lib',
'C:\Users\ramia\AppData\Local\Programs\Python\Python310',
'C:\Users\ramia\PycharmProjects\PyShop\venv',
'C:\Users\ramia\PycharmProjects\PyShop\venv\lib\site-packages']
this is what occurs when i try inputting my data into the admin site i have
if i press any save buttons
it comes to this error
and i dont know why
Ohh that is great are you going to explore ml ai in python
Nope.
Dealt with it in master's degree.
Not wishing to continue
Not finding it as fun for me
Have you register the app in setting.py
bruh you have a masters?
if you mean this
how long did it take to do one and in whihc branch
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'products.apps.ProductsConfig'
then yes
i think
4 years bachelor +2 years master in my country
well its the admin
Did you write all the models in product models?
What are you think about data structure and algorithm
That is cool to know as general basics
And it was teached at first or second year in university
I am thinking of getting bachelors in maths, bachelors and masters in data science
I am learning it now and doing it with python ๐
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=255)
price = models.FloatField()
stock = models.IntegerField()
image_url = models.CharField(max_length=2083)
class Offers(models.Model):
code = models.CharField(max_length=10)
description = models.CharField(max_length=255)
discount = models.FloatField()
this is all the models ive done
im doing the admin thing
which is built in already into django im pretty sure
Python tutorial - Python for beginners - Go from Zero to Hero with Python (includes machine learning & web development project).
๐ Enjoyed this video? Please vote for me for Top Tech YouTuber: https://bit.ly/34CIUn3
๐ฅ Want to master Python? Get my Python mastery course: http://bit.ly/35BLHHP
๐ Subscribe for more Python tutorials like this: https...
thanks
but this is not web dev
but im struggling with this django stuff
ohh
it kind of is
if u want to skip the important stuff
skip to the django timeskip
but it might be a bit complicated without watching the first parts of the video
anyway does anyone have any ideas on how to solve this
Have you run migration?
yes
Try to input the data manually
Hi, I am new here
I wanted to know, How can we make a portfolio website with python ?
I wouldn't. You could do it with Flask or Django but it would be easier to just use Hugo or something
Can you add product manually using shell?
ohh, okay
I thought python would help
i think you can but i dont know how to do that
i just used djangos automatic feature
You can certainly use Python if you really want to, here's an example: https://medium.datadriveninvestor.com/how-to-make-a-personal-portfolio-using-flask-56892c261984
okay!, thankyou
Reverse for ' activate' not found. 'activate' is not a valid view function or pattern name.
i am getting this error even though i have this in my urlpatterns
path("activate/<uidb64>/<token>", VerificationView.as_view(), name="activate")
i am getting the error on this line
link = reverse('activate', kwargs={
'uidb64': email_body['uid'], 'token': email_body['token']})
does anyone have a tutorial or course for django which takes less than 5 hours
costs money or doesnt idm
yo @inland oak i got it working
๐
And I finished learning golang basics, made primitive program
https://github.com/dd84ai/goping
covered with tests to 90%+
and published as docker image
https://hub.docker.com/r/darkwind8/goping
example to run docker run darkwind8/goping --url="https://httpbin.org/ip" --n=2
description: the image contains script to make efficient amount of http/https requests to the same url N times at the same time
it can be useful for performance testing
damn you did a lot more than i did
It is not the first language for me ยฏ_(ใ)_/ยฏ
yea i understand, i learned css in like 2hrs
This book is awesome
Teaches how to publish golang modules
How to test
How to make primitive web server
The awesome part... No dependencies are required
Everything what is needed in standard package of the language
Even templating language
same with my webserver hehe
I learned much longer
Head first CSS
And the missing manual CSS 4th edition
Plus few games about css
Flex zombies are awesome
so head first has book on every well known language?
oh
Some not related are present too
head first is a catchy title
Golang web server in inbuilt package is definitely higher leveled
I would say it is almost equal to flask
wait till i complete my webserver
Hey, I have a simple question related to linking html and css files in #help-orange, I would really appreciate if someone took a look at it
Can someyeone help me? When i make a discord bot, or even copy the code (not forgeting to change the token) it Just doesnt do antthing, i whatched some tuturials but they Just al say that it must to work? I use pycode btw.
Probably better to ask in #discord-bots
Hello, I want to transfer text from local computer to django localhost server (edit the file and replace a text by time). So how can I? (Django) I know to setup a project, app, and create views for it
Does anyone know like a "host" I could use to post photos. I made a forecast model and I want to have my python script automatically post it to a website or some kind of media/website (I tried applying as a Twitter bot). I rather not go through the pain of making a webserver for Wordpress, but if thats the only option I will. I just know theres API's that make it so much easier to post.
I have a script that generates an image of the model output (a weather model) and runs with crontab I just curious if theres anywhere to like be able to post it without the hell wordpress website route
No! Its by django templates, uses the render() function of django python which is in django.shortcuts as `render``
this helped thnx!!!
http://example.com/accounts/activate/MTg/b0e3ow-6ac86ead043876c8fead402026be69a2
i am following a tutorial
and i have sent an authentication email
but i am getting this link instead of the local host link that he gets in the
tutorial
stupid question time. when i create a model in django, does it automatically create a primary key?
thanks
did you solve your problem?
is it as simple as from main import app? because that feels wrong
https://www.sjoerdlangkemper.nl/2016/04/07/djangos-reset-password-mechanism/#:~:text=Django solves this in a,password%2C the token is invalidated.
could someone explain how change in state of the user make the token invalid?
is it because once the state is changed the token generated is different to the previous token hence python knows old token is invalid
?
Did you try it?
I did, it said it was ok in the ide but when trying to request the page it didnt have the proper contents and passed an error
Is there anyone interested in building a webapp with django and collaborating together
the webapp technically boots up though. im wondering if it has to do with file structure because the app should be accessible in the other files
Thank you, I went with Jekyll and I strongly recommend this to anyone, realy powerful, fast, robus and easy. Guys, check that out. Even github pages has it to build webpages, but you can always build Jekyll from scratch. Documentation is well explained. Worth to try, worth to use for business for websites that do not need DB.
Is there anyone interested in collaborating to build a webapp together. Please ping
Guys, I'm a bit confused, does it make any sense to use a Web framework combined with some GraphQl server (python eg: fastapi+ariadne) for an app where I want to use this query language?
If a GraphQL server allows me to connect directly to the database, I can create access control policies with jwt, access to the endpoint from the browsers and so on, in which app cases, could or should I use only the Graphql server and when do I need to combine it with a web framework?
Graphql is just a different way to accept input/output data into the backend framework
Replaces Rest API philosophy and removes need for multiple endpoints/routes, replaced them with one
Apply if u think I will have too many routes ;b
@inland oak Thank you, I understand that concept, my questions is, a graphql server allows send, get, modify data directly from any database with http protocol... then, why or when I will need use it(graphql server) with any web framework?...
Example: I couldn't create a graphql schema layout for a blog (or any web app), using only "ariadne" for the backend and write resolvers using the jwt library for user access control, then connect any frontend with a graphql client to the api created with ariadne only?
Does anybody have a good source for learning how to use the terminal in vs code
hey guys, i am working with my Django project . and i have to consume a queue from rabbitmq using pika . i have done all the configurations. but where should i call my consume method ? i have try to call in ready function in app.py. but it stops further execution of code even though i run the consumer in another thread. i also try to call it as a celery task but it stops my celery worker from further processing. where and how should i all my consumer method? please help.
please take a look https://stackoverflow.com/q/71006163/12638510 I could not deploy fast API app through azure DevOps.
Im not too sure what those are and im still trying to learn the framework. Ive made a webapp using flask but its quite different from fastapi from what i can tell. Ive just been trying to translate ideas and structures from what i know
That statement i think is all i needed lol
Ill still take a look at this aswell as routers in specific. Thanks for getting back to me
It is 3:30 in the morning though so ill check it out later, back to sleep for me
What's that mean? not import to other endpoints. I didn't understand. Can you be more elaborate? I have tried the same app deploying with Heroku and it's working perfectly fine. I have issues only when I started using azure
ok
is it possible to make a GitHub Static Page with javascript and host my own backend api, so the github page will go from a static page to a dynamic one
you can make dynamic stuff in github with javascript, you can host at it even results of client side frontend frameworks like React or Vue.js
but you can't host in it backend frameworks
i mean can i use front end js to comunicate with my own hosted backend
like if i make an api for example
sure
you can host backend in your own server, and attach frontend in github pages to it
ye that's what i meant
should i choose django or nodejs or fastapi for backend ?
someone please explain with appropriate reasoning
How can I split a python list, based on how many items I want in the subcreated lists?
Example:
Suppose that I have list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and that I want to split this list. I want to create new list containing only 3 items per-list. So the results would be
[1, 2, 3],
[3, 4, 5],
etc..
If I wanted to split by two numbers, the results would have been
[1, 2],
[3, 4],
[5, 6]
etc..
Which is the fastest (typing) way to do it?
I think there is an SO post that handles this question: https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks. Essentially, you iterate through the list, specifying the number of elements you want in each 'chunk'...
Thanks, it solved my problem
You could split after every nth item. a % 2 etc.
or maybe a generator loop that takes every list[::2] items
Hello, does anyone know how to solve this issue.
I have a django app I'm working on and I'm looping from the db however each item in the db contains a url name to take the user to the items page. I tried using {% url {{items.link}}%} inside the loop but the django url tag doesn't take an argument from the db. Is there a way to solve this issue?
In django, I have a table that iterate through the model item. I want to create a search bar that will only show the searched item inside the table
You would have to render the result on another page except if you're using js, might be another way though
{% url {{items.link}}%} i don't understand what you tried to achieve with this
it does not match any known to me syntax, check how to write in the right way by link
I created items from a model object inside a bootstrap card with the card being covered by an <a> tag do that when you click on the card, a page with Items relating to the card would be rendered. So I added the links for each items pulling from the db to make a looped card.
You know in django if you're trying to call a url inside the url patterns from the URLs.py you would use a url tag {% url ''%} so I'm trying to get the url name I inputed from the db and place it into the <a> tag using the template tag
May be too simplify it.
Calling reverse URL by name inside python code
And submitting ready to use URL value to template
It would be easy to test
I'm looping each items from the database and the link also has to be dynamic with the template too I thought of what I could do but the only solution to allow separate links was through looping the links for each item on the template. Would reverse work?
if anyone have experience in django please i need help
Would have to send you an image of the code when I can, so you can better understand what I mean
What's the issue you're having
how i can customize PasswordResetConfirmView page
i want to add class to forms
new password 1 and new password 2
Just read up on what you meant by reversing the call, would try it, I think it might work
https://docs.djangoproject.com/en/4.0/ref/urlresolvers/
For drf: https://www.django-rest-framework.org/api-guide/reverse/
Django, API, REST, Returning URLs
from django.urls import reverse
reverse('news-archive')
URL should be having designated name for this to work
If you instantiated the template in your registration folder you can customise it from there .
This is what I always use for mine https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html
i am getting this:
Reverse for 'admin_delete_book' with arguments '(None,)' not found. 1 pattern(s) tried: ['admin_books/(?P<pk>[0-9]+)/$']
error on this line:
return render(request, "Filehandler/Category.html", context)
when this line is not even in the same view
can someone help me pls?
Yes
I have deployed my web app but I am getting Application Error. I have checked the logs and I got ModuleNotFoundError: No module named 'uvicorn' But I have kept uvicorn in my requirements.txt file. I don't know why I am getting this error
How do i check class list view so only logged in user can access?
Nvm, got it alrdy
Hi, I'm trying to migrate my models in django but getting Fields.E300 and E307 check errors.
The file tree is something like ```
root
|-- models.py [Student Model]
api
|-- views
|-- klass
|-- models.py [Class Model]
The StudentModel defines a ForeignKey relation with ClassModel like ```py
# Student Model
class Student(models.Model):
student = models.OneToOneField(to="User", on_delete=models.CASCADE, primary_key=True, related_name="student")
parent = models.ForeignKey(to="Parent", on_delete=models.SET_NULL, null=True, related_name="student_set")
grade = models.ForeignKey(to="api.Class", on_delete=models.SET_NULL, null=True, blank=True, related_name="student_set")
roll_no = models.IntegerField(verbose_name=_("Roll Number"))
...
# Class Model
class Class(models.Model):
...
I tried to just migrate the ClassModel first and then later the StudentModel (by makemigrations <app_name>) but still same error. Any way to fix this?
Error:
Guys I'm new to Django and tried exploring projects that uses it. From what I saw, templates and static folders are created in the same directory as the project folder. Is your Django projects also structured that way? I thought it's better to put them inside their respective app folders to make them more modular. Am I wrong? Please enlighten me
It is totally up to you setup your project structure the way you want to. What you can do is to create a main "template" folder and then place each files for different apps in sub-folders.
As for the static files, for each app, all the static files will be placed inside one single folder when you run the collect static command.
Understood. Thank you @gentle grail
I am interested in running ads on a Flask app I'm working on as a way to offset server costs and maybe get a bit of profit. Is there an easy way to do this?
I should note I'm wary of Google Ads because I often see ads put through by them that do not fit my acceptable content policy.
There are endless alternatives if you search, but I haven't tried any. You'll need to do some research based on whatever your policy is
ok
ok so some of my models were being saved when i create their objects however other had a "null" value as an id
but when i added this in my models :
id = models.AutoField(primary_key=True)
problem was solved can anyone tell why?
Hey can anyone help me with my Html and CSS code?
It was just running find I dont know what happened but none of the CSS codes are showing up
can you show us the code?
context: Workin on a flask project where I'm trying to implement a way to get basic roles and data in database?
Should I make a script that adds basic role?
And a script that makes adds a role to a user?
verified, admin are the basic role
bro how do you get ur code in this format
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
!code
Hello guys can I get a little bit of help from this, I am trying to post an image file through a form using flask_wtf and it always returns None I have tried everything the only way that works is using vanilla flask but I rather not do since I wanna make everything uniformed, my python code for the path
@signup.route("/signup", methods=["GET", "POST"])
def signup_page():
if current_user.is_authenticated:
return redirect(url_for("index"))
else:
form = SignupForm(request.form)
if form.validate_on_submit():
f = form.avatar.data
filename = secure_filename(f.filename)
f.save(os.path.join(app.config["UPLOAD_FOLDER"], "avatars", filename))
form.register()
flash("You have successfully registered.")
return redirect(url_for("signup.signup_page"))
return render_template("/signup/index.html", form=form)
and here is the form
from flask_wtf.file import FileField, FileAllowed
...
avatar = FileField(
"Avatar", validators=[FileAllowed(["jpg", "png", "jpeg", "gif"])]
)
and the HTML
<form
method="POST"
action="{{ url_for('signup.signup_page') }}"
enctype="multipart/form-data"
>
{{ form.csrf_token }} {{ form.username.label }} {{ form.username() }}
<br />
{{ form.email.label }} {{ form.email() }} <br />
{{ form.password.label }} {{ form.password() }} <br />
{{ form.confirm.label }} {{ form.confirm() }} <br />
{{ form.privacy.label }} {{ form.privacy() }} <br />
{{ form.mail_list.label }} {{ form.mail_list() }} <br />
{{ form.avatar.label }} {{ form.avatar() }} <br />
{{ form.submit() }}<br />
{% for field in form.errors.values() %} {% for i in field %} {{ i }}{%
endfor %} <br />
{% endfor %}
</form>
HTML code after being rendered if that help
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form
method="POST"
action="/signup"
enctype="multipart/form-data"
>
<input id="csrf_token" name="csrf_token" type="hidden" value="xxxxxxxxxxx"> <label for="username">Username</label> <input id="username" maxlength="20" minlength="3" name="username" required type="text" value="">
<br />
<label for="email">Email</label> <input id="email" name="email" required type="text" value=""> <br />
<label for="password">Password</label> <input id="password" maxlength="36" minlength="8" name="password" required type="password" value=""> <br />
<label for="confirm">Confirm Password</label> <input id="confirm" maxlength="36" minlength="8" name="confirm" required type="password" value=""> <br />
<label for="privacy">I agree to the privacy policy</label> <input id="privacy" name="privacy" required type="checkbox" value="y"> <br />
<label for="mail_list">Subscribe to mailing list</label> <input id="mail_list" name="mail_list" type="checkbox" value="y"> <br />
<label for="avatar">Avatar</label> <input id="avatar" name="avatar" type="file"> <br />
<button type="submit">Send</button><br />
</form>
<h3><a href="/signin">Signin Here</a></h3>
</body>
</html>
I would like to know (as a noob) what would be the reason to use Django over other backend frameworks and how much is it used in reality?
Django is the most popular Python web framework, and the most complex.
If you've never used a Python web framework before, you might do a bit with Flask first as it's a little easier to learn. But it's better suited to small and simple projects
Can anyone take a look please? I'm stuck, can't find any straightforward example of doing this.. #help-broccoli
Anyone knows some cool syntax-highlighting extensions for Html and CSS? Vs-code doesn't highlight my CSS code in styles.css :( !
Did you look? This comes right up https://marketplace.visualstudio.com/items?itemName=ecmel.vscode-html-css
@inland oak This was what i was talking about yesterday, here's the code
so i found a temporary solution by hardcoding the link into the href and then adding the url name which isn't professional, which other way do you think i could handle it with
hi guys, i'm having an issue trying to implement a sign up for 2 users. One for normal users and one for is_staff users and the is_staff user would have the permissions from the signup page after signing up
getting this error in Git bash. solutions from stack overflow didn't work for me.
django?
Has anyone else noticed that emitting to room 0 with Flask-SocketIO emits to all rooms?
Late but wow, Django already at 4.0?
yeah
Redis-included.
I haven't used redis much so I'm curious to see what it can do it regards to assisting in site speed with a React/Next front-end.
Maybe caching searches or something to that effect? Redudant API requests.
What else is a well-known use case for Redis?
Good day everyone
Hi
You have to disable staticfiles on heroku, then you have to change the storage file on django settings from compressed manifest storage to STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'... That's if you're using whitenoise but if just django then just compressed staticfiles for django, don't use compressed manifest
hey, guys
I messed up bad on production
could you please have a look
I am in deep trouble
Hi guys, is it possible to add a choicefield in forms.py without first adding it through the model?
I have a development question related to web development in #help-broccoli , if anyone's interested in giving their thoughts.
I also would like functions to run irrespective of the Webhooks results and at set intervals of time.
sounds like you need Celery and Celery -beats for repeative jobs
guys is it possible to somehow pass a request.user from tempalte to django filters/tags or to model's method, as an argument?
hi how do i get the name from an authenticated user in django?
i want to automatically get the author based of the user
Image
when i create a blog post
You should have the user id saved somewhere in the session.
what do you mean by session
i.e. request.session
it's a signed cookie you give to the client, which is returned to you each request.
Django should handle that for you.
and how do i save the user id
thank you
There's also this, which is more specialized.
https://docs.djangoproject.com/en/4.0/topics/auth/
I'm going to write an API endpoint which is going to be remove users from Azure Active Directory and also Database.
Should I use PUT or DELETE or POST for this task ?
I mean, sure sounds like a delete
all 3 involve changing/updating or removing data but yeah I do agree delete will prolly be best
does anyone have any idea how to create a form where depending on the form involving the state you chose, its going to allow the next form to be about cities pertaining to that specific state choosen
Working on a web scraping program could anyone vc and help me out with an issue I'm experiencing rn
This is my first time using beautiful soup
A form in Html?
<form></form>
hello everyone and very good morning
Hey guys, So i was just doing a course on codeacademy, and found out this piece of statement
Horizontal margins (left and right), like padding, are always displayed and added together. For example, if two divs with ids #div-one and #div-two, are next to each other, they will be as far apart as the sum of their adjacent margins.
I might sound dumb, but I wasn't really able to understand what it meant, so if anyone can, please explain what this means 
They over complicated it I think. They are just saying that the distance between 2 divs is gonna be the sum of the paddings on each side. This is cuz the padding is the border
wow okay, thanks a lot!
Lol no, a forms.py in django, how do I go about that with it before instantiating it on the template
is there any way to pass two contexts in one view function in django
I wanted to ask something on Poetry with FastAPI since spamming the help channels doesn't get me any responses: has anybody tried to launch a FastAPI app through a Poetry script?
Like, I have a function using uvicorn.run as entrypoint, except the script can't recognize the package for some reason
nvm seems it was all caused by an issue in the name
Hello All, I am new to software engineering and even newer to web development and I would like your suggestions about the stack and technology I chose for a project. It would be a basic website to create a questionnaire and users would have to send answers privately to the creator of the questionnaire.
- Python Flask with Jinja templating + Bootstrap for frontend(A looked into FLask and Django both a little and Flask made a little more sense to me but if a better alternative is there, I can check that one out as well)
- Database: Postgres
- SqlAlchemy for ORM
- Docker for running separate containers(one for website, one for Database).
Questions:
- Please advise any replacement of the above if you think is a better alternative.
- Should I look into liquibase or flask-Migrate and learn them before beginning with the project? If yes, which one should I consider?
- Am I missing anything which would make me go back to the drawing board and start from the beginning again?
How about you start describing what you are actually wishing to implement
Are you developing for which level of quality? Tell a bit about background, are you student / or beginner in some company?
what kind of human resources are available to you
everything is working now how do i use my html and css file in my flask server using my domain (i am very new at this thing so please help me)
Does anyone have experience using Django exclusively as an API? Thoughts? Good? Bad?
Have you tried Django Rest Framework?
I haven't, how is it?
Django, API, REST, Home
Basically it transforms your models in serializers
Serializers are objects formatting your models for an API response
These go into views.
I suggest looking at the examples to see how these structures are connected
Objective: Admin would create a questionnaire and and a link will be sent to participants from answers are needed. They will login to the website and submit answers. Those answers can only be viewed by the admin and not by the rest of the participants.
Quality expected: Internal organization production level, won't be customer facing or revenue impacting.
I am new in the company and to website development.
Human Resources available: Just me, at least for now, since it's a side project.
yeah, DRF is quite good for rapid development. Good for being beginner friendly and being valid solution for enterprise for its stuff.
For medium quality of work is quite well.
But if to reach Highest quiality available in Python for Enterprise, perhaps it would be better to choose FastAPI
But using FastAPI is much more demandful in skills than using DRF, i think
Fast API is not guiding you on a train on trails aproach like DRF does
Fast API asks to think for ORM solution on your own, which is harder, but at the same more flexible, and you can at last choose Async ORM, which Django is still not having
Fast API is more for diving into Async python ecosystem as far as I discovered
Fast API involve smth additional in terms of to check your code quality, but it could be hard to get for beginners
And... FastAPI is a bit more performant than Django, about several times https://www.techempower.com/benchmarks/#section=data-r20&hw=cl&test=plaintext&l=1kw1-0
Also idk if Peewee is better for ORMs than SQLAlchemy
My experience with SQLAlchemy being kinda tedious
Hello guys, pretty new to api/web development. Using Flask JWT for my API and is currently working. I am now making a separate app that 'talks' with my API. Should I then save the access/refresh token for my app in a cookie? or should I just login everytime it talks with the API?
Who would be participants to the test, company workers?
So in case of accidental database loss, nothing would bad happen?
It is needed only to run the test, check results, and database can be lost after that until the new test is needed?
How much participants to the test you estimate to be entering the test at the same time?
How much time frames do you have for the project?
I would prefer that data is not lost least for at least 12 months as those answers would be relevant for a fiscal year. But yes, even if the DB is lost, nobody would lose their job or customer sentiments would be impacted.
These questions are not necessarily considered as quizzes for assessment or tests. They would be free text answers that interested people collected information through static word files and maintained separate files per employee.
Participants could vary between 50 to 500 per questionnaire.
Their is no deadline since this is a side project but would like to complete it in at least 3 months.
couldn't fix. shows me the same errors. and internal server error when i open the site
how much you can afford for the infrastructure to be expensive
tell numbers for the money to spend per month
minimal / maximum / what you can estimate
we have our internal cloud so hosting charges would not be a issue unless it goes beyond control
but the cheapest option would be appreciated I guess
internal cloud.... is it your only option for the infrastructure I guess
is it having terraform compatibility?
what type of common resources you can use from it? Raising VPSes?
is it having Managed Databases?
separate AWS instance that can talk to the internet
i mean, can u request from the cloud managed databases for your project?
what types of common Cloud Objects are available to you
yes, either separate container for DB and for app or an VM. I would prefer the containerized way though instead of Compute instances.
everything available in AWS.
well, I think that should be enough of questions to formulate advices for your case
Hello All, I am new to software engineering and even newer to web development and I would like your suggestions about the stack and technology I chose for a project. It would be a basic website to create a questionnaire and users would have to send answers privately to the creator of the questionnaire.
- Python Flask with Jinja templating + Bootstrap for frontend(A looked into FLask and Django both a little and Flask made a little more sense to me but if a better alternative is there, I can check that one out as well)
- Database: Postgres
- SqlAlchemy for ORM
- Docker for running separate containers(one for website, one for Database).
Questions:
- Please advise any replacement of the above if you think is a better alternative.
- Should I look into liquibase or flask-Migrate and learn them before beginning with the project? If yes, which one should I consider?
- Am I missing anything which would make me go back to the drawing board and start from the beginning again?
I would strongly advice using Django for your case, Flask is just not cutting for company development
for internal development to make project of your quality in the fastest way, Django is the best
Django ORM for the database
PostgreSQL is cool
Docker is cool too
What you can improve for your case....
https://www.amazon.co.uk/Systems-Analysis-Design-Alan-Dennis/dp/1119585856/ref=pd_lpo_1?pd_rd_i=1119585856&psc=1
Firstly it would be highly good for you to go through the Systems Analysis And Design book
You could formulate how to make your project better
less time would be spent on redoing on the way to a different direction
Secondly...
I would recommend to learn terraform / pulumi (available in python) or even AWS CDK? If i know the name right (choose something one out of three to work with AWS)
it will allow you to setup infrastructure for your project at infra privisioning level as a code, working with AWS GUI is terrible is experience, the code is better ๐
Fourthly you would highly wish to use Managed AWS databases for PostgreSQL
you could check out its options, so it would have auto backups of your data
so you would not loose any of your data
Make sure to check that backups are made, and that you CAN RESTORE the data
if you did not try restoring the data, then you have no backups
If you would go for manually(even docker containerized database) make sure to implement some sort of backups and data restoration
Fifthly: I would stress you the need to use unit testing throughly across your project, pytest is perfect for you, if you don't know how to test, recommending the book
https://www.manning.com/books/unit-testing?query= Vladimir Khorikov
Unit Testing Principles, Patterns and Practices shows you how to refine your existing unit tests by implementing modern best practices. Youโll learn to spot which tests are performing, which need refactoring, and which need to be deleted entirely! Upgrade your testing suite with new testing styles, good patterns, and reliable automated testing.
That should be all from most important things in my opinion.
I can add few more optional additions for the future
you would be possibly looking one day for Ci/CD tool like Gitlab CI, Github, Travis, CircleCI, Drone CI.
Don't use Jenkins, i recommend Gitlab CI, it is nice.
Ansible could be useful to you for server configurations if you will be configuring linux servers, it will make your configuration as acode, but if you would be using AWS container objects, it would be not needed I think
Docker Compose could be useful for local development / and or depending on how you deploy could be useful for deployment too
Disclaimer: Every mentioned by me technology is not necessary for your project, but if it will make the life easier.
The most important ones from new technologies, would be testing, and Managed Database? ๐ค The rest is less important
P.S. Django is also the best, because it comes with inbuilt Admin interface (that requires just a bit of code to set it up) available just for admins
it will make easy out of the box solution for your Admins to see results of the test
Guys I am learning css and I need to put this div at the center of the block, I tried using padding-top but it also increasing the height of the block. Can someone tell me how can I keep it at the center.
margin: 0 auto
It look like this as of this moment but if I do margin: 0 auto it looks like this -
Honestly no one can help you without seeing your layout and existing CSS
'left' and 'right' should work. I would recommend not using px unless you have a reason to fix the size. Percent or visible is better
also food for thought here
https://www.w3schools.com/css/css_grid_item.asp
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
U mean padding-left and padding-right?
has anyone encountered a way for sessions to be invalidated on all browsers when a user changes password?
session data is stored server-side.
Hi
I was working on a Web app kinda thing
Needed to add Cross origin isolation
Cross-Origin-Embedder-Policy: require-corp
Cross-Origin-Opener-Policy: same-origin```
It says to add this to header,
But I am not too sure, I work in C++ and my knowledge of web is almost none
what framework are you using?
is it possible to grab all session keys that belongs to one user?
If I am being honest, I am not sure. This web part isn't really part of my code. I'll try to see
probably depends on the backend. like memcached or redis
I can get that info from the JS files being used by my HTML ?
Sorry, really new to this stuff
headers are part of the http protocol
@inland oak Thank you so much for the detailed answer, explanation and reference material. I decided flask because rest of the few apps that I am expected to work here are planned to be created using flask. I have created one app already in Django so I preferred it in the beginning as well.
Auto backup is a great suggestion. It was in the list of features to be implemented. And I am also learning boto(AWS SDK) so hopefully that will be helpful in platform deployment. Atleast for outbound notification using SQS.
Also, unit testing makes sense definitely. Would be the first time I right app with unit testing if I am expecting this to be successful and involve more people in the future.
Thank you again for your time and help. I appreciate that a LOT !!!
you need to go into the server to modify them.
U a welcome ๐
I see, so as this is a local testapp. I need to add this info to where i start server ?
Like ```Python
#!/usr/bin/env python
import sys
PORT = int(sys.argv[1])
if sys.version_info[0] < 3:
#print ("Running Python Version -2")
print ("Running Python HTTP Server on port %d" % PORT)
import BaseHTTPServer, SimpleHTTPServer
SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map['.wasm'] = 'application/wasm'
httpd = BaseHTTPServer.HTTPServer(('localhost', PORT), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.serve_forever()
else :
#print ("Running Python Version -3")
print ("Running Python HTTP Server on port %d" % PORT)
import http.server
import socketserver
handler = http.server.SimpleHTTPRequestHandler
handler.extensions_map['.wasm'] = 'application/wasm'
httpd = socketserver.TCPServer(('localhost', PORT), handler)
httpd.serve_forever()
Add the header info here ?
Or is it to be added in JavaScript files?
its just an html header
Cross-Origin-Opener-Policy: same-origin ```
Add this to HTML Header?
But where
Thank you
Does anyone know why ModelQuery.objects.filter().count() always returns incorrect length of query? As well as len()? I have 2 items in query but it returns 1. Django
i have a friend who needs help with : im creating a checkout page for a website(ofc this is for sch) and a staff page where the staff can obtain the order from the customer as well as their data like email contact postal code and their specific order
and as for the checkout page i need to obtain data from the customer's order from a previous page and there's a page for billing info like normally when you wld order stuff. as for the table thats supposed to show the customer order, just place placeholders there cuz im not doing that part, and u can remove any code u find weird but just tell me about it, i just hv trouble storing data and getting data
this what it looks like kinda. pls dm me if you want to help
idk if this counts as python sorry
sounds like index starting at 1 vs 0 somewhere
from flask import Flask, jsonify
from flask import Flask, jsonify
from threading import Thread
from flask_restful import Resource, Api
import random
import json
app = Flask('')
api = Api(app)
@app.route('/')
def home():
return "/name/<TEXT HERE>"
@app.route('/add', methods=['GET'])
def add():
return jsonify({"2 + 2": 2 + 2})
@app.route('/echo/<string:echo>', methods=['GET'])
def get_name(echo):
return jsonify({"text": echo})
def get_facts(fact_type):
if fact_type == "random":
file_address = 'Facts/random.json'
elif fact_type == "technology":
file_address = 'Facts/technology.json'
else:
file_address = 'errormsg.json'
with open(file_address, 'r') as factfile:
data = json.load(factfile)
fact = random.choice(list(data['Facts']))
return fact
class Facts(Resource):
def get(self, fact_type):
return get_facts(fact_type)
api.add_resource(Facts, '/facts/<string:fact_type>')
def run():
app.run(host='0.0.0.0',port=7000)
t = Thread(target=run)
t.start()```
What's wrong here?
Don't you have any logs?
can some one suggest me some intermediate to advance django projects I am really confused
You try to open a file, according to that error that file does not exist. Check whether the path is correct. @flint vigil
Ok
Can you show specifics?
Unless you are forgetting that 0 is the first one, and not 1.
does anyone have any idea how i can create a 3 selection form in django in forms.py. The first form being the country and dependent on the country, the second form is going to produce the states in the country and dependent on the second form, the third form is going to produce the regions in the country. Is there anyone with how this can work without js?
I'm not sure you can without js. Would love to hear if that's not true, but you need to be able to change the DOM on the fly based on the state of your form, so you sort of need some JS there.
Hey, does anyone know why these modules I have installed still give me a not resolved error?
Hello ! Does anyone know how to use openstreetmap api ?
okay thanks
Hi, im at the very beginning of designing my game's backend architecture. It will be a turn based multiplayer card/strategy game. I never programmed servers so i wonder with what and (on high level) how to implement the matchmaking and session(2 or maybe more players) handling part of it?
Since it will have a fairly complex state/state-machine and i want a universal interface with the game server, i'd like to implement a GraphQL API for this purpose, to handle state update and query from clients. The frameworks i researched a bit and would like to work with are FastAPI and Strawberry GraphQL.
From the FastAPI documentation the most related thing i found is the authentication(https://fastapi.tiangolo.com/tutorial/security/first-steps/), but i feel like this is not what im looking for. I found tutorials for session management with socket and socket.io modules. I wonder if i could do the same with FastAPI or have any of these integrated with FastAPI?
Any advice is appreciated, i can check and reply in the morning (it's night here). Thanks!
Any Flask/FastAPI devs here? I have some simple questions that I'm stuck with, it won't take you long to answer, please dm me :) No answers in help channels, probably to webdev specific...
Anyone have any experience with Django Rest? Im trying to decide between it and Flask for an api project.
I guess just a general question, but should be making API calls in my backend or frontend? what would it look like doing it from the server
I'm working on a website for my business. And I would like to add a blog feature. All the tutorials I have found display all of the blogs, and their content on one page. I was wondering if there was a way to only display the titles as links and when they are clicked it takes you to a url unique to that article, and displays the content. Or just a page where if you click on the title it brings up the content instead of showing it all on the page. I am using flask, flask-sqlalchemy, and flask-login so preferably just using those. Any help is appreciated. Thank You!
try importing react in your file
it should be but it's not doing that so try importing react
Hello I am currently working with flask api with swagger ui and i have encountered an issue,
does someone here encountered an issue with regards the
AttributeError: module 'jsonschema._utils' has no attribute 'types_msg'
it is working fine when connecting to local however when connecting it to AWS it shows error like that
If you're just building an API, FastAPI might be better than either of those. Django is almost certainly overkill if the API is all you need
Hi Is it possible to make a fewer queries for this in Django?
artist = Artist.objects.select_for_update().get(id=id, merged_to__isnull=True)
merged_to = Artist.objects.select_for_update().get(id=merge_to, merged_to__isnull=True)
albums = Album.objects.filter(artists=artist)
for track in Track.objects.filter(artists=artist):
track.artists.remove(artist)
track.artists.add(merged_to)
for album in albums:
album.artists.remove(artist)
album.artists.add(merged_to)
artist.merged_to = merged_to
artist.save(update_fields=["merged_to"])
yo anyone on
need help with media query
it is firing sometime and other time not
any idea why
does someone here knows how to fix this error?
AttributeError: module 'jsonschema._utils' has no attribute 'types_msg'
It is working fine when connected to local database however when i switched to AWS I received this error I am currently installing my jsonschema in requirements like this
RUN echo 'jsonschema >= 2.5.1,<4' >> requirements.txt
please help thank you
What is your framework
What is your library to connect to database
What is your database in Development, and which database did you use in AWS?
im using flask framework
im using ORM connection to database
and im using postgreSQL in AWS
it is working fine in local but when connecting to AWS it raise an error like that
What do you use for local database
postgres also
Blinked. Postgres there, and Postgres there and still error
try to find postgres version difference
match it too
in local and AWS
Btw that's a bit wrong way to install requirements
will that cause an error?
usually we freeze requirements to specific version
like
stuff=7.7.7
and installing requirements from files
requirements.txt and constraints.txt
did you test the same built image for local db and AWS?
are you sure it was the same one?
FROM backend/api:20220209
USER root
RUN echo 'flask-sqlalchemy == 2.5.1' >> requirements.txt &&
echo 'SQLAlchemy-Utils >= 0.32.0' >> requirements.txt &&
echo 'jsonschema >= 2.5.1,<4' >> requirements.txt
this is how i install
yes they are both thesame
im not sure about the database tho, they just informed me about the said issue
https://pypi.org/project/jsonschema/ looking over this module it looks a simple JSON config loader
So one of two things to go wrong
- They write for your application wrong input
- Freeze the dependency version properly!
although if you would DOCKER PUSH your image to docker registry
they would have used the same image you tested in your local dev
so it should not have been an issue
but you did not do it, right? They were rebuilding image from scratch?
which is quite wrong too
no they said they are using my image built
how can i check on what version of packages installed in my project?
pip freeze > filename.txt, to freeze them all
or just pip freeze
what does it do?
it shows all current installed packages in the current python environment
we develop projects in VENV usually
so all installed packages are the ones that are used for current project
then we just freeze everything installed to constraints.txt
and copy the primary dependencies to requirements.txt
constraints.txt aren't installed, they are just to lock secondary dependencies to primary dependencies from requirements.txt
i tried to pip freeze > requirements.txt
but
-bash: requirements.txt: Permission denied
sudo pip freeze > requirements.txt
and you can just unlock your permissions, with setting right rights for the project folder, a bit of chmod is required, then it will not require sudo
im inside su - docker
do it from the user who created the project
yea i want to learn it also but i think im still newbie
can i put it inside the dockerfile? so it will log the output?
do it before dockerfile
freeze to requirements.txt
copy requirements to docker, and install them all
COPY ./requirements.txt ./
RUN pip install -r requirements.txt -c constraints.txt
COPY . .
FROM backend/api:20220209
USER root
COPY ./requirements.txt ./
RUN pip install -r requirements.txt -c constraints.txt
COPY . .
RUN echo 'flask-sqlalchemy == 2.5.1' >> requirements.txt &&
echo 'SQLAlchemy-Utils >= 0.32.0' >> requirements.txt &&
echo 'jsonschema >= 2.5.1,<4' >> requirements.txt
like this?
sorry for being a noob
RUN echo 'flask-sqlalchemy == 2.5.1' >> requirements.txt &&
echo 'SQLAlchemy-Utils >= 0.32.0' >> requirements.txt &&
echo 'jsonschema >= 2.5.1,<4' >> requirements.txt
why would you add to file after you already RUN pip install -r requirements.txt -c constraints.txt installed what is inside of it
it does not make any sense
and I already told you, use flask-sqlalchemy == 2.5.1 specific frozen versions, don't make them go wild in a range
And you don't need to add to requirements.txt file, u a supposed to have everything in it already
no it has not everything on it i added those other stuffs
it is already made project and those 3 are added
its from the mongo connection change to postgre
thats why
that's a wrong approach
own the code, delete what is not needed, add to it what is needed
the worst enemy of programmer is having commented not needed code in the project
the even worse situation, having this not needed code actually present in the project
thats what my lead told me im just following orders sorry ๐ฆ im just a newbie
This book could be useful
It should tell you main things regarding the code cleansiness
But to have it the best, you probably just need to make your own pet projects
made from scratch
that would be even more useful
you told me u have flask there
Go through this tutorial first
Fully on your own in project owned by you only
i dont understand even i dont fixed my version installed.. but we are using same image it must work in there end right?
because it is working in my end
Yes, it is supposed to work... But there is no guarantee because... U did not have testing in staging environment
which is the aws?
Local development should be close as possible to production infrastructure, but it has limits in achieving it
In order to make sure full compatibility, u need to test it working in staging (cheap small mirror of your production infrastructure)
Since u use AWS, staging should be in AWS
AWS is a cloud provider.
Basically it gives virtual machines (virtual private servers) for u to install your soft
Besides that it offers a lot of other infra stuff, firewall, automatically managed scaled backed up databases and etc
It removes the need to have physical servers and removes the need for a part of Development and maintanance
maybe my connection to the aws has an error thats why the json schema error appeared?
May be u ll have a look what config u a missing, what for jsonscheme is used
And to try testing in AWS object they used
Ask for access to staging copy to where they tried to Deploy it
Of their AWS db
https://jsfiddle.net/uxai_/p4e9dbx0/
Created this simple filtering for articles by category...mostly with CSS and a couple lines of JS. ^^
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
how to switch from open api 3.0.0 to api 3.1.0?
Why is wsgi layer needed when we have nginx?
Why can't nginx directly talk to application server (flask)?
Because your default flask server is meant just for development. It has detailed debugging, and not meant to be used by more than one user connected at the same time
We run flask with gunicorn, to have all the feature like auto recovery from errors, scaling etc
What wsgi does in detail I have no idea, never encountered the need to know yet such low level details
isnt gunicorn is one of wsgi servers?
there are gunicorn, uwsgi, etc
there are all wsgi's if I am not mistaken
My knowledge ends at wsgi being engine for sync, and asgi being engine for async frameworks
Async are asgi
didnt know that
To my understanding gunicorn can run wsgi engined web servers
At the same time I encountered that wsgi had most of features of gunicorn
I can assume that gunicorn is probably just CLI interface for easy wsgi run
I can be wrong though
We can run a Flask in production mode, right? There is an env var which tells the app whether it will run in dev vs prod mode.
Flask can be run in production mode if u run it by gunicorn
Did you find an answer?
Are you using django on purpose or it just was the first one you tried coz it's popular?
I'm gonna use FastAPI for my project and my goals look nearly the same - send inputs from web form directly to py script
We can cooperate to find the answers and share them. Ngl im stuck af
I've been posting the same question over 10 times in help section and here, but still no progress
Are you workin on some school project?
can anyone help my friend with coding for a website thats similar built to amazon
anyone?
What are the tools y'all think I can use as a beginner for web development
and some beginner project I can work on
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
Get started with just
Flask
Git
Getting used to Deploy at Linux servers
Add Docker to the list, if u wish additional challenge
Thanks
If u ll handle all those challenges, recommending getting used to pytest, how to do unit testing
Unit Testing Principles, Patterns and Practices shows you how to refine your existing unit tests by implementing modern best practices. Youโll learn to spot which tests are performing, which need refactoring, and which need to be deleted entirely! Upgrade your testing suite with new testing styles, good patterns, and reliable automated testing.
Thanks so much, do you mind if I could chat u up Incase I have some issues or challenges
I mind, this approach is time ineffective and not valuing other people's time.
Ask in public chats everyone
Okay
Why flask not fastapi?
Flask is better for beginners
Especially for zero beginners
Why exactly?
I'm zero beginner, I started with FastAPI and cant find an answer to my question for 2 weeks already
But at least fastapi works where flask didn't for no obvious reason
Hey Guys, I'm facing an issue which I tried to solve and read articles related to that but not found any solution. Actually in my pc, All the python commands is working fine but while running a command py manage.py runserver I'm getting an error "Unable to create process using 'C:\Users\Abhishek Anand\AppData\Local\Programs\Python\Python310\python.exe manage.py runserver'". I tried to uninstall and re-install the python on my pc but still getting this error with all django projects.
go inside project1 and try to start server
u perfectly answered on your own
u can't find an answer for 2 weeks already
Flask should be having less learning curve
@wheat verge Actually I tried to run but server isn't starting...
Its consistently saying the same thing
I think python.exe is failing to start the server...
project 1 is your project right?and website 1 is a project which you made inside the project?
Same question would appear with Flask, it's not FastAPI specific. I just don't know what should lay between web form and python prog to transfer inputs/outputs both ways
it is more problem of ambiguity of your question I guess?
-
Anyway, you can just use default web form behavior and utilize
-> Page is rendered to use
<- Form sends POST request with data on submit
-> Server sends a different rendered thing on answer
(Available even if you utilize just backend framework without frontend, zero dependencies thing inbuilt into html) -
Same can be used for total free sending in both directions
If you just add Javascript to it, you can send in both directions then HTTP/HTTPS requests
(Better fitting to be used, if your frontend is made in frontend framework, then you can send requests in javascript without re rendering client in a comfortable way, because Vanilla JS is pain) -
There are few other ways to send information both ways, like Web sockets make a channel for that in real time for quick and often data transmissions like in Live Chat
(Available only if your backend framework supports web sockets, and u added at frontend Javascript for the same)
Yes, websockets look like what i need, at least fastapi example works nice
can anyone help my friend with coding for a website thats similar built to amazon he rrly needs help
But what's next? That's where I got stuck. I can send text to form but how can I send it to python prog?
Can I only do it sending those inputs to console or there is some other way
I don't even know what to google :)
read documentation to web sockets
for whatever u use at front and for back, both docs
Where should I find this docs?
what do u use for front
Html + maybe some simple js (i dont have js experience, so i dint know if i even need it), but I need some sliders
What is serving your frontend
where it is generated
is Uvicorn sending your html files, generated from FastAPI?
FastAPI framework, high performance, easy to learn, fast to code, ready for production
I just copy pasted this
And it worked
So what I need is more textboxes, checkboxes, sliders etc on the same page, submit button and some text area to print raspberry pi console outputs
<form action="" onsubmit="sendMessage(event)">
your html form has attached javascript function to act on click
function sendMessage(event) {
var input = document.getElementById("messageText")
ws.send(input.value)
input.value = ''
event.preventDefault()
}
this one
That's where you currently send data to python
your lack general understanding of Javascript in the terms of using it in html
Read the book
It will make stuff better to understand
feel free to get over HTML/CSS book in addition
https://www.amazon.co.uk/Head-First-HTML-Elisabeth-Robson/dp/0596159900/ref=pd_bxgy_img_2/262-3652027-3709143?pd_rd_w=yzpIs&pf_rd_p=424ee22f-2317-49a5-9cbb-bc8836ac7d96&pf_rd_r=7YGYM5HR36YAD7FTC88W&pd_rd_r=8aaa71b0-2cfc-4f5e-b0ad-c5ab88ceeec5&pd_rd_wg=fZs6X&pd_rd_i=0596159900&psc=1
Not enough time to dig into all the aspects
just get over Javascript book then at least
The point is im not aiming at webdew job etc, i just need to make my stuff receive inputs from web ๐ I'd probably better pay someone to do that for me
Passing full js tutorial is def not worth the time
it is the most fun js tutorial that could exist in the world
fun for the sake of fun ๐
Hey @wheat verge I've figured the thing out
Thanks for your help๐
Actually the problem is that python is not configured in my system properly
I've reinstalled it via custom install
I've given the permission to all users there
and that's what it needed
and now my scripts are running smoothly....
Hey folks, working with a FastAPI project right now. What's the typical pattern for splitting endpoints into their own separate folders? Right now, in my api package, I've got a main.py that contains the app and I'm simply importing that app object from the subpackages which are separate categories for all my endpoints
Just want to know if there's a preferred way of doing this
I see there's already documentation on this
FastAPI framework, high performance, easy to learn, fast to code, ready for production
koi baat nahi bhai ye sab saale firangi kabhi help nahi karte humme hi ek doosre ki help karni hogi
Are bhai bhai
ye saale answer hi nahi dete
accha bhai ek baat bata koi accha django project idea hai jo resume mei dalne layak ho
samajh hi nahi aa rha kya karu
ek to do app banaya tha vo logo ko impressive nahi laga
Django aur koi bhi library ya framework jaise tailwind ya react use krke clone bana famous sites ke ya phir problem solving site bna
Hello, I want to perform a DELETE request in python, in postman, I'm able to make delete request to this url: mysecretapilink.com/customer/delete/{user-id}
So in python, should I write this user Id to url, or is it going to be add it to the url if I write it to data=json.dumps part?
response = requests.delete(
url,
data=json.dumps(payload),
headers=headers,
auth=HTTPBasicAuth(toggl_token, 'api_token')
)
Hlo
I want to learn web development in django
I know basics of python
Help me out
you need to put the user-id in the url
thanks! ๐
Ok
Anyone familiar with FastAPI on how to make session management for matches in multiplayer games?
Hi could someone tell me please if this looks good or is there are any big issues with these https://github.com/arsalasif/flask-rest-api?
hey i need someone here to make simple website for me
u can see contact info, about us page, and a games page to download free games i make
dm if can help
hey im having an error trying to run a code that webscrapes the price of an item in an website
can someone help?
Show your code and the error you are getting
@golden bone
code :
from cgitb import strong
from multiprocessing import parent_process
from bs4 import BeautifulSoup
import requests
url = 'https://www.jumia.dz/djebs-sweat-shirt-a-capuche-en-coton-pour-homme-rose-328228.html'
result = requests.get(url)
doc = BeautifulSoup(result.text , 'html.parser')
prices = doc.find_all(text='$')
parent = prices[0].parent
strong = parent.find('strong')
print(strong.string)
Error:
Traceback (most recent call last):
File "c:\Users\Yasser\Desktop\Coding\Py\Learn.py", line 10, in <module>
parent = prices[0].parent
IndexError: list index out of range
prices doesn't have an item at 0 position
so i just delete [0]?
Why delete?
I would check whether 'doc' contains what you expect
oh the problem was that i did put the wrong url
Can i make a website to control python script without Js?
thanks for the help
Sure, check out Flask
Flask did not run for me, FastAPI did, but i still dont get how i get the data from the web site
If you want to use FastAPI, I think you'll probably need JavaScript (or maybe HTMX?) to make requests. Or you could figure out what the problem is with Flask
But what's the difference in terms of getting input data from website? Different approach?
Any info i find sais fastAPI is better by all means, just a little harder to learn
Flask uses Jinja templates, which makes it very easy to interact with static HTML. I'm not sure FastAPI has anything like that
FastAPI framework, high performance, easy to learn, fast to code, ready for production
๐ชFastAPI
Nice... So try that and see how it goes
I'll have to look at that for my next project, didn't know it supports templates but I've heard good things in general
anyone have any suggestions for a decent basic flask boilerplate json api with authentication?
I so dumb :(
Why is it so difficult to just send 1 symbol to from web to python.. It's like travel to the moon
I found an example of controlling gpio with fastAPI but it only has 2 states and both server and python gpio control script are on the same rpi which is not my case
what's your case?
I made gpio control script for scientific project and i need to send inputs from web not from rpi console
sounds like you need to host a server that is able to interact with your rpi
exactly bro
so what's the issue?
I can't find a good example of how to send inputs from web to python
while web server and py script are miles away from each opther
i.e, your commands in this case
so i need 2 servers?
then you send them where you want
why would you need two servers?
one is enough
as long as it can interact with your rpi
1 server to input stuf, other servers to receive stuff
do you understand how a server works?
I must be missing some basic things
Look, I need to send X variables to Y RPis all over the world
what ...
Are you expecting people to link their RPI to your platform or something?
The idea is I open my browser, go to some URL, choose the RPis i want to update and input variables, press submit and all the variables go straight to the supercomplicated py script
Lmao I honestly don't know if you're trolling or not.
Probably it will work this way too
Nah, I want to make it work, preferably without learning Js
your devices need to be actively connected to your server and actively listening for changes
without js?
eh wait
Or at least ultrabasic Js that I can copypaste and apply minimal changes
yeah, what you want is not a simple thing
Why not just connect one rpi to your fastapi (or whatever) server and start from there.
I bet)
Because I need a solution that is 100% scalable i.e. i don't have to remake it from scratch in a month to add more RPis
To add more RPis
By scalable I mean the web page will most likely have the same UI, same variables, but more users, more RPis etc
I know what scaling means.
I didn't ask what scaling is.
Nwm, I didn't get the question
I am 99.9% sure you shouldn't be worried about scale at the moment.
What's the hurry?
It's a scientific project
It sounds very scientific.
And I hate double work, so I prefer to do things the way I won't need to change a lot later
You ask the questions not related to the topic
Pretty sure they were related.
How?
Good luck with the science!
Here is the troll here.
dude, you basically want a server that is able to remote control a lot of devices?
Yes
a web server basically
yes
Look at the first link when googling how to connect raspberry pi to fastapi
How To Build a FastApi Server to Control a Raspberry Pi?
Sounds like that's what you want, yea?
the way i see this working is if you, basically, put a server on each of your devices, and than use this one webserver to basically interact with the servers on the RPIs
No
else, i dont think what you want is possible
In this example web server and GPIO are on the same RPi
Plus there are no values sent, and instead of inputs there are 2 pages for 2 valve states
you can configure the example to do whatever you want ...
So it doesn't answer the question how to transfer values to remote RPis
Only from local network so far
so if you want to access this truly remotely, you do realize that you'd have to basically make a server on your RPi publicly available right?
Yes, for this matter I'll implement login later. If it's possible to run such server in Azure or AWS there is also such option if it's safer
i mean, if you host this on AWS for example, the thing is, it will not be connected to your RPi
you'd basically have to be the one interacting with this server from your RPi
Even if rpi has static ip?
what do you mean by that? are you hosting the server on the pi or aws?
Both ways available, the question is which one will work
User will connect rpi to the remote server at least once and will keep it online 24/7
The thing is, what you want to do is complex.
Could someone point me in the right direction to what I would use to build a basic web-app with Sliders, Dropdowns, using an excel sheet for the data?
Like that?
You can just use google sheets as your API. Does it have to be excel? Is this local only or living online?
you want users to connect to a server and interact with it through the pi?
You can put one server on a remote linux machine, and one on the pi, and then have your website (on the first server) send commands to your pi. Now, scaling that to many rpis is complex and difficult.
So the question that's not really clear is - what do you need at this moment?
It sounds like you need - "an answer"
but that's really vague
I'll check it out. Thanks @dense slate
does anyone know thow to convert openapi 3.0 to openapi 3.1
I can't find any straightforward explanation of how I can send commands directly to the running python prog from anywhere, i.e. should I communicate with RPi console as if I would enter the values manually, or I have to save it into some file and read the file by python prog, or there is some more convenient way
set up a server on you pi
Ok, I have 2 servers on 2 pis, how do i make them chat?
you can use the requests library i believe
FastAPI framework, high performance, easy to learn, fast to code, ready for production
You run a function on one server, to reach out the api of the second server.
That article you said was not related to what you're doing, shows you how to do that I believe.
Here is the example of sending messages to itself, i need to send them to another rpis python )
what you want is akin to interacting with an api from within a server
only the api in this case is your other server
does someone know how to disable schema validation in openapi 3?
Probably I missed something but I read it 3 times and the point of confusion is that server and gpio controller in this example is the same py file
Tbh that article is the closest to what i do of all the articles I googled
But still i dont get the communication thing
You can setup a remote web server, like fastapi or flask. On that remote web server, run a function that sends a request to your rpi server (the ip:port). The rpi server will then capture the request and run whatever function you want it to on that rpi server based on the information passed through.
That make sense?
It's imposdible to avoid static ip? If web server ip is static and client ip is not
The rpi has to be static if you expect the server to do this automatically.
I mean that might not be entirely true.
I don't work with hardware much. There might be a way but you need a way to specify where you are send the information so my guess is that anything dynamic will get complex.
You can have the rpi check for updates every X minutes, I suppose.
Provided every rpi is running 24/7 it can ping web server and update its state every sec
It gets more and more confusing. I imagined it as some kind of chat. Every rpi connects to it and just listens to it
And picks up data if it's ID is addressed
Yea you can use websockets then.
But the connection has to stay open.
But that gets more complex.
I like the concept of websockets, looks like something that would work
Maybe you could think of any example that could help me dig into the communication part better?
How can I strict every user to one account? So users don't exchange passwords and login into eachother's accounts? In C# I used to do it by HWID, is there any way to do it in django, will ip address whitelisting be as efficient?
Hey was wondering if someone could help me out real quick, I was able to parse together a HTML table using BeautifulSoup but now I am wondering how I can search within that table for a specific term?
The IP whitelisting would work, there is some bad points near it like two different users under the same router woundt be able to login. It all depends on how strict you want to be
GitHub - fingerprintjs/fingerprintjs: Browser fingerprinting library with the highest accuracy and stability.
You could take a look at fingerprint too
hi guys is anyone familiar with postgresql?
No, nobody has ever heard of it
Just kidding, just ask your question. (Even though #databases might be a better place, and there is also a dedicated Postgres Discord server)
Yeah thanks haha
I asked in the python general and the databases channel
And it seems that I should install Postgresql on my PC, and then once i am done with my role and the website is deployed, I can safely remove postgresql from my computer and save it in a github repo where the rest of my python backend code will be held
Does that make sense? I've never heard of storing a database in a github repository
PS F:\Flask\Market> set FLASK_APP=market.py
PS F:\Flask\Market> python -m flask run
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
Usage: python -m flask run [OPTIONS]
Try 'python -m flask run --help' for help.
Error: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory.
PS F:\Flask\Market>
i set everything still i am facing error
Only partially making sense
I would recommend installing postgresql to your PC with docker
Having local postgres is good for testing
PS F:\Flask\Market> set FLASK_APP=market.py
PS F:\Flask\Market> flask run
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
Usage: flask run [OPTIONS]
Try 'flask run --help' for help.
Error: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory.
PS F:\Flask\Market>
what i am doing wrong
?
Yeah but I will leave the team after my work is done for various reasons, and won't be having a local postgres on my PC anymore
Docker allows removing photogram without a trace it was there
So the new project maintainers can pull down the database from heroku (where the website will be deployed)?
once i leave?
Think of docker as lightweight virtualization, that is super lightweight and good to be used just to run a single app
Sounds like a shit plan
Yeah I've heard of docker, and I do want to use it, but I'd rather keep my tooling as simple as possible (for this project)
okay so what do I do?
Use managed databases from cloud provider
Would something like a raspberry pi work
Yeah, but a cloud platform will be easier. Heroku free tier Postgres is up to 250mb and super easy to spin up
Only if u a over experienced pervert or just doing it for the sake of experience in homelab
why such harsh language?
Yeah I am planning to deploy with heroku
It was hard to find better words to explain it in a short way ;)
Then definitely develop there too
@wheat verge Haan Bhai Sahi Kaha..... But Sabhi toh ek jaise nahi hote bhai...
Hey, FastAPI people, what does the tags keyword parameter mean?
router = APIRouter(
prefix="/items",
tags=["items"],
dependencies=[Depends(get_token_header)],
responses={404: {"description": "Not found"}},
)
Can't seem to find its docs
Like in instagram if someone posts a picture or photo everyone can see that so how can I code in flask so that if someone books a seat everyone cannot book that seat and get the seat color in grey
Please help
I fiddled very less in web dev. srry ๐คทโโ๏ธ
bruh I am talking about DB
back end a bit
well, in that case
I have only done basics, OOP, and I'm learning data analysis
haven't fiddled with flask yet
sounds like time for SQL database
in the terms of Flask it means using library: SQLAlchemy usually ๐
As for database, PostgreSQL is a good average one
i am very new
can some one tell me do i need to download django after python 3 and vscode
first master the basics like loops, conditionals, functions, objects etc. once done, if you want to do web dev, then i would recommend starting with flask, then moving on to django as flask is more beginner friendly
Hello, is there a channel here where i could ask Sqlalchemy questions?
just drop your question
It doesn't matter because my users would be of different routers
So it would work fine
I think it's for grouping your endpoints together in the generated docs: https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-tags
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Cool, thanks
If I want to sell my django website , where should I sell and thanks alot please hope anyone know a way since I need the money
Hey can someone tell me how how can put my upload button at the center of the block? I have already tried using padding-bottom and margin-bottom. What am I missing?
i fell for this troll yesterday
I did what you suggested that day
Hey was wondering if someone could help me out real quick, I was able to parse together a HTML table using BeautifulSoup but now I am wondering how I can search within that table for a specific term?
Now I want to keep the button at the center
You can watch Tech with tim beautiful soup tutorial for that
https://www.w3schools.com/Css/css_intro.asp
You can use an editor or bootstrap if you dont want to learn css
soup.find or soup.find_all
I have completed this till CSS Lists
so much learning... gotta respect that. just make sure you will use it more than once
Just tell me if I am in the right direction or not? Like ultimately will I have to use padding and margin for this task or not?
to center a single button on the page, you dont need padding. it all depends how you structure it
Okay so maybe I am doing something wrong with HTML code
right now it looks like your "upload button" isnt a button. i think youre working too hard tbh. look at templates and flask
Ok so I used the soup.find and soup.find_all expressions to create an output that was essentially a table, now what I want to do is find a specific term inside that table that I created
unless you wana design css layouts n stuff
what kind of table ? how do you parse it?
Alright
oh you mean the results from the search
i think you can use find/find_all on the results as well cant you?
search = soup.find('table')
content = search.find_all('tr')
for i in content:
table_data = i.find_all('td')
data = [j.text for j in table_data]
print(data)```
This is essentially what I did
Now I want to essentially search this part for a specific term
sorry i didnt see this
Lol no worries
so its is always empty ?
No data does output a table
With the contents of what's inside the tags
['Horaire', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche']
['8h', 'Indisponible', 'Indisponible', 'Indisponible', 'Indisponible', 'Complet', 'Complet', '']
['9h', 'Indisponible', 'Indisponible', 'Indisponible', 'Indisponible', 'Complet', 'Complet', '']
['10h', 'Indisponible', 'Indisponible', 'Indisponible', 'Indisponible', 'Complet', 'Complet', '']
['11h', 'Indisponible', 'Indisponible', 'Indisponible', 'Indisponible', 'Complet', 'Complet', '']
['12h', '', '', '', '', '', '', '']
['13h', '', '', '', '', '', '', '']
['14h', 'Indisponible', 'Indisponible', 'Indisponible', 'Indisponible', 'Complet', '', '']
['15h', 'Indisponible', 'Indisponible', 'Indisponible', 'Indisponible', 'Complet', '', '']
['16h', 'Indisponible', 'Indisponible', 'Indisponible', 'Indisponible', 'Complet', '', '']
['17h', 'Indisponible', 'Indisponible', 'Indisponible', 'Indisponible', 'Complet', '', '']
['18h', 'Indisponible', 'Indisponible', 'Indisponible', 'Indisponible', 'Complet', '', '']
This is the output essentially
What I would like to do is essentially search within this table for a specific term
for list in lists: if "term" in list
So I have to create another loop then, is that it?
Because ideally I want it to find a term let's say like 'Complet' with the corresponding day and time, I don't know if that makes sense
you can roll it up in to a one liner after you have the logic worked out
find methods chain together, result can be handled with a list comprehension, but first get it working
Ok I'll try, thank you!
you'll have this done in no time
bs4 could be webdev or datascience right?
but more analysis than development
more like web scraping
and web scraping is sometimes used for datascience/machine learning
to clean data / or to acquire cheaply
yeah categories are pointless sometimes, web but not dev
is there any ethereum free node i can use?
can someone help me solve cors error, im doing get request to a flask api through axios like below:js axios( { method:'GET', 'url': 'http://127.0.0.1:5000/get_user', mode: 'cors', cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: 'same-origin', 'Access-Control-Allow-Origin':'*', // include, *same-origin, omit headers: { 'Content-Type': 'application/json' }, })
what am i doing wrong, all the cors information is provided for it to allow all and my flask endpoint is also signifying that i've provided cors
@auth.route('/get_user')
@jwt_required()
@cross_origin(origin='*',headers=['Content-Type','application/json'])
def fetch_user():
currentUser = get_jwt_identity()
print(currentUser)
return jsonify({"current_user":currentUser}), 200
this is the response of the axios response
@inland oak any advice?
feel free to send your questions
ok
thanks
<audio controls>
<source src="Shor-Ek Pyar Ka Nagma Hai.mp3" type="audio/mpeg">
</audio>
Could you find any errors in the code
I was working on the HTML Audio controls code
from my experience, you don't really need all those configurations for cors for axios. simply setting cors up in your backend should work
this is the route thats causing the error
@auth.route('/get_user', methods=['POST','OPTIONS','GET'])
@jwt_required()
@cross_origin(origin='*',headers=['Content-Type','application/json'])
def fetch_user():
currentUser = get_jwt_identity()
print(currentUser)
currentUser.headers.add('Access-Control-Allow-Origin', '*')
return jsonify({'hello_from': get_jwt_identity()}), 200
i added the jwt_required() right
which requires a jwt param in the request
