#web-development
2 messages ¡ Page 199 of 1
Ok, once they have that public IP, what do they do with ISPs?
they find which ISP is regstered for this IP address usage
and apperently in registrational data even mentioned towns for particular IPs
Do they use a number from my public IP to do a hash?
why would they need a hash?
they just compare your IP address directly
if "45.76.34.76" in ISP_company_in_germany.ip_addresses:
it_is_person_who_uses_german_ISP_provider = True
print(ISP_company_in_germany.ip_addresses["45.76.34.74"].town_of_registration)
# printing "Berling"
This answers what I was trying to question
This information is really useful, thank you so much!
u a welcome
although technically, they could be using hashes anyway ;b
for example if the data stored in dictionary
when accessed with key
ip_addresses["45.76.34.74"]
it makes the value auto hashed to find the data in the dictionary
but that's just theoretical thinking. we know nothing about how they store their data
it could be some SQL database or smth like that
then real request is SQL query
I see :)
Look at this
class Config(object):
"""Base config, uses staging database server."""
DEBUG = False
TESTING = False
DB_SERVER = '192.168.1.56'
@property
def DATABASE_URI(self): # Note: all caps
return 'mysql://user@{}/foo'.format(self.DB_SERVER)
class ProductionConfig(Config):
"""Uses production database server."""
DB_SERVER = '192.168.19.32'
class DevelopmentConfig(Config):
DB_SERVER = 'localhost'
DEBUG = True
class TestingConfig(Config):
DB_SERVER = 'localhost'
DEBUG = True
DATABASE_URI = 'sqlite:///:memory:'
Retrieved from
Why not getting the IP programatically than hardcoded?
why are using documentation for older flask versions?
https://flask.palletsprojects.com/en/2.0.x/config/
it is already 2.0
is it by intention?
Oh, I'm only using that code as example because since it's there I assume that it's a common practice to hardcode it
So, my question is why is it a common practice, since from my judgement it'd be better to get them programmatically
sure, I get IP usually with
import os
DB_HOST = os.environ["db_host"]
the most common practice to get the values from environment variables
Although, you then would have to hardcode the IP into the environment variable, it ends up being the same
and if wishing for some simplification, then additionally used .env file, that basically loads the value to environment
which allows the program to load variables to load then like they are from environment too
.env file example
db_host="localhost"
user="root"
we have a choice in how to load variables. two choices then.
export VARNAME="123123123"
in operational system
or using .env
P.S. no idea why they hardcode values
In a production environment, let's say, a server in digitalocean, nginx + gunicorn + flask, no docker, what would be put in the DB_SERVER as best practice?
database best practice hosting in priority from best to the worst:
- using Managed Database from cloud provider (DigitalOcean gives them) (the best, low effort, maximum result choice)
- Having separate server with database only, but if you wish having it HA, it will take much more efforts than Managed DB
- Having database installed at the same server where application is
- Having database in container at the same server where application is (usually best only for development environment at local machine having container with database if you need it ;b )
Having separate server with database only, but if you wish having it HA, it will take much more efforts than Managed DB
You make an HTTP request to a separate server from your main server once you receive the HTTP client GET request?
Ok, so you use the TCP protocol, how are queries serialized..?
receive request -> need info -> ask the server hosting the database
In what "shape" do you ask the server?
all this stuff is handled by database libraries. we don't deal with level usually.
but if you wish to know...
if you have SQL database, you are using it with requests in raw SQL language or with ORM library syntax
example of raw SQL is: SELECT stuff from TABLE...
example of ORM: in your chosen programming language, you write classes and access their functions to send of request stuff
regardless of the choice, at the last step your request to database is always convereted to raw SQL language like
SELECT stuff from TABLE in DATABASE
WHERE things = "blababla"
and your libraries handle how the answer is received, you are giving values or cursor to read through values (basically certain SQLish syntax to read the answer)
and the easiest to read form to get database answer goes if you use ORM, then you just receive objects in your programming language, like classes
Ohhhh!
Ok, so the database URI can be a remote URI, that's the only thing that changes
you mean in terms of settings? no.
different URL of database (optionally port?)
different login
different password
different database engine (besides PostgreSQL, exist other forms of SQL databases)
usually those params
Ok ok, this is blowing my mind. I have my models defined in my gunicorn + flask server using SQLAlchemy, now how exactly having the database in other server can work with my models?
read about SQLAlchemy library
I make the db connection. This points to a URI of a database and user created in my machine
If you have the database in another server, wouldn't it make sense to just have to change the URI?
yes, we just change address of the database with pointing to different machine
So, why is the answer no?
not understanding the question enough
Database URI can be a remote URI <- you have your db hosted somewhere else, the URI you make the connection to in your main server is the URI describing where the db is located remotely
yes, exactly
Sigh! Now I understand, it's very simple
Why is having it in a separated server better practice than having it locally?
Independent resources for traffic load:
example: Your application has a lot of user flow, it overloaded app or database, but both go super slowly because they affect each other.
if you use different servers, your database server could be having more space at server, while app server could be having more CPU ;b
Independency for updates (that's actually the imost important):
You already went to production and database has a lot of stuff
You made new update to application, that requires a lot of changes to server, to nginx, to other small dependencies.
Usually the easiest way to update... is to delete server and to install everything from zero (with InfrastructureAsCode instruments in ideal way), but if they at the same server, you can't do it.
+independent monitoring btw
example:
Your app makes high CPU load due to stuff it does. With having it on separate server, you see how much resources only your application eats
go super slowly because they affect each other
I don't undestand that part
Ohh, that's a point I understand
with having database on separate server, you see how effective your SQL requests, you see the load on the database with server
SQL queries can be written in a super bad way that makes super high load to the server
How do they "affect each other"?
sharing same CPU (which is limited too), same hard drive (that has limit in write/read capabilities)
sharing same RAM (and that's limited too ;b)
Main server:
Lots of RAM, good CPU, almost no storage
DB server:
Lots of storage, good CPU
If all in one server:
Lots of RAM, good CPU, lots of storage
How is all in one server bad?
the most important is indepency for updates as I said
Ohh, ok ok
So, in this regard, it's the same thing, right?
with having in separate servers, you can clearly see how much resources each application part takes....
...but!
there is downside to having separate servers
Yes yes, I mean in that specific regard
In the specs
This wise, is the same thing, only this wise, right?
with having in one server, you could monitor actually every part of your application easily. Everything at the same server
but with having a lot of servers, each taking only part of application, you need more advanced logging/monitoring/deployment instruments
that handle the increased complexity
But! having on separate servers... will be more preferable for scalability always anyway
because....
If you have on one server...
Independency of updates
your APP is limited to scale only vertically
there is a limit in how well one server you can buy
with if your application parts take different servers
you could scale them horizontally
buying more servers
copying your application parts to multiple servers and redirecting users randomly to one of them
I imagine they have a lot of servers, but only one for DB, and these servers access the same thing
for database it can be an issue having just one server
server goes down or corrupted => database is lost or really hard to recever (with backups it is easier though, but still small lost of data)
people setup HA databases that make copies of the data in real time to several database instances
if one of them goes down
second database is enabled without any delay
people don't notice that one of database servers went down, if there are several databases that work in replica
What is HA database?
imagine having one server with database that your application uses
your can make reading and writing operations to it
Ok, two servers, one for app, one for server
but everytime when you send new data to the main database, it copies all data to second or third database
the second and third database share basically delayed copy of all data, you could even use them purely for reading to decrease the traffic load in main databhase
Ok, that blows my mind
if main database goes down, you could make second database as main one
digitalocean offers managed database as service
takes complexity away for this, for a price
That's very good
Makes sense, very good feature
So, let's say you buy the managed database
How do you integrate it into your app? They just provide a URI?
yeah
imagine having one server with your main flask app
and lets imagine you copied it to two more servers
and created fourth server, that has load balancer (for example: Haproxy, or managed load balancers from digitalocean)
All it does... receives request to your flask apps, and redirects randomly to one out of three your flask app servers
thus, the load for your flask app is distributed between three servers (+load balancer)
This is where you lost me, what is a load balancer?
It's impressive. I learned so many things from this conversation
You are really kind, I really appreciate it
Ohhhhhhhh
user comes to load balancers and get redirected to one of flask app servers
and the best part... load balancers checks if the servers behind him are alive!
Nono, wait
HTTP request to load balancer server, load balancer server what does it do then to check what server to proxy the request to?
every blue server, has your flask app and nginx instance
load balancers takes request first and sends them to one of your nginx'es
and nginx at specific server, sends request to flask app at the same server where nginx is
load balancer sends requests to the servers in a rule that you setup. Randomly to one of them, In a sequence choosing each one, or to which server had less connections
Ohhhhhh, awesome
And the most awesome part about load balancer, it can check which server is alive đ
if one of your flask app goes down, it will direct requests only to two remaining servers, it will ignore the third that went down
Alright, how is the load balancer integrated behind the scenes of that URI DigitalOcean gives you?
Exactly, I see that's the main purpose
URI to what
To the managed database
you don't need doing anything with this URI
it is already HA database
it has already somewhere hidden load balancer, or whatever, we need to read specific in how they offer it
Just to chip in to this conversation, you can easily test what a load balancer does by signing up for a free AWS account. Spinning up a free EC2 instance and applying an elastic load balancer to said EC2 instance. https://aws.amazon.com/elasticloadbalancing/
Ok, I see!
no
HA database can be managed database
but you can setup HA database as not managed, on your own, it is just much more difficult
Alright, I asked what is a HA db, then I interrupted asking what is load balancer. Now, we are coming back to what is a HA database
the point is, HA database, High Availiablity database, is the database that has more than one instance/uses more than one server
for the purpose of backup in real time, and when one database server/instance goes down, second instance starts being used without any delays
High Availiability, always available database, regardless of the server destruction
Alright, and a load balancer proxies requests. Where is it in a HA database?
load balancer could be needed in HA databases in some of its setups, depending on how you setup it
as I said, multiple databases instances could be used to decrease the load from one database
we could use other databases for reading too at the same time
load balancer would redirect our reading requests to one of databases with the least amount of connections
HA database -> has more than one instance/uses more than one server
Load balancer -> decides the best server to use
HA database -> decides the best server to use
HA database -> MUST use load balancer
Then, why are some HA dbs that do NOT use a load balancer?
it depends on which things we wish to get from database
we could be wishing only 100% time uptime from database even in the case of one of its instance destruction, with backups in real time, but without traffic load distribution
in first choice we don't need LB, in second where we wish traffic load distribution between multiple DB instances, we need LB
possibly those databases setup can be having different names
Do you have an example of technologies used to set a HA database yourself?
Awesome :)
the guide mentions load balancer as HAProxy
I have enough to google for a whole lot of time
Yes, I have to get back to what I was doing hahaha
I should really get back to my studies
What!? Absolutely not
What!? Did so much time pass
I can't believe it
I thought it was 30 minutes at much
scroll up and check time ;b
Thank you VERY much for this help
if anyone worked before with flask web apps which have a webcam integrated could you give me some advice?
u a welcome
How do I return a response 'status' : 'successfully changed password' when password is changed... I am aware that the update function in UserSerializer must return a user instance and not a response...
class UserSerializer(serializers.ModelSerializer):
"""Serializer for the users object"""
class Meta:
model = get_user_model()
fields = ('email', 'password', 'name')
extra_kwargs = {
'password': {'write_only': True, 'min_length': 5,'required': True, 'error_messages': {"required": "Change this"}},
'email': {'required': True,'error_messages': {"required": "Email field may not be blank."}},
'name': {'required': True,'error_messages': {"required": "Email field may not be blank."}},
}
def create(self, validated_data):
"""Create a new user with encrypted password and return it"""
return get_user_model().objects.create_user(**validated_data)
def update(self, instance, validated_data):
password = validated_data.pop('password', None)
user = super().update(instance, validated_data)
if password:
user.set_password(password)
user.save()
return user, Response({'status': 'Password changed successfully.'})
return user```
hi i'm new to Flask/Django. I want to know how to automatically create a Flask/Django project in VSCode without manually setting up files/folders everytime. Thanks ^^
ohhh
Does anybody know how to create any type of contact form that directly sends the mail to your inbox?
OpenAPI question: why is this giving the error Path parameter 'loginIdentifier' for 'get' operation in '/login/{loginIdentifier}' was not resolved? I have a $ref resolving it?
Minimal Config: https://paste.pythondiscord.com/teguzunutu.yaml?noredirect
Django questions
I use django-storage and MinIO to store static/media files in S3 storage. But when I try to upload some file, it raise EndpointConnectionError
raise ImproperlyConfigured("You're using the staticfiles app "
django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.
;-;
hey @olive hedge check out https://dev-neha.blogspot.com/2019/04/beginners-guide-starting-django-project.html
thanks
Actually if you are new the you should enjoy to creating a new project and learn how the app and moduler structure of Django
And for advance you can write you own bash script to setup or any docker container will help you out
Question!
@app.after_request
def cors(response: Response) -> Response:
if request.headers['Origin'] in app.config['WHITE_HOST']:
response.headers['Access-Control-Allow-Origin'] = request.headers['Origin']
return response
I have that code in my flask application
It's supposed to implement CORS
And.. it works. But there's a whole module for CORS, and this is too simple, and I suspect I'm doing something terribly wrong
It's quite self explanatory
Do you spot something wrong?
Thank you very much beforehand!
any dev ready to make team to compete in hackathons?
my skills: python, django, sql
Might be interested. I'm full-stack React+Django/Python.
Interested
hi guys. i got this issue with sqlite3
i fully pip installed flask_sqlalchemy and flask_login already but still cant run sqlite3 database.db
It just means you don't have sqlite3 installed to your system. Python's sqlite3 is a builtin module separate from any system executables.
class pathlib.Path(*pathsegments)```
A subclass of [`PurePath`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath "pathlib.PurePath"), this class represents concrete paths of the systemâs path flavour (instantiating it creates either a [`PosixPath`](https://docs.python.org/3/library/pathlib.html#pathlib.PosixPath "pathlib.PosixPath") or a [`WindowsPath`](https://docs.python.org/3/library/pathlib.html#pathlib.WindowsPath "pathlib.WindowsPath")):
```py
>>> Path('setup.py')
PosixPath('setup.py')
``` *pathsegments* is specified similarly to [`PurePath`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath "pathlib.PurePath").
i searched for it and i found this
you don't need to install sqlite3 (to use it from python)
you do need to install it if you want to use it as a cli program
ubuntu sqlite3 flask wsgi apache2
error log
sqlite3.OperationalError: unable to open database file```
default.conf
<Directory /var/www/html>
Order allow,deny
Allow from all```
Its not overloaded or permission, then why it cant open db?
U know that sqlite db file should not be anywhere close to Apache web server?
Because u don't want to share your db as static file to everyone
Apache should serve only as reverse proxy to flask and serve your static images
I dont mind about security problem
đą
Oh wait you need to put sqlite db in static folder?
solved conn = sqlite3.connect('//var//www//html//hs.db')
anyone
forloop.counter15 <= 30
thx bro
how can i add a switch in the html that runs code in flask
No problem. Easiest Google i did today.
Iâm creating an API that requires authorization.
Should I use JWT or an API key?
JWTs are often used as API keys, they're not mutually exclusive
But if I use an API key then I have to store it in a database whereas if I use a JWT then I can validate it with code
Uhh, that doesn't make any sense. How would you know what the JWT is supposed to be?
Almost any auth system will need a database of some kind
No
Thatâs not how JWT work
A user signs in with username and password and is then given a JWT. That JWT is then packaged with some piece of data and is signed with the sever secret key
And you'd validate that how?
When the user makes a request and sends the jwt then we can decrypt it with the server side secret key and extract the data
If the jwt is corrupted then the data would not be there
I... don't really get that. So you'd store username and password inside that data?
I don't see how you wouldn't need some data storage.
Maybe I'm just misunderstanding, idk
No, you would store whatever you want but usually youâd store just the user name and expiration date of the jwt
Anyone else have thoughts?
what kind of data do you want to store for the user?
if you want to store lots of data you can use jwt to encapsulate it in the middle portion of the token afaik
otherwise you should use api keys because it's easier for devs to add them to request, typically as a url parameter
Wait API keys as a url sounds like a bad idea? Itâs public and not encrypted
yes
in general API key in URL is Bad
as well as claims, if you're planning on authorisation
and not just authentication
If you want a simple api key without a database, store a bcrypted key as an env variable and then send the raw key, check the hash. Depending on what youâre protecting, itâs reasonably safe.
@native tide can you expand on that?
Sure. It doesnât work as well if you have lots of users, but if thatâs your use case you probably want a DB. Say you make a 16 char key. abcdefghijklmnop you use bcrypt to salt and hash it. Take that result and store it in an env variable thatâs read in. Now you pass the original abc key with your api calls, do the same hash and check it against your hashed version. Thatâs basically how a traditional password in a database works.
Really dependent on your use case. If itâs one service talking to another, this is an easy, relatively secure way. If you have a front end react app, this would be a bad setup.
I can send some example snippets in the morning.
When user receives JWT, he receives in general cookie. Preferably protected from JavaScript interaction flag.
That contains not encrypted dictionary of any information that says which is it user. Which ID in db, which email to verify in addition if we wish. Or level of user rights could be written to it also. Or when time to expire for the token
The trick is... With dictionary he receives special signature. Which is created with your secret code. It verifies the information from tampering. If the user changes any bit in dictionary, signature becomes invalid. Or if set time became expired, it becomes invalid too.
When any of our servers receives the JWT back, we can verify that it is ours by checking with secret key. We don't need to address database for verification, and that makes JWT perfect for shattered architecture like microservices, where we have clear separation between Auth and other app parts. As we can Auth user, without verificating request to Auth app. All we need same secret key as Auth app.
And we'll know everything even the amount of user rights, safely transmitted by user to us.
Just don't put any sensetive information into dictionary though. If u don't want the user to read it. Because the dictionary is encrypted just by transport protocol base64
I'm trying to send data from frontend (js) to backend (py, flask) and it isn't wanting to work. can someone help?
JS code:
let url = "/addprofile"
let data = { "name": "urmom", "id": "01293" }
fetch(url, { method: "POST", body: JSON.stringify(data) });â
Python code:
https://cdn.selectthegang.tk/file/Screenshot 2021-11-04 12.16.37 AM.png
It returns None in console when called
out of curiosity, enable debug mode and put breakpoint in your python code
dir(request) to see other available attributes and methods
there should be raw html document available, smth like request.data, request.body, request.html or smth similar
you will see what you really receive there from frontend in raw format
So i enable debug mode, set a breakpoint for the "data" variable and attempt to call it
I'm using Replit but there is a built in debugger
perhaps smth wrong with your javascript code too, not sure đ¤ˇââď¸
I would usually write first test in python that calls my request in python and verifies it
then I would have tried doing the same in javascript
JavaScript is my first language, and it looks correct to me
No, not yet
although if python at localhost, probably it is not an issue yet
Replit isn't local, it's cloud based
then it is an issue too highly likely
more can be found only with knowing which error you get
ah and yes, you can debug with putting word breakpoint()
if replit allows it to you
Replit has a built-in debugger
dir(request) right?
that does not look like a good way to debug it
i was thinking you would output it right there in conosle
It kept returning an error saying it was a list
In console, it returns
@inland oak
enable debug in flask, at flag/config/env level for more detailed error descriptions
we surely wish to know at least the which http code error it is
is visual code better for beginners???
copy to the end, and copy, not screenshot
visual studio code*
- Serving Flask app 'main' (lazy loading)
- Environment: development
- Debug mode: on
- Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployment. - Running on http://172.18.0.4:8080/ (Press CTRL+C to quit)
- Restarting with stat
- Debugger is active!
- Debugger PIN: 360-609-423
172.18.0.1 - - [04/Nov/2021 07:29:55] "GET / HTTP/1.1" 200 -
172.18.0.1 - - [04/Nov/2021 07:29:55] "GET / HTTP/1.1" 200 -
172.18.0.1 - - [04/Nov/2021 07:29:55] "GET /static/style.css HTTP/1.1" 304 -
172.18.0.1 - - [04/Nov/2021 07:29:55] "GET /static/auth.js HTTP/1.1" 304 -
<Request 'http://replstories.ml/addprofile' [POST]>
172.18.0.1 - - [04/Nov/2021 07:30:07] "POST /addprofile HTTP/1.1" 500 -
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 2091, in call
return self.wsgi_app(environ, start_response)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 2076, in wsgi_app
response = self.handle_exception(e)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 2073, in wsgi_app
response = self.full_dispatch_request()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 1519, in full_dispatch_request
return self.finalize_request(rv)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 1538, in finalize_request
response = self.make_response(rv)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 1701, in make_response
raise TypeError(
TypeError: The view function for 'add' did not return a valid response. The function either returned None or ended without a return statement.
definitely optimal best choice;
@app.route("/addprofile", methods=["POST"])
def add():
if request.method == "POST":
data = request
jsonData = data
print(jsonData)
#return jsonData
end the function with smth like
from flask import jsonify
@app.route("/addprofile", methods=["POST"])
def add():
if request.method == "POST":
data = request
jsonData = data
print(jsonData)
return jsonify({"status": "post request, yay!"})
return jsonify({"error": "not post request, not yay"})
probably error code can be returned here
return jsonify({"error": "not post request, not yay"}, 400)
the point is, jsonify returns.... json in Response form
flask functions should return Response objects
that what jsonify does if I remember right. it is been a long time since I used it
<Request 'http://replstories.ml/addprofile' [POST]>
172.18.0.1 - - [04/Nov/2021 07:35:46] "POST /addprofile HTTP/1.1" 200 -
i still need the json
200 means you received valid json answer in your javascript
read in your frontend the answer
\
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
open the promise request, it is async request. u a sure you know js? đ
except i didn't get the data i need in backend
change the left bit
def add():
if request.method == "POST":
return jsonify({"data": request.json()})
return jsonify({"error": "not post request, not yay"})
I don't remember syntax for getting json in flask already
return.json() was it I think?
File "/home/runner/stories/main.py", line 84, in add
return jsonify(request.json())
TypeError: 'NoneType' object is not callable
def add(request):
if request.method == "POST":
return jsonify({"data": request.json()})
return jsonify({"error": "not post request, not yay"})
forgot the request in add declaration
File "/home/runner/stories/main.py", line 84, in add
return jsonify({"data": request.json()})
TypeError: 'NoneType' object is not callable
fetch(url, { method: "POST", body: JSON.stringify(data) }).then(response => response.json())
.then(data => console.log(data));
https://stackoverflow.com/questions/10434599/get-the-data-received-in-a-flask-request
trying this then
import json
json.loads(request.data)
or request.json, or request.get_json(force=True)
Those two books can be useful:
{'name': 'urmom', 'id': '4949494'}
172.18.0.1 - - [04/Nov/2021 07:45:29] "POST /addprofile HTTP/1.1" 200 -
hooray, everything works
u received your data back
which was python code succesful?
yep
Been thinking of restructuring my app's controllers to their respective routes, like ./controllers/ __init__.py for / route, ./controllers/users/delete.py for /users/delete route etc. What do you guys think of this pattern?
Based on Next.js's way of routing
I think that usually view functions in python should possess so little code, that it is not needed
all logic out of them should be moved to somewhere else... to model for example
well, at least I divide my applications to sectors like
/controllers/users/views.py in your system
and that's usually enough for me to have tests for current section /controllers/users/tests.py
but that's probably depending on the size of the application
perhaps there are some cases when further dividing is required
basically I make dividing based on the amounts of tests I need to the section đ¤ on tests which I can categorize meaningfully to the same category
@inland oak hey bro , willing to help me? i wanna deploy static files to production lvl
Yeah I usually relocate long codes to helpers.py or something
The previous pattern seems interesting since I could test each routes with the structure as ./tests/users/delete.py and relate easily with the corresponding controller
it has some merit
but usually application is not only CRUD like, so pattern get/create/update/delete would be not fixed for your filename paths
that will make some confusions.
better perhaps keeping all views in.... views
Got it, ty
Out of curiosity how do you structure your apps?
I'd guess based on functionality?
I just use structure suggested by Django in a next way:
for every meaningful app part I have created folder that contains files:
model.py, urls.py, tests.py, views.py and e.t.c.
mm how to divide is a bit difficult, usually it is based on the domain specifics. (you could say functionality too)
and I say said, it depends on having all tests of one category meaningfully in the same category.
So, different folders for example to "Cars", "Drivers" and e.t.c.
basically it depends on business model and/or on essential entities to SQL database
properly abstracting layers of different logic layers still escapes me I guess, there should be some room for improvement
Okay thanks
I always overthink stuff like this and barely work on features haha it's a problem
there is always room for improvement đ in healthy doses it is quite good to question things like that
hi guys, i need help on Flask problem
hello! i m having some trouble on a flask web app in which i have a camera integrated in a webpage and i d like to try to make it take a photo or something like that. the thing is i have in backend a function that takes photos and gets the text out of them. like a lable scanner. but i can t figure out how can i actually take the photo in browser and send it back to use it
hi, how can i sort of prevent users from altering form submissions (Flask)?
What do u mean by that
how can i turn off the camera in flask? i have a videocapture variable and on press of button stop i do videocapture.release() but it still shows in browser and keeps working?
i want to perform a validation where i check what the user submitted and compare it to my DB
Still it does not explain enough
hi
apache2 wsgi ubuntu flask can enable debug mode?
sure, enable flask debug
read server logs from web server that launches flask
and read apache2 logs
Guys, I'm new to python. I'm programming on a Linux machine, I made a login area in HTML and CSS, I created a SQL database with a table called users, I wanted to connect to my python backend. Can I do this without using frameworks? I installed the response for this. Can someone help me take this first step with POST and GET requests to connect to index?
:incoming_envelope: :ok_hand: applied mute to @autumn birch until <t:1636037465:f> (9 minutes and 58 seconds) (reason: links rule: sent 17 links in 10s).
Yes but I prefer to read browser version error log
flask default development server in debug mode will tell browser errors too
but u will read only flask errors
for apache2 errors you should go to its log file
How about read Internal server error from browser
in a html file i have some textboxes that i want prefillebd based on some data i m processing in the backend. i ll have a list of words and 3 textboxes.
if i have a funtion that returns the list of words
can i have in the html file sth like
<input type id etc value = {{ url_for(function that returns word list[0]) }} >
?
url_for would just fill in the input with the url to your function (if it's registered). It wouldn't actually call it.
You can provide the function or the result of the function in your jinja template call.
i.e.
app.py
@app.route("/page.html")
def mypage():
return render_template("page.html", words=get_words())
page.html
<input value="{{words}}"/>
i did something before for returning a video feed where i returned Response(function(),and some mimetype)
is that the same thing or ?
and to this could i have in page.html words[0]
aight thanks
and if i already got the html file i can do another app route
like create another app route which renders the same template
thanks a lot
1 more thing
inside the {{ }}
i ll get the variable words which might have 1 2 3 or more words
how can i write something like
if len(words) > 0 words[0] , if len(wods)>1 words[1] and so on in each {{ }}
cause sometimes i might get less than what i actually need
You can either use {% if xxx %} ... {% endif %} or {{ x if y else z }}
maybe you actually want a for
{% for x in list %} {{ x }} {% endfor %}
@dense slate yay, at last I join the frontend too. But I chose Vue.js to start my path there ;b
vue is good
I was very tempted to choose Svelte đ
oh yes i forgot about that syntax thanks a lot đ
but decided I should better choose more... solid and stable framework
plus reusable for next job
Here's something I wrote up to help with updating object props reactively.
utils.ts: https://www.toptal.com/developers/hastebin/isapoqoxom.typescript
component.vue: https://www.toptal.com/developers/hastebin/uxonehifom.vue
hey, what's the new hastebin service that doesn't have an ugly url like that above?
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
I have ~100k tasks that I need to put into a celery queue, and I want to fire a callback when all of them are complete. What is the best way to do this?
I know about chords, but I need to get these tasks onto the queue as fast as possible and I'm worried about memory limits for the enqueueing thread. Can you get around those somehow while using chords?
Awesome!
yup. already went through html/css book and just finished javascript book
the next book on the queue
xD from Monday going to have a lot of practice at work with it
already planned few books to deepen my CSS knowledge just in case đ¤
does someone know how to lift the placeholder
up
i tried using padding and margin none of em worked
imagining how to debug the code that could not be seen
Becoming Neo to access matrix
dosent input automatically get in the middle? @inland oak
imagining how to debug the code that could not be seen
its not debuging
Defaults align html stuff at the top left, from left to right
Everything else by default depends on object sizes
my bad then-
!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.
Screenshots are bad, copy pasting is the way
Not having pc under the hand. Plus not complete code anyway. Went to sleep
im confused
those are made for only python
That is just CSS, I see no html
thats why im asking in #web-development
Rendered html can be still coppied
<h1>Contact Info</h1>
<input type="Text" name="Text" placeholder="Username">
<input type="email" name="email" placeholder="Email">
<input type="Text" name="About" list="About" placeholder="About">
<datalist id=About>
<option>Reason1</option>
<option>Reason2</option>
<option>Reason3</option>
</datalist>
<input type="Text" id="id1" name="Details" placeholder="Type">
<button type="Submit" class="button">Send</button>
</form>
input{
display:block;
width:400px;
height:50px;
margin:5px;
border:none;
outline:none;
font-size:15px;
border-bottom:1px solid white;
background:transparent;
color:white;
}
there
Much better, the willing person can truly help now.
Went to sleep, already in bed. From phone can't help that much
okay
Oops, I messed up somewhere. ```
[Vue warn]: Invalid prop: type check failed for prop "modelValue". Expected String with value "[object Object]", got Object
flask
@app.route('/',methods=['GET','POST'])
def home():
request.form.get('etc')
return "best page"
will request.form.get('etc') only search for post param called etc?
or get too
property values: CombinedMultiDict[str, str]```
A [`werkzeug.datastructures.CombinedMultiDict`](https://werkzeug.palletsprojects.com/en/2.0.x/datastructures/#werkzeug.datastructures.CombinedMultiDict "(in Werkzeug v2.0.x)") that combines [`args`](https://flask.palletsprojects.com/en/2.0.x/api/#flask.Request.args "flask.Request.args") and [`form`](https://flask.palletsprojects.com/en/2.0.x/api/#flask.Request.form "flask.Request.form").
For GET requests, only `args` are present, not `form`.
Changed in version 2.0: For GET requests, only `args` are present, not `form`.
To answer your question, it will only search post params
great :D
you might want to do a check of the request method
if you want to do different things for GET or POST
ubuntu apache2 flask
ModuleNotFoundError: No module named 'pyotp'
But pip3 list, pip list have it
I need help
When I enter the link http://api.example.com:5000/ironman comes this error but it should come something
# Flask
application = Flask(__name__)
# application (ironman)
@application.route('/ironman')
def ironman():
return random.choice(ironman_gifs())
# setup
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000, debug=True)```
Is this all local? Does your server have access to the folder where the gifs are?
The gifs are not local on the server but are different urls that are randomly selected
And in ironman_gifs() he goes to fetch the links
can you post ironman_gifs()
thats my json
and from ironman_gifs() it should select the links randomly
But I can not and he says I have no access to anything not even to the main page
when i go to the page the photos in it place and its removed after while
you aren't actually entering example.com, right? should be something like 127.0.0.1:5000/ironman
Hi i'm making a model in django, and I want to store all the codes used by a person is thier model, how would I do that.
used_codes = models.?? what here
preferably an list where I can apped the code
example is supposed to represent my domain I do not really enter example xD
just checking
you probably want another model with a foreign key to the user
hi i have a prp when i edit anything in my code its have a err
and i do it
right
what's the error?
So I entered my ip without the domain and it says no access to resource so the same error as above and with my domain it is the same
if you're running local, there is no domain, right?
the images gone
The site is already running on my server but if I do it locally on my pc everything works
ah okay...does your webserver have access to the json you're serving
Question, how do socket connections get closed after the client closes the browser?
Yes the json is on the server in a file and is also connected to the app.py
I mean, I know you can do a disconnect() in the frontend, but let's say someone injects code into the client that doesn't disconnect the socket connection. What do you do then?
I don't understand your question
can you please post the ironman_gifs function?
are you serving this file as a static file somehow with flask? it seems like your webserver doesn't know that data exists
wydm ?
test app
I send you screen from my data
I don't know what images gone means. If you want me to put the time in to answering a question, you need to put the time in to post an actual question, not a link and handful of words.
Is everything there ?
the data folder is there, but once it's running as a web app it reads things differently...you need to look at serving static files from flask
this will show u
how i have to make data in static folder inside or how ?
that doesn't happen when I go to the link you posted
mmm
so
restart pc
??
my pc
not ur
hmmm, I'm actually not sure
that was my initial thought, but maybe not
It will be difficult to find out what the problem is :(
Can you tell me more about your deployment? You're running on a VPS running Linux, right? How are you starting the flask app on the server? gunicorn? something else? Is it behind a reverse proxy like nginx?
I use Ubuntu 20.04 LTS and use apache2 with Python3.9
So Apache receives the request and routes to your application? That means you started flask and have it running on localhost at some port? How do you start flask?
i wanted a custom port and made 4444 and at host 0.0.0.0
if __name__ == '__main__':
app.run(host="0.0.0.0", port=4444, debug=True)```
what does starting the api with apache2 look like? you wrote in the config?
it seems like you're using the flask development server in "production" which you don't want to do
Well I set the api.conf to available
What do you mean by that now I am completely confused ?
Can someone take a look on #âhelp-coffee please ? 
I'm not sure how apache2 works, but for nginx, it handles the web request and passes it on to your actual server
I took out some info, but mine looks something like:
listen 443 ssl;
server_name mydomain.com;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
}
location /static {
alias /srv/www/static/;
}
}
I have probably set it completely wrong
This is called a conf in apache2
to activate your page
right, does yours point to your running flask application?
I run my flask app on :8000 with gunicorn
well mine is django, but same idea
This is my conf only that at example.com is my domain and not example
my guess is this is an apache thing and not a flask thing. I don't know enough about apache to help here, sorry.
not that I know of, maybe someone here will see the convo that knows.
Found something that is quite new for two months but I do not know exactly what this means
https://stackoverflow.com/questions/68698686/403-forbidden-you-dont-have-permission-to-access-this-resource-apache-2-4-29
Hm? I don't understand what you mean. I appreciate the help! Can you elaborate further?
Hey all.. i am stuck! what can i do without JS.
if prod_name == '4' << from CHOICES. then i want to disable prod_quantity in form. any idea?
i probably misunderstood what you were asking. sorry. sounded like your were worried about browser connections being secure
Thank you so much! For react vs next, I thought that they were meant to be used together since next uses react i believe. For the coding portion, do you have recommendations for the proces of coding? For example, would I start with html/css, then incoporate react, and then link it to express and a database? Currenty, I have two github starter repositories, one for front-end (https://github.com/jpedroschmitz/typescript-nextjs-starter) and one for back-end (https://github.com/ljlm0402/typescript-express-starter)
Non-opinionated TypeScript starter for Next.js. All the tools you need to build your next project âĄď¸ - GitHub - jpedroschmitz/typescript-nextjs-starter: Non-opinionated TypeScript starter for Next....
How can I allow another server to call my (Python) API by authenticating with certificates. No username or password just certificates?
Better to apply framework from the start, they have an alternative way to deal with html
- 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
Next is simply an extension on React. You'd still needreactandreact-domas dependencies, and for the capabilities they provide.
i usually assume, react is Create React App ; b
Ah, I usually assume the opposite because every time I use react, I roll a custom setup, whether that's vite or webpack or something else.
hey guys, i have a question about nginx. When deploying a react app, must i already have a server (that i can access via ssh) to install nginx on it and serve static files or i can create a config folder in my root project and somehow deploy it? So, what is the process of deploying react apps with nginx. I watched a lot of tutorial on yt but they all use already made ubuntu servers and access them trough ssh, but i deploy my app on google app engine and don't see any way to connect to it through ssh. Thanks.
@signal iris You will need the Node Server to deploy the React App built.
i already have a server.js file with express, serving static content, and it starts by typing npm start, but i want to use nginx instead of express and my question is how am i supposed to do it?
Do you want serve the static files without Express?
Does anyone know why this isn't getting bypassed?
I specified the
X-Forwarded-For
Header and one of the IP's from the array but it doesn't seem to be actually bypassing
<?php
$whitelist = array("127.0.0.1", "1.3.3.7"); //whitelisted IP's
if(!(in_array($_SERVER['X-Forwarded-For'], $whitelist))) //checks if the header is not set and compares the value of the header to the array if its not true it gives us a 401 below
{
header("HTTP/1.1 401 Unauthorized"); //401
}
else //else statement from the above statement is called I know I don't have to specify the else because the statement above says if it's not in the header and compares however I want to make things neat instead of just writing code thus I used the else statement
{
print("lol"); //just prints lol
}
?>
Context: I am making a blog on a few things and I am trying to implement a white list bypass and this should be an insecure way because if the
X-Forwarded-For
the header is set to one of the IP's in the array it should be returning true thus printing lol not sure why it is not working though?
Thanks.
Nginx can serve the static files without Node server.
I have also sent the request manually too and then tried with Python both 401's
Did you check the value of $_SERVER['X-Forwarded-For']?
The check should happen here
if(!(in_array($_SERVER['X-Forwarded-For'], $whitelist)))
It checks if the X-Forwarded-Header is not set and or if it is it checks if the value is one of the IP's from the array? If that's what you mean.
I have tried a few things, I intentionally want it to be vulnerable. Not sure why this isn't working though tbh
$_SERVER['X-Forwarded-For'] is always NULL, so it shows 401 error.
Someone in #help-kiwi found the solution turns it it has to be HTTP_X_FORWARDED_FOR not just X-Forwarded-For when checking.
<?php
$whitelist = array("127.0.0.1", "1.3.3.7");
if(!(in_array($_SERVER['HTTP_X_FORWARDED_FOR'], $whitelist)))
{
header("HTTP/1.1 401 Unauthorized");
}
else
{
print("lol");
}
?>
Works.
Yes you specify the header in the request
import requests
Headers={"X-Forwarded-For":"127.0.0.1"}
r = requests.post("http://0day.fun/Blog/bypass.php", headers=Headers)
print(r)
Would bypass the code.
As it trusts the contents of X-Forwarded-For instead of doing REMOTE ADDR
I did that and it worked but when I put this code on any other page it doesn't work and this is on the same for loop but I'm on page 2
{% for post in posts %}
{% if forloop.counter <= 15 %}
<div style="background-color: #9999;" class="card mb-3" style="max-width: 100%;">
<div class="row no-gutters">
<div class="col-md-4">
<a href="{% url 'post_detail' post.slug %}"><img style="height: 200px; width: 330px;" src="{{ post.mainimage.url }}" class="card-img" alt="..."></a>
</div>
<div class="col-md-6" id="ph">
<div class="card-body">
<h5 class="card-title">{{ post.title }} , {{ post.xnumber }}</h5>
<p class="card-text">{{ post.version }}</p>
<p>{{ post.category }}</p>
<p class="card-text"><small class="text-muted">{{ post.date_added }}</small></p>
</div>
</div>
</div>
</div>
<hr >
{% endif %}
{% empty %}
<div class="notification">
<p>No posts yet!</p>
</div>
{% endfor %}
the code
No I have not, please don't randomly ping people for help
app
from flask import Flask, render_template, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from blueprints.auth import auth
from models.User import User
app = Flask(__name__)
db = SQLAlchemy(app)
models.User
from app import db
from flask_login import UserMixin
from utils.GUID import GUID
import uuid
class User(db.Model, UserMixin):
__tablename__ = 'Users'
user_id = db.Column(GUID, default=uuid.uuid4, primary_key=True)
first_name = db.Column(db.String(length=255), nullable=False)
last_name = db.Column(db.String(length=255), nullable=False)
email = db.Column(db.String(length=255), nullable=False, unique=True)
username = db.Column(db.String(length=255), nullable=False, unique=True)
password = db.Column(db.String(length=255), nullable=False)
balance = db.Column(db.Integer(), default=0)
```
How do i prevent circular imports ? app imports User, User imports app
I put this in a Jupyter notebook to hide warnings
from IPython.display import HTML
HTML('''<script>
function code_toggle_err() { $('div.output_stderr').hide(); }
$( document ).ready(code_toggle_err);
</script>''')
but it only hides warnings that already show. I want to pre-emptively prevent warnings from displaying.
https://stackoverflow.com/questions/69853076/how-to-create-a-pagination-with-if-and-for-loop-django
help
hi I'm new to Django can anyone please help me. I am getting this error >>Not Found
The requested resource was not found on this server. <<
There's a problem with your routing
allright, i somehow imported it there, but now i have some problems in utils.js
django-rest-framework ```py
class CreateChatGroupSerializer(ModelSerializer):
creator = UserSerializer()
class Meta:
model = ChatGroup
fields = ("creator", "name", "description", "icon")
``` In this serializer how can I automatically set the creator field to request.user?, Thanks
Hax
sted and I will contact you shortly. Thanks!
sted and I will contact you shortly. Thanks!
hello
@task.post("/api/v1/task")
async def create_task(ip: Ip):
ip_details = get_ip_details.delay(ip.address)
return {"task_id":ip_details.get()}
ip.details.get() should be a big json object but i only got one element from this object, any solution?
Make APIs with cgi-programming easily
https://python.plainenglish.io/cgi-programming-with-python-310bfa23d9af
GitHub Profile link-
https://github.com/YashIndane
Do people still use cgi? wsgi/asgi is what I use nowadays
Hello everyone. I want to start building websites, and i want to start with something simple. I know this is a python channel, but could you give me some ideas on what i could start with? What websites do people usually start with for fun?
Brython
Can someone explain how django or flask work in the background with apache. Say a person requests site.com/index.html apache wants to grab and serve the file. But flask wants to generate stuff and make the template to make the page and send the template. How does flask grab the request and process it
how would i build a basic chat send and receive system with python
đŚ
: (
: (
:=
bruhhh
@native tide omg i figured it out now i just had to activate the ufw 4444 but now i just have to make it run through my domain xD
So right now it runs over the ip of the server but wants to change it to the domain
how do I get the data sent with ajax in the backend?
Example ajax
$.ajax({
data : {
watchlist_name : $("#watchlist-selector").val()
},
type : "POST",
url: "/process_watchlist_request"
})
How do I get the watchlist_name variable in python?
ah nevermind, found out how to use request.get_data() correctly, didn't use it the right way at first
Glad to hear it. I didn't even think of the port.
Can someone help me with a small issue ?
Just dump the error and describe what you're trying to do
Soo
This is my python code
This is my template
I wanna change values of intrebaree, optiune1, optiune2, optiune3, everytime I click Intrebare noua button
Any advice ? đŚ
Id have to be off phone and on laptop to check that out. I will look later.
Anyways better to ask for help than to ask if you can ask for help.
anyone can help me with JS dm me pllllss
Offering paid work is against the #rules here
You need, at minimum, a DNS CNAME entry to point your domain to the correct IP. Where is your page hosted? Do you have a certificate yet? If not, look into LetsEncrypt
Thanks for notifying me đ
Hello how can I completely remove the database that comes with django by default? I'm already using another DB configured in the default database section inside settings.py.
you mean the sqlite db?
Yes
just delete it
if you are not referencing it anywhere in your code, you can just delete the file from your project.
I did some migrations with the sqlite db before swapping to the current database. By deleting the sqlite file it will delete those migrations as well
nope
migrations are stored under /migrations inside each application, Incase if its different for each database you can always delete the whole folder and re run those commands and django will create new migrations for your current database.
If you are talking about the data stored in your sqlite, you will have to do a data migration from your sqlite to the new database with some tools or manually.
{% for post in postss %}
{% if 'title' == None %}
<div class="alert2 alert-success" role="alert">
No results ): {{title}}
</div>
<div class="notification">
<p></p>
</div>
{% else %}
<div style="background-color: #9999;" class="card mb-3" style="max-width: 100%;">
<div class="row no-gutters">
<div class="col-md-4">
<a href="{% url 'post_detail' post.slug %}"><img style="height: 200px; width: 330px;" src="{{ post.mainimage.url }}" class="card-img" alt="..."></a>
</div>
<div class="col-md-6" id="ph">
<div class="card-body">
<h5 class="card-title">{{ post.title }} , {{ post.xnumber }}</h5>
<p class="card-text">{{ post.version }}</p>
<p>{{ post.category }}</p>
<p class="card-text"><small class="text-muted">{{ post.date_added }}</small></p>
</div>
</div>
</div>
</div>
<hr >
{% endif %}
{% empty %}
<div class="alert2 alert-success" role="alert">
No results ): {{title}}
</div>
<div class="notification">
<p></p>
</div>
{% endfor %}
why its not work the if
its loop on the posts
and i want if the title = none
do not do any thing
but if has value
do the for loop
@potent glade
Alright I think that I don't have valuable data stored inside the sqlite db aside from the first migration just to ensure that everything worked fine. By deleting sqlite file and re running migrations as you said should work. Thank you so much
sorry im new to flask too. maybe make your own room :3
i guess u are using for loops wrong
no django not flask
how can I print the <tr> with soup the problem is that the <tr> has no class ...
I want to filter it so that only the <tr> which have the text in class = "Klasse ungerade" are output ...
Haven't used BS4 in a while but if you can find the td by class, then you can simply select the tr as .parent I believe
can you guys point me to some article about xlsx files processing in django
and how can i find this text Klasse1234 ?
soup.find_all('td' text="Klasse1234")
like this it dosent works...
Hey, I'm looking to build a page for sorting algorithms visualizers. I know a little bit of flask, was just looking for tips in what I should look into in regard to how I should make the graphics and such
Hey how to learn django
There's plenty of books, videos, courses, etc...
Also django docs
self signed cert
Hey everyone, I'm making a site on django currently, and considering I just had to execute one function once the server/site has been started, what would be the best library/module/repository to use, to achieve that?
because yes, I don't really have a particular reason, apart from for optimisation
if we talk local environment wise, then as soon as you have run manage.py runserver
Let's say you have a piece of initialization code, that you want to run only once, when Django is starting up. What's the proper way to handle this? Where should you put this code?
string not text as in soup.find_all("td" , string="Klasse1234") according to https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-string-argument
Do you guys remove copyrights from templates and customize them?
for html, if i submit a form, which method could i use for others to see the new form i submitted without refreshing the page?
because if i submit, it basically refreshes for me but not for others
can someone help me i have same problem here #help-popcorn
Is this an appropriate place to ask a general JavaScript question?
Though I do need to know so I can implement some Python
Who not, sure
I actually already got some insight â but I have another
What's the difference between XML and XHTML?
XML is data format similar to JSON and YML, low amount of rules how to represent data(dictionary, arrays and etc) and transmit for any case, for example in REST API
XHTML is one of outdated ways to code web page. Structural language that goes in pair with CSS and JS, not recommended for usage. HTML5 is the standard
any tips?
Guys i got this excel file that i process with openpyxl and there is a date column where some of the dates are returned as datetime.datetime(2012-1-1-0-0) and some are just returned as 02/02/2002. I use the data to create objects via django models and one of the attributes is models.DateFIeld() which is giving me errors because of the different data it receives
I'm afraid that you'd need js for any complex animations đ¤
What's the right way to organize django apps inside subfolders.
my project structure looks like this
core
|- settings.py
|- urls.py
|- apps
|- app1
|- app2
but whenever i create a model inside my app i get
Model class core.apps.app1.models.Paste doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
Even thought its added to INSTALLED_APPS
I tired adding app_label on the model and i get this error:
Conflicting 'paste' models in application 'app1': <class 'app1.models.Paste'> and <class 'core.apps.app1.models.Paste'>.
@ashen trench Do you have app config inside apps.py in your application?
yeah
Could you share a screenshot of your structure?
and what about any of the packages in apps?
actually 1 app works perfectly,
the web app for instance does its job, But when i add a model to my ide app it doesn't work
Did you actually add all of these apps into installed apps?
initially django wasn't detecting my apps since i organized them into sub folders, and i had to add
sys.path.append(os.path.join(BASE_DIR, "core/apps")) to get it working
Don't do that đ¤
You can just specify them as core.apps.yourapp in INSTALLED_APPS
yeah but it didn't work i tired.
Can i clone your project?
yes
i'll give you the link, Let me push my current changes
@serene prawn https://github.com/ryuga/Backend
just visiting the localhost:8000 would give you the error
let me see if i pushed the correct version, Did you migrate?
I did
okay give me a min
Yep, there's still an issue
You'd have to name your apps core.apps.ide i think đ
yeah its the current version, when you visit the localhost you get Model class core.apps.ide.models.Paste doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
You could avoid some nesting if you move your apps to other directory
wdym?
inside the installed_apps?
@ashen trench https://github.com/ryuga/Backend/pull/9
oh i see
Maybe move apps into core packages to avoid some nesting đ¤
But it depends
or create another package for your code applications, i'm not sure
It's up to you anyway
but for the python discord sites, they never had to add the app name like that
i used that repository as a references, initially i had all apps spread out like the default django project structure.
Can you give me link to that repo?
pythondiscord.com - A Django and Bulma web application. - site/pydis_site/apps at main ¡ python-discord/site
i see
Not sure how they did that though đ
thanks a lot for the help, i've been on this bug for a while.
yeah its strange, but works for them.
Thats fine, I just started with it. (literally an hour ago got to js in my course) I'm asking about maybe libraries and stuff like that I should look into
I didn't really work with animations in javascript đ
@plush bloom What error?
cant find parent module
Could you share your project structure?
Why are you trying to run it directly?
Try starting your django dev server đ¤¨
ye it show huge error
python manage.py runserver
ye it show error
ik that syntax
ye
but my server not running either
so i tot
if some problem i can find in seperate files
Just share whatever error you're getting when trying to run the server
What about the bottom part?
thats it
Ehm, there should be an error message at the bottom
Yep
đ¤¨
Not sure why views is undefined error was there then
yw
that wat made me go through mental breakdown
i knew that was correct
i had to join like 10 different programming servers and ask this
u r a real G man
finding out even dumb stuff i do
hey
how exactly does routing work when you have django and react? do you just have to route everything twice?
i hae no clue about either of them
thanks
If it's a SPA you usually build a backend API and interact with it at your frontend
Did you import os at the top of the file?
Seems like nobody in the help channels can help me so i will ask here. I upload xlsx files/excel files and import them in my database using django model. I have a cell in the file that represents date and whenever i try to assign it to my models.DateField i get an error
sometimes it returns datetime.datetime objects
What is the best way to store the json web token in the client side?
The frontend will be react.js
(django) how do i rewrite this using rest_framework.generics.CreateAPIView?
class BookingCreateView(APIView):
def post(self, request, user_pk, advisor_pk, format=None):
user = get_object_or_404(User, pk=user_pk)
advisor = get_object_or_404(Advisor, pk=advisor_pk)
Booking.objects.create(user=user, advisor=advisor, time=request.data["time"])
return Response()
hi ppl how can i use the lib flask_socketio and get the clients and put them in a list.
@eternal blade i just recently made a chat app
oh, nice
you are making it with rest framework good
@cerulean badge you would do something like this
class BookingSerializer(serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField()
advisor = serializers.PrimaryKeyRelatedField()
class Meta:
model = Booking
fields = ['user', 'advisor', 'time']
class BookingCreateView(CreateAPIView):
serializer_class = BookingSerializer
and then you would supply user and advisor like you do with time in the body of your post
how do i use the user and advisor pk provided in the url instead?
Hey guys, django image data (models.imagefield) from model is not appearing post deployment. What do I do? My other static files are working because I have them on my S3 bucket. Should I do the same for these? If so, how?
Either have to serve them as static files on your web server or point to their path on S3 I think.
Static file on web server wonât work as my server is on an EC2 instance. But the image is of type models.imagefield. How do I populate it?
Not really sure, I rarely work with images. Maybe a OnetoOne on another model with the s3 path
Is there an API for Facebook where I can search for videos in archive?
There is a video I watched 'more than 1.5 year ago' and I only remember the song which was played.
Graph API has Video but won't do you much good if you don't know what page the video was posted on
Does anyone know how to send a whole folder in flask?
send_from_directory only supports files as it seems
or is it even possible to do so?
đ¤ oh ke
what's wrong with this line of code ? ```js
app.use(bodyParser.json({ limit: "20mb", extended: true }));``` It says bodyParser is depricated.
not an error tho
routing in django provides http endpoints for your server, in react/vue the router isn't really a router in the same sense
Would basically need a way to direct models.imagefield to s3 bucket
If anyone has any expertise would love to know!
is this chat for web automation as well or just development?

How can I allow another server to call my (Python) API by authenticating with certificates. No username or password just certificates?
Something about a .pem file? Would love any pointers
Would anyone happen to know what could cause this weird oval shape?
<a href="https://www.github.com/Void-ux">
<button class="github">
<img src="https://github-readme-stats.vercel.app/api/top-langs/?username=Void-ux&layout=compact&theme=vue"
alt="Top Languages Failed to Load"
width="400"
height="200">
</button>
</a>```
```css
.github {
border: 1px solid white;
border-width: 2px;
border-radius: 40px;
background: rgba(0,0,0,0);
}```
obviously that's border-radius: 40px;
hey i just want a simple register an login system i tried many times but i failed can u give me a prototype code ?
anyway...
you need something like that
.github {
// shared css
}
button.github {
border: 1px solid white;
border-width: 2px;
border-radius: 40px;
background: rgba(0,0,0,0);
}
.github img {
//css specific to img
}
to specify that those styles should be applied only really to button object
u have a problem from img inherting styles from button object, with specifying button.github, it should be no longer a problem
well, technically could be still working...
probably > element should be applied, or just overwriting what you don't want in child element will work too
rendered the code directly in google chrome
<!DOCTYPE html>
<head>
<style>
.github {
border: 1px solid white;
border-width: 2px;
border-radius: 40px;
background: rgba(0,0,0,0);
}
</style>
</head>
<body style="background-color:black;">
<a href="https://www.github.com/Void-ux">
<button class="github">
<img src="https://github-readme-stats.vercel.app/api/top-langs/?username=Void-ux&layout=compact&theme=vue"
alt="Top Languages Failed to Load"
width="400"
height="200">
</button>
</a>
</body>
</html>
highly likely you have some other code somewhere that interferes into it, somewhere style is inherited from higher parent object perhaps
Ahh, you're right css img { border-radius: 50%; }
That was it
đ
Hello i need some help. I managed to make a site which opens a camera takes a photo and gets some data from it. but i realised it only works locally on the macine i run the code on. if i put it on a server cv2.VideoCapture(0) won t do anything like there would be no camera for the end user. how can i make the website so that it access the user s camera? i m pretty lost. As refference i m using tesseract opencv and flask
I'm trying to test my api. I'm just using request module to test the status code and that's it. There is just one endpoint that uses external api under the hood, so i think i need to mock it as we can't rely on external api response in testing. What whould be the best way to mock this third-party api while using request library to test my own api?
@foggy bramble I think you could use https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch to mock requests coming from that api
I know this, i used mock from different cases. However i don't know how to apply it here... Lets say in my end point http:localhost:5000/ip_details
Im getting information about ip address by using external api, and while testing i send request to my end own api endpoint directly so i don't have access to my function that handles my endpoint and sends requests to external api
What framework are you using? @foggy bramble
Fastapi
For some reasons i didn't use testclient
I preferred request for some reason, so I'm wonder if there is a way for request in this scenario
You would have access to all your internals this way and would be able to patch functions you want
They have similar if not the same interface
Honestly i have had hard time with imports while using pytest and testclient
imports?
Yes, lets say i have dedicated directory for tests named tests, and all my source code is in src directory. When i try to import app in the test, for testclient, i got import error as they are in different directories
Also in src directory there is another folder that my main file handles routers, so it's imports give me errors as well
Take a look, i set up application and TestClient here
And then i can use it in tests
so umm any ideea on my problem on how how i can access a user s camera in my flask app??
@stable sorrel You can request user permission to access camera in javascript
and hopw do i deal with the photo?
before i used opencv to save the photo in a folder and process it
You can send it to your backend
and it s sent as a jpeg or it needs to be converted or something?
it s the first time i m working with something like this so i don t really know
I don't know either, đ
I think you could encode that screenshot as base64 and send it to your api
hmm ok i ll try it
i saw that there s something like webcam.attach('camera') so i need to get the data from that thing
if i have some textboxes and i want the data from them to say form an object in the backend or be used or something do i use a post in which i return request.form['textbox_name']?
Hello, let's say that I made some migrations, create a super user and insert some data into db tables. Now if I delete those migrations, the super user and data inserted into the db will be erased as well?
No, the present state of your database will not immediately change just because you delete the migration files, but why delete them?
Because I want to remove the default database that comes with django. I did some migrations to that database but I'm not longer using it.
I see. If you don't need your old data, deleting the old migrations and starting fresh with the new db is probably easiest
Yeah that's what I will do, thank you
Anyone here who has deployed django written dynamic website on google cloud using docker?
Facing some issues.....if anybody could help me would be really appreciated
Don't ask to ask, explain your issue here
Or grab a help channel if it's complicated #âď˝how-to-get-help
hi
I'm having problems about flask
idk where is he referring to, the first one is the "user" idk if he's referring to the function or he just created it as a str
and also the user without ""
user is declared right there in the previous line. You don't show us where 'session' is declared, but it looks like it's a dictionary where ["user"] is a key and its value is being set to the user object
yea thanks I figured it out the ["user"] was actually referring to the function below
I just don't understand how the code works exactly, do I really need to understand the whole code before I go to the next tutorial?
Any ideas what the implications of unlocking python's GIL for python frameworks might look like?
Would it be bringing us to a more true state of async?
hello i need like my jinja templating is not working .
code:-```py
from flask import Flask, render_template, request, redirect, url_for
app = Flask(name)
@app.route('/')
def index():
return render_template('index.html')
if name == 'main':
app.run(debug=True)
html flies-1 ```<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{% block body %}{% endblock %}
</body>
</html>```
file-2```{% extends "index.html" %}
{% block body %}
{% for x in range(5) %}
<p>
Bruh
</p>
{% endfor %}
{% endblock %}```
how is it not working, what error
Blank html document
Does index.html exist? Your route doesn't refer to file-1 or file-2
this is index.html
You sure it's pointing to the right place for your template/page?
yez
What if you change it to return render_template('index2.html')
See if there's an error
everything is fine ....
So then it's probably not pointing correctly to the file.
Probably makes more sense that way but you don't have to
You just need jinja to properly point to your file. I don't know how jinja does it.
Or the path to your file simply isn't right.
But in Django you get an error if it's not pointing to an existing template.
I made a cool thing!
Looks nice!
'index.html' is your base template and it currently doesn't have anything in it. The content is in the other html page that inherits from 'index.html'
Hello guys i need your help in django. what is name of the checkbox fields (like in html) in django or how to make fields like this in django admin
I have this form in django admin
and i just want to add checkboxes there so i can choose multiple answers
If you have very specific choices for a certain field you should first set those up with choices= in your charfield in your model
by default django doesn't use checkboxes for this but you may be able to override that fairly easily...
https://stackoverflow.com/questions/147752/in-django-is-there-a-way-to-display-choices-as-checkboxes
this is helpful
is there another type of fields where i can choose many answers ? i mean is there alternative for the checkboxes ?
actually what you may need to do is set up a separate model which contains the options and have a foreign key pointing to your main model
yes exactly
i have to make separate model so i can add new choices to the model
lol, actually it should be a many-to-many probably. Put a many-to-many field on your main model pointing to your option model and it should show up in the admin form as a multiple choice field
omgg thank uu!
haha sorry, I was having some issues understanding there
np
if you really want checkboxes, you can override the admin form like they do in the link above
no bro u are kind and great guy! thanks for help
I have one more question
I need to make another model for another field
i need to make selectable field that has multiple options but with ability to choose only one
then you should create a foreign key in your main model out to the option model
and what field should i use ?
Using Flask? You asked some days ago or am I thinking of someone else?
i did ask a few days ago but i was on vaction and forgot to see what they said
Haha, I think is sent you a SO link but I don't see it now
I'm not sure what you mean
looking back it wasn't answered
sorry i'm asking some dumb questions i'm kinda new to django... i will try to make that things you told me.
See if this helps https://stackoverflow.com/questions/51057966/flask-toggle-button-with-dynamic-label
i see
No worries! I just wasn't sure what you were asking. The field type is models.ForeignKey and you tell it that you want this to point to the options model, whatever that is py my_option = models.ForeignKey(MyOptionModel, on_delete=models.SET_NULL, null=True, default=None)
I want to create a website with django for backend, vue js for front end. How should I start with this? I know there r tons of vids for it on youtube, but Im looking for resources that would really help me in the long run. Not just copying and editing some code from some tutorials.
What kind of site?
It all depends what you need as you go.
And honestly, you start with copy-paste, learning little bits of how it works at the beginning, and the more you do, the more you learn in depth of what really makes everything work. So there's nothing wrong with copy-paste at the beginning.
Just read more about certain topics as you hit them.
Makes sense, thanks!
Im planning to just create a simple personal portfolio website
Ive already created one(school project) but we're forced to use an obsolete c# .net framework for it. Planning to use something pretty new now
I was just actually afraid Itâd turn out the same way it did when I watched videos about OOP. In the end, I was still ignorant bout lots of stuff like decorators, async, etc
My fault anyway for not reading into it that much
Yea, so that's on you to gain depth on topics. I have been doing web dev for like 4-5 years, and I'm just barely getting into the science behind data structures and algos (I don't have a CS background). I should have done it sooner, but having the practical application knowledge gave me a better sense of how it applies to the things I do in reality.
do you guys have any tutorials about how to upload and download pdf files using django
I'm making an assignment organizer web app and I tried to use cloudinary but it only handles images when using the free version so I think I have to handle it manually
Free tier AWS includes 5gb is S3 storage if that's all you need. Dreamhost does 250gb for like $1/month
yeah I definitely don't need anything more than 5gb, this should work
And here's a tutorial on S3 with Django https://testdriven.io/blog/storing-django-static-and-media-files-on-amazon-s3/