#web-development

2 messages ¡ Page 199 of 1

inland oak
#

which can be masked by Proxy and VPN services

ruby palm
#

Ok, once they have that public IP, what do they do with ISPs?

inland oak
#

they find which ISP is regstered for this IP address usage

#

and apperently in registrational data even mentioned towns for particular IPs

ruby palm
#

Do they use a number from my public IP to do a hash?

inland oak
#

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"
ruby palm
#

This information is really useful, thank you so much!

inland oak
inland oak
#

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

ruby palm
#

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?

inland oak
#

why are using documentation for older flask versions?

#

is it by intention?

ruby palm
#

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

inland oak
#

the most common practice to get the values from environment variables

ruby palm
#

Although, you then would have to hardcode the IP into the environment variable, it ends up being the same

inland oak
#

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

ruby palm
#

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?

inland oak
#

database best practice hosting in priority from best to the worst:

  1. using Managed Database from cloud provider (DigitalOcean gives them) (the best, low effort, maximum result choice)
  2. Having separate server with database only, but if you wish having it HA, it will take much more efforts than Managed DB
  3. Having database installed at the same server where application is
  4. 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 )
ruby palm
#

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?

inland oak
#

database connections work in TCP sockets i think

#

not in HTTP

ruby palm
#

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?

inland oak
#

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

ruby palm
#

Ohhhh!

#

Ok, so the database URI can be a remote URI, that's the only thing that changes

inland oak
#

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

ruby palm
#

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?

inland oak
#

read about SQLAlchemy library

ruby palm
#

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?

inland oak
#

yes, we just change address of the database with pointing to different machine

inland oak
#

not understanding the question enough

ruby palm
#

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

inland oak
#

yes, exactly

ruby palm
#

Sigh! Now I understand, it's very simple

#

Why is having it in a separated server better practice than having it locally?

inland oak
#

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.

ruby palm
#

it overloaded app or database

#

I don't understand that statement

inland oak
#

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

ruby palm
#

go super slowly because they affect each other
I don't undestand that part

ruby palm
inland oak
#

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

ruby palm
inland oak
#

sharing same RAM (and that's limited too ;b)

ruby palm
#

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?

inland oak
#

the most important is indepency for updates as I said

ruby palm
#

Ohh, ok ok

ruby palm
inland oak
#

...but!

#

there is downside to having separate servers

ruby palm
#

In the specs

ruby palm
inland oak
#

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...

ruby palm
inland oak
#

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

ruby palm
#

Ohhhhhhhhhhhhhhhhh

#

That's what the very big apps like YouTube do

inland oak
#

surely.

#

also...

ruby palm
#

I imagine they have a lot of servers, but only one for DB, and these servers access the same thing

inland oak
#

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

ruby palm
#

What is HA database?

inland oak
#

your can make reading and writing operations to it

ruby palm
inland oak
#

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

ruby palm
#

Ok, that blows my mind

inland oak
#

if main database goes down, you could make second database as main one

inland oak
#

takes complexity away for this, for a price

ruby palm
#

That's very good

ruby palm
#

So, let's say you buy the managed database

#

How do you integrate it into your app? They just provide a URI?

inland oak
#

yeah

ruby palm
#

But a DB URI corresponds to just ONE DB...

#

What exactly is happening in there?

inland oak
#

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)

ruby palm
#

"load balancer"

#

New term for me

ruby palm
#

It's impressive. I learned so many things from this conversation

#

You are really kind, I really appreciate it

inland oak
#

blue things are your servers with flask apps

#

green thing is load balancer

ruby palm
#

Ohhhhhhhh

inland oak
#

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!

ruby palm
#

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?

inland oak
#

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

inland oak
#

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

ruby palm
#

Alright, how is the load balancer integrated behind the scenes of that URI DigitalOcean gives you?

ruby palm
ruby palm
inland oak
#

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

digital bay
ruby palm
#

Ok, I see!

inland oak
#

load balancers will be useful for your other application parts

#

flask apps and etc

ruby palm
#

Alright, so a HA database is a managed database

#

Right?

inland oak
#

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

ruby palm
#

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

inland oak
#

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

ruby palm
#

Alright, and a load balancer proxies requests. Where is it in a HA database?

inland oak
#

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

ruby palm
#

Then, why are some HA dbs that do NOT use a load balancer?

inland oak
#

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

ruby palm
#

Do you have an example of technologies used to set a HA database yourself?

inland oak
ruby palm
#

Awesome :)

inland oak
#

the guide mentions load balancer as HAProxy

ruby palm
#

I have enough to google for a whole lot of time

inland oak
#

uh. lets end it here then)

#

I am answering your questions one hour and half already

ruby palm
#

Yes, I have to get back to what I was doing hahaha

inland oak
#

I should really get back to my studies

ruby palm
#

What!? Did so much time pass

#

I can't believe it

#

I thought it was 30 minutes at much

inland oak
ruby palm
#

Thank you VERY much for this help

stable sorrel
#

if anyone worked before with flask web apps which have a webcam integrated could you give me some advice?

inland oak
dreamy willow
#

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```
olive hedge
#

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 ^^

dusk portal
#

ohhh

surreal portal
#

Does anybody know how to create any type of contact form that directly sends the mail to your inbox?

rigid loom
wraith dagger
#

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

dusk portal
#

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.

#

;-;

olive hedge
#

thanks

stark tartan
ruby palm
#

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

ruby palm
#

Do you spot something wrong?

#

Thank you very much beforehand!

sonic island
#

any dev ready to make team to compete in hackathons?
my skills: python, django, sql

dense slate
olive hedge
#

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

night sequoia
frank shoal
frank shoal
#

!d pathlib.Path

lavish prismBOT
#

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").
olive hedge
frank shoal
#

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

autumn birch
#

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?

inland oak
#

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

autumn birch
#

I dont mind about security problem

inland oak
autumn birch
#

Oh wait you need to put sqlite db in static folder?

autumn birch
#

solved conn = sqlite3.connect('//var//www//html//hs.db')

native tide
#

i get this err

#

help

#

how to make the for loop start from the post 15

native tide
#

anyone

dense slate
#

forloop.counter15 <= 30

native tide
solar obsidian
#

how can i add a switch in the html that runs code in flask

dense slate
crude badge
#

I’m creating an API that requires authorization.
Should I use JWT or an API key?

calm plume
#

JWTs are often used as API keys, they're not mutually exclusive

crude badge
#

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

calm plume
#

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

crude badge
#

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

calm plume
#

And you'd validate that how?

crude badge
#

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

calm plume
#

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

crude badge
#

No, you would store whatever you want but usually you’d store just the user name and expiration date of the jwt

wooden ruin
#

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

crude badge
#

Wait API keys as a url sounds like a bad idea? It’s public and not encrypted

vestal hound
#

in general API key in URL is Bad

vestal hound
#

and not just authentication

native tide
#

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.

crude badge
#

@native tide can you expand on that?

native tide
# crude badge <@456226577798135808> 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.

crude badge
#

Hmmm will have to give it some thought

#

Thanks

native tide
#

I can send some example snippets in the morning.

inland oak
# calm plume Uhh, that doesn't make any sense. How would you know what the JWT is supposed to...

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

daring turret
#

It returns None in console when called

inland oak
#

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

daring turret
#

So i enable debug mode, set a breakpoint for the "data" variable and attempt to call it

inland oak
#

yup

#

are u using vscode?

daring turret
#

I'm using Replit but there is a built in debugger

inland oak
#

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

daring turret
#

JavaScript is my first language, and it looks correct to me

inland oak
#

btw, you should be definitely having CORS problems

#

did you setup CORS?

daring turret
#

No, not yet

inland oak
#

although if python at localhost, probably it is not an issue yet

daring turret
#

Replit isn't local, it's cloud based

inland oak
#

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

daring turret
#

Replit has a built-in debugger

inland oak
#

if normal debug is not available

#

all right

daring turret
#

dir(request) right?

inland oak
#

print(dir(request)) if you wish

daring turret
inland oak
#

that does not look like a good way to debug it

#

i was thinking you would output it right there in conosle

daring turret
#

It kept returning an error saying it was a list

#

In console, it returns

#

@inland oak

inland oak
#

we surely wish to know at least the which http code error it is

daring turret
#

@inland oak

charred gulch
#

is visual code better for beginners???

inland oak
charred gulch
#

visual studio code*

daring turret
#
  • 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.
inland oak
daring turret
#
@app.route("/addprofile", methods=["POST"])
def add():
  if request.method == "POST":
    data = request
    jsonData = data
    print(jsonData)
    #return jsonData
inland oak
# daring turret * Serving Flask app 'main' (lazy loading) * Environment: development * Debug m...

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

daring turret
#
<Request 'http://replstories.ml/addprofile' [POST]>
172.18.0.1 - - [04/Nov/2021 07:35:46] "POST /addprofile HTTP/1.1" 200 -
inland oak
#

here u go

#

200 is good

#

read the answer json

daring turret
#

i still need the json

inland oak
#

200 means you received valid json answer in your javascript

#

read in your frontend the answer

daring turret
inland oak
daring turret
inland oak
#

here u go.

#

everything works

daring turret
#

except i didn't get the data i need in backend

inland oak
#

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?

daring turret
#

File "/home/runner/stories/main.py", line 84, in add
return jsonify(request.json())
TypeError: 'NoneType' object is not callable

inland oak
#
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

daring turret
#

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));

inland oak
#

or request.json, or request.get_json(force=True)

#

Those two books can be useful:

daring turret
#

{'name': 'urmom', 'id': '4949494'}
172.18.0.1 - - [04/Nov/2021 07:45:29] "POST /addprofile HTTP/1.1" 200 -

inland oak
#

u received your data back

daring turret
inland oak
#

which was python code succesful?

daring turret
#

yep

inland oak
#

u can just access your variables with syntax

#

data["name"]

#

and data["id"]

rigid parrot
#

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

inland oak
#

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

dusk portal
#

@inland oak hey bro , willing to help me? i wanna deploy static files to production lvl

rigid parrot
#

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

inland oak
#

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

rigid parrot
#

I'd guess based on functionality?

inland oak
# rigid parrot Out of curiosity how do you structure your apps?

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

rigid parrot
#

Okay thanks

#

I always overthink stuff like this and barely work on features haha it's a problem

inland oak
olive hedge
#

hi guys, i need help on Flask problem

stable sorrel
#

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

dusk sonnet
#

hi, how can i sort of prevent users from altering form submissions (Flask)?

stable sorrel
#

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?

dusk sonnet
inland oak
proven elk
#

hi

autumn birch
#

apache2 wsgi ubuntu flask can enable debug mode?

inland oak
brisk dawn
#

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?

lavish prismBOT
#

: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).

autumn birch
inland oak
#

but u will read only flask errors

#

for apache2 errors you should go to its log file

autumn birch
#

How about read Internal server error from browser

stable sorrel
#

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]) }} >

#

?

frank shoal
#

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}}"/>
stable sorrel
#

i did something before for returning a video feed where i returned Response(function(),and some mimetype)

#

is that the same thing or ?

stable sorrel
frank shoal
#

this is more specific to jinja.

#

you can put any valid python inside {{}}

stable sorrel
#

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

frank shoal
#

sure.

#

Or you could change it based on the url params

stable sorrel
#

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

frank shoal
#

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 %}

inland oak
#

@dense slate yay, at last I join the frontend too. But I chose Vue.js to start my path there ;b

frank shoal
#

vue is good

inland oak
#

I was very tempted to choose Svelte 😉

stable sorrel
inland oak
#

but decided I should better choose more... solid and stable framework

#

plus reusable for next job

frank shoal
#

hey, what's the new hastebin service that doesn't have an ugly url like that above?

inland oak
#

!paste

lavish prismBOT
#

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.

normal pebble
#

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?

inland oak
#

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 🤔

inland oak
#

Or better to go for Svelte 🤔

#

Urgh. I'll try to setup Svelte first.

simple garden
#

does someone know how to lift the placeholder

#

up

#

i tried using padding and margin none of em worked

inland oak
simple garden
#

dosent input automatically get in the middle? @inland oak

inland oak
simple garden
#

its not debuging

inland oak
#

Everything else by default depends on object sizes

simple garden
#

my bad then-

inland oak
#

!code

lavish prismBOT
#

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.

inland oak
#

Screenshots are bad, copy pasting is the way

#

Not having pc under the hand. Plus not complete code anyway. Went to sleep

simple garden
#

im confused

inland oak
#

To read how to ask for help in detailed way

simple garden
#

those are made for only python

inland oak
simple garden
inland oak
#

Rendered html can be still coppied

simple garden
#
            <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

inland oak
#

Much better, the willing person can truly help now.

#

Went to sleep, already in bed. From phone can't help that much

simple garden
#

okay

frank shoal
#

Oops, I messed up somewhere. ```
[Vue warn]: Invalid prop: type check failed for prop "modelValue". Expected String with value "[object Object]", got Object

potent glade
#

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

frank shoal
#

you should use values

#

!d flask.Request.values

lavish prismBOT
#

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`.
frank shoal
#

To answer your question, it will only search post params

crystal bramble
#

if you want to do different things for GET or POST

autumn birch
#

ubuntu apache2 flask
ModuleNotFoundError: No module named 'pyotp'
But pip3 list, pip list have it

edgy sable
#

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)```
native tide
edgy sable
#

And in ironman_gifs() he goes to fetch the links

native tide
#

can you post ironman_gifs()

edgy sable
#

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

native tide
#

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

coral storm
#

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

edgy sable
native tide
#

hi i have a prp when i edit anything in my code its have a err

#

and i do it

#

right

native tide
edgy sable
# native tide just checking

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

native tide
native tide
edgy sable
native tide
ruby palm
#

Question, how do socket connections get closed after the client closes the browser?

edgy sable
native tide
#

u seee

#

@native tide

ruby palm
native tide
#

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

native tide
#

test app

edgy sable
#

I send you screen from my data

native tide
#

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.

edgy sable
#

Is everything there ?

native tide
# edgy sable 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

edgy sable
native tide
#

mmm

#

so

#

restart pc

#

??

#

my pc

#

not ur

native tide
#

okay

native tide
#

that was my initial thought, but maybe not

edgy sable
#

It will be difficult to find out what the problem is :(

native tide
edgy sable
#

I use Ubuntu 20.04 LTS and use apache2 with Python3.9

native tide
edgy sable
#

I simply started the api with apache2 and started the app.py with python3.9 app.py

#

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)```
native tide
#

it seems like you're using the flask development server in "production" which you don't want to do

edgy sable
#

Well I set the api.conf to available

edgy sable
native tide
native tide
#

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/;
    }
}
edgy sable
#

I have probably set it completely wrong

edgy sable
#

to activate your page

native tide
#

I run my flask app on :8000 with gunicorn

#

well mine is django, but same idea

edgy sable
native tide
edgy sable
#

:(

#

There is no apache help channel here or ?

native tide
ruby palm
#

Hm? I don't understand what you mean. I appreciate the help! Can you elaborate further?

snow sierra
#

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?

fickle garnet
snow sierra
#

no idea :/

#

but this form dos not know what kind of choice made by user

olive acorn
#

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)

GitHub

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....

GitHub

🚀 TypeScript Express Starter. Contribute to ljlm0402/typescript-express-starter development by creating an account on GitHub.

crude badge
#

How can I allow another server to call my (Python) API by authenticating with certificates. No username or password just certificates?

inland oak
calm plume
#
  1. 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 need react and react-dom as dependencies, and for the capabilities they provide.
inland oak
calm plume
#

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.

dusk portal
#

@calm plume hey sir i need help

#

have u used CPanel?

signal iris
#

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.

echo fjord
#

@signal iris You will need the Node Server to deploy the React App built.

signal iris
echo fjord
#

Do you want serve the static files without Express?

native tide
#

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.

echo fjord
native tide
echo fjord
native tide
#

I have tried a few things, I intentionally want it to be vulnerable. Not sure why this isn't working though tbh

echo fjord
native tide
#
<?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.

native tide
#
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

native tide
#

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

calm plume
noble smelt
#

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

native tide
#

that work

#

but in the other page not work why

#

its on my Pagination

primal grove
#

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.

native tide
foggy bramble
#

func.delay().get()

Just waits when i try to run celery task

#

What can I do

lethal void
#

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. <<

frank shoal
#

There's a problem with your routing

native tide
#

allright, i somehow imported it there, but now i have some problems in utils.js

eternal blade
#

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

native tide
#

Hax
sted and I will contact you shortly. Thanks!
sted and I will contact you shortly. Thanks!

foggy bramble
#

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?

rotund bronze
frank shoal
#

Do people still use cgi? wsgi/asgi is what I use nowadays

white delta
#

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?

hushed ermine
viscid spade
fair dirge
#

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

left summit
#

how would i build a basic chat send and receive system with python

#

😦

#

: (

#

: (

#

:=

#

bruhhh

edgy sable
#

I need help

#

Apache2 (Flask)

edgy sable
#

@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

boreal knot
#

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

native tide
native tide
#

Can someone help me with a small issue ?

pulsar kraken
#

Just dump the error and describe what you're trying to do

native tide
#

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

native tide
pulsar kraken
#

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.

native tide
#

Oh, thanks anyway pepelove

native tide
#

anyone can help me with JS dm me pllllss

golden bone
golden bone
shadow vine
#

I need some serious help with django templating stuff

native tide
native tide
#

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.

native tide
ashen trench
#

just delete it

#

if you are not referencing it anywhere in your code, you can just delete the file from your project.

native tide
#

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

ashen trench
#

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.

native tide
#
  
    {% 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

potent glade
#

give more informations

#

what is not working

#

what is the error

native tide
#

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

native tide
potent glade
#

i guess u are using for loops wrong

native tide
potent glade
light goblet
#

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 ...

golden bone
halcyon lion
#

can you guys point me to some article about xlsx files processing in django

light goblet
#
soup.find_all('td' text="Klasse1234")
#

like this it dosent works...

mild wing
#

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

plush bloom
#

Hey how to learn django

serene prawn
#

Also django docs

warm igloo
#

self signed cert

glacial yoke
#

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?

warm igloo
#

started as in first visitor? server turns on? container?

#

also: why?

glacial yoke
glacial yoke
warm igloo
golden bone
white delta
#

Do you guys remove copyrights from templates and customize them?

terse vapor
#

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

formal mason
patent glade
#

Is this an appropriate place to ask a general JavaScript question?

#

Though I do need to know so I can implement some Python

patent glade
#

What's the difference between XML and XHTML?

inland oak
# patent glade 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

halcyon lion
#

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

serene prawn
ashen trench
#

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'>.

serene prawn
#

@ashen trench Do you have app config inside apps.py in your application?

ashen trench
#

yeah

serene prawn
#

Could you share a screenshot of your structure?

ashen trench
serene prawn
#

and what about any of the packages in apps?

ashen trench
#

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

serene prawn
#

Did you actually add all of these apps into installed apps?

ashen trench
#

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

serene prawn
#

Don't do that 🤔

#

You can just specify them as core.apps.yourapp in INSTALLED_APPS

ashen trench
#

yeah but it didn't work i tired.

serene prawn
#

Can i clone your project?

ashen trench
#

yes

#

i'll give you the link, Let me push my current changes

serene prawn
#

👍

#

@ashen trench How can i replicate the issue?

ashen trench
#

just visiting the localhost:8000 would give you the error

#

let me see if i pushed the correct version, Did you migrate?

serene prawn
#

I did

ashen trench
#

okay give me a min

serene prawn
#

Yep, there's still an issue

#

You'd have to name your apps core.apps.ide i think 🙃

ashen trench
#

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.

serene prawn
#

You could avoid some nesting if you move your apps to other directory

ashen trench
#

inside the installed_apps?

serene prawn
ashen trench
#

oh i see

serene prawn
#

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

ashen trench
#

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.

serene prawn
#

Can you give me link to that repo?

ashen trench
ashen trench
#

i see

serene prawn
#

Not sure how they did that though 😅

ashen trench
ashen trench
mild wing
serene prawn
#

I didn't really work with animations in javascript 😅

plush bloom
#

hey

#

i am getting error for

#

from . import views

serene prawn
#

@plush bloom What error?

plush bloom
#

cant find parent module

serene prawn
#

Could you share your project structure?

plush bloom
#

is this ok?

serene prawn
#

Why are you trying to run it directly?

plush bloom
#

just running the debug thing

#

and getting this

serene prawn
#

Try starting your django dev server 🤨

plush bloom
#

ye it show huge error

serene prawn
#

python manage.py runserver

plush bloom
#

ye it show error

plush bloom
serene prawn
#

urls.py is not meant to be run directly

plush bloom
#

ye

#

but my server not running either

#

so i tot

#

if some problem i can find in seperate files

serene prawn
#

Just share whatever error you're getting when trying to run the server

plush bloom
#

ye 1 sec

serene prawn
#

What about the bottom part?

plush bloom
#

thats it

serene prawn
#

Ehm, there should be an error message at the bottom

plush bloom
#

yeye

#

laast line

#

i tot that was in image i sent first

#

sorry

serene prawn
#

(again)

plush bloom
#

1

#

sec

#

only urls code?

serene prawn
#

Yep

plush bloom
serene prawn
#

Hah, weird, it should work

#

It should be urlpatterns btw

#

not urlspatterns

plush bloom
#

it worked!

#

that was the problem

serene prawn
#

🤨

plush bloom
#

i got my wassup homie

serene prawn
#

Not sure why views is undefined error was there then

plush bloom
#

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

plush bloom
#

hey

dire urchin
#

how exactly does routing work when you have django and react? do you just have to route everything twice?

plush bloom
plush bloom
dire urchin
#

thanks

serene prawn
plush bloom
#

doctor

#

@serene prawn

#

broter

plush bloom
#

os error

calm plume
plush bloom
#

ye just did

#

it works now

halcyon lion
#

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

plush bloom
#

guys

#

need welp

eternal blade
#

What is the best way to store the json web token in the client side?

eternal blade
#

The frontend will be react.js

cerulean badge
#

(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()
vital crest
#

hi ppl how can i use the lib flask_socketio and get the clients and put them in a list.

cerulean badge
#

@eternal blade i just recently made a chat app

eternal blade
#

oh, nice

cerulean badge
#

you are making it with rest framework good

indigo kettle
#

@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

cerulean badge
fossil pond
#

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?

native tide
#

Either have to serve them as static files on your web server or point to their path on S3 I think.

fossil pond
native tide
regal carbon
#

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.

golden bone
rain robin
#

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?

regal carbon
#

🤔 oh ke

regal carbon
#

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

wooden ruin
fossil pond
#

If anyone has any expertise would love to know!

fallen bison
#

is this chat for web automation as well or just development?

dusk portal
crude badge
#

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

native tide
#

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);
    }```
inland oak
native tide
#

hey i just want a simple register an login system i tried many times but i failed can u give me a prototype code ?

inland oak
#

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

native tide
#

That was it

stable sorrel
#

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

foggy bramble
#

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?

serene prawn
foggy bramble
serene prawn
#

What framework are you using? @foggy bramble

foggy bramble
#

For some reasons i didn't use testclient

serene prawn
#

Use it

#

Just do 🙂

foggy bramble
#

I preferred request for some reason, so I'm wonder if there is a way for request in this scenario

serene prawn
#

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

foggy bramble
serene prawn
#

imports?

foggy bramble
# serene prawn 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

foggy bramble
#

Also in src directory there is another folder that my main file handles routers, so it's imports give me errors as well

serene prawn
#

Take a look, i set up application and TestClient here

#

And then i can use it in tests

stable sorrel
#

so umm any ideea on my problem on how how i can access a user s camera in my flask app??

serene prawn
#

@stable sorrel You can request user permission to access camera in javascript

stable sorrel
#

and hopw do i deal with the photo?

#

before i used opencv to save the photo in a folder and process it

serene prawn
#

You can send it to your backend

stable sorrel
#

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

serene prawn
#

I don't know either, 🙂
I think you could encode that screenshot as base64 and send it to your api

stable sorrel
#

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

stable sorrel
#

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']?

native tide
#

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?

golden bone
native tide
golden bone
native tide
boreal rover
#

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

golden bone
quasi tangle
#

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 ""

golden bone
quasi tangle
#

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?

dense slate
#

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?

random sand
#

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 %}```

dense slate
#

how is it not working, what error

random sand
#

Blank html document

golden bone
#

Does index.html exist? Your route doesn't refer to file-1 or file-2

random sand
#

hmmm

#

wai

dense slate
#

You sure it's pointing to the right place for your template/page?

random sand
#

yez

dense slate
#

What if you change it to return render_template('index2.html')

#

See if there's an error

random sand
#

everything is fine ....

dense slate
#

So then it's probably not pointing correctly to the file.

random sand
#

ok

#

should i change the name?

golden bone
dense slate
#

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.

lavish ferry
#

I made a cool thing!

dense slate
jovial cloud
# random sand this is index.html

'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'

past lion
#

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

indigo kettle
#

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...

past lion
#

is there another type of fields where i can choose many answers ? i mean is there alternative for the checkboxes ?

indigo kettle
#

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

past lion
#

yes exactly

past lion
indigo kettle
#

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

indigo kettle
#

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

past lion
past lion
#

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

indigo kettle
#

then you should create a foreign key in your main model out to the option model

solar obsidian
#

how can i make a switch

#

on the html that does stuff in python

golden bone
solar obsidian
golden bone
indigo kettle
solar obsidian
#

looking back it wasn't answered

past lion
golden bone
solar obsidian
#

i see

indigo kettle
fading bough
#

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.

dense slate
#

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.

fading bough
#

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

fading bough
#

My fault anyway for not reading into it that much

dense slate
# fading bough 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.

native tide
#

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

golden bone
native tide
native tide
#

would using using S3 count as using an API?

#

I wanted to use an API to build the web app just to show that I have experience using that