#web-development

2 messages · Page 208 of 1

native tide
#

I don't understand how does that relate to what I said

thorn igloo
#

man

#

it's better to google this stuff

#

you'll understand better than i can explain

#

a virtual environment is not really related to heroku

#

it's just a python thing

#

if you use pycharm you should realize that each project you make doesn't have the libraries you used in another project for example

#

it uses virtual environments to separate this

daring isle
#

Yeah in kivy ages ago

native tide
#
from gan import EnhanceAgent
from basicsr.archs.rrdbnet_arch import RRDBNet
import flask
from PIL import Image
import io
import numpy as np
import cv2



@app.route("/enhance", methods=["POST"])
def enhance():
    if flask.request.method =="POST":
        if flask.request.files.get("image"):
            image=Image.open(io.BytesIO(flask.request.files("image").read()))
            image=np.array(image)
            upscale=EnhanceAgent(
    scale=4,
    model_path="ImageEnhance.pth",
    model=RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4),
    tile=0,
)
            final=upscale.enhance(image, outscale=3.5)
            return final

print('done')

#

I am setting the following as my FLASK_APP environment variable

#

it throws the error: NameError: name 'app' is not defined

#

why is this the case?

native tide
daring isle
thorn igloo
daring isle
native tide
#

Thats it? Damn

daring isle
#
import React, { useState, useEffect } from 'react';
import axiosInstance from '../axios';
import { useParams } from 'react-router-dom';
//MaterialUI
import CssBaseline from '@material-ui/core/CssBaseline';
import { makeStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
import Typography from '@material-ui/core/Typography';
console.log('start')
const useStyles = makeStyles((theme) => ({
    paper: {
        marginTop: theme.spacing(8),
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
    },
}));
console.log('18')
export default function User() {
    console.log('20')
    
    const { id } = useParams();
    const classes = useStyles();
    console.log('23')
    const [data, setData] = useState({ users: [] });
    console.log('25')
    useEffect(() => {

my code is longer but never hits log 20 in the console, anybody see anything wrong with my export?

thorn igloo
daring isle
#

this is what im trying to do

#

go from userlist component to a single user view

thorn igloo
#

youre exporting default User()

#

what is that?

#

isn't that a component

#

yes, it's a function

#

let me rephrase, where are you using this function

daring isle
#

im going from a tutorial who uses the singlular for their object,
blog posts , is listed as function post there

#

im trying to return user list instead of posts and user instead of post, im very confused atm

thorn igloo
#

that function returns html right? or jsx etc, whatever you want to call it

thorn igloo
#

if so,

#

if you're not seeing the 20 in your browser console, it basically means that component is not being mounted at all

#

i.e, it's not being used

daring isle
#

yeah its not, but i dont know how to get my user to show, its showing in my api , but cant figure it out in react

#

im trying to look online for like 2 days and cant find out the solution lol

thorn igloo
#

what are you trying to achieve exactly?

daring isle
#

I have a user model, i have that displayed as a component sucessfully.
it shows a row of cards for my users.

I want to click one and show a screen specific for that user using the pk

#

i've set the serialiser up in drf and the json is fine, i just have no idea how to render it in react

#

these are my cards

thorn igloo
#

so backend is returning json?

#

of the user you want to display etc

daring isle
#

yep , if i type the id into the address bar it gets the correct record

wise osprey
thorn igloo
#

right, so are you using axios by chance? or just fetch

daring isle
#

axios i believe, but im frankensteining the code as im trying to learn js

thorn igloo
#

ok, so it has a get method, i'm sure you know that by now

#

you can use that to fetch the data

#

so basically, if i understood you correctly, you're fetching a userlist and displaying it

#

so i see you have a route like /userlist/:id

#

so you can navigate to this from the /userlist route

#

since you have your users already, you can specify the /:id part when you navigate

daring isle
#

yeah exactly

thorn igloo
#

then you can use axios to fetch the data from the id property

#

react router has a useparams constructor or function i believe

daring isle
#

do you have an example? the tutorial i was following used href={'/userlist/' + user.id}>

thorn igloo
#

yeah that works i guess

daring isle
#

my code doesnt reach my useParams()

thorn igloo
#

which react-router version are you using? 5?

daring isle
daring isle
native tide
#

Guys if I add some code, then I first use git add . git commit -m "commit message" and then push...to add code to heroku all I need is to write git push heroku?

thorn igloo
daring isle
#

"react-router-dom": "^5.3.0",

thorn igloo
#

ok, gimme a sec

native tide
#

@thorn igloo Could you please comment what I wrote above?

thorn igloo
#

just push to your repo, and link the repo to heroku

#

it will automatically detect your updates

native tide
#

This worked locally but doesn't work when I upload it to Heroku

thorn igloo
#

ok, so i just made this showing how to use useParams

#

so you can apply that to your application i guess

thorn igloo
native tide
thorn igloo
#

procfile

#

you're not supposed to invoke app.run

#

heroku will do the stuff for you

native tide
#

web: gunicorn PhotoMathBackend:PhotoMathBackend

thorn igloo
native tide
#

PhotoMathBackend

daring isle
#

so my routes should be in aoo instead of index?

#

app*

thorn igloo
#

i just like putting them in app

#

it's just a personal preference

#

has nothing to do with anything

native tide
#

@thorn igloo Do you know why I get error?

thorn igloo
#

web: gunicorn PhotoMathBackend:app

#

try that

#

and again, remove app.run

native tide
#

@thorn igloo Did I connect my GitHub repo and Heroku with this line

thorn igloo
#

idk man

#

i use the gui on the website to connect

#

if you're gonna use the cli, i can't help you there

native tide
#

So all you did is use gui on website to connect and any change in your GitHub repo is automatically detected to Heroku?

thorn igloo
#

huh?

#

i created a repo o. GitHub

#

went on heroku

daring isle
#

im not sure my app code allows for this , if i try use a to="" it doesnt do anything and i dont really know where to put the params in my userlist.

Ii dont understand javascript enough, and when i try look stuff up its always different ways and layouts .

#

at least i understand the api side and some of the component stuff, i need to do some more reading

thorn igloo
#

started an application, then chose a GitHub repo

#

if i push changes heroku will automatically detect them

#

that simple

#

i didn't use the cli interface

thorn igloo
#

you understand how an anchor tag works in html right?

#

the link component is basically an anchor

#

but this one just prevents the page from reloading

native tide
#

Actually I think this is last error

thorn igloo
#

it's saying request is not defined

#

did you import it?

daring isle
#

mate i barely understand how this is working, im not even trying to prevent reloads atm i just want to display my data.

I'll try read up. Do you know of any decent youtube tutorials for the correct way of doing things?

thorn igloo
#

normally I'd recommend ben awad for react tutorials

#

but I'm not sure if his videos cover react router

#

just checked, he does have a tutorial

#

so I'd say check him out

daring isle
#

ok will do!
thanks for the help man

thorn igloo
#

sure

native tide
#

@thorn igloo I imported Flask, so there should bee request

thorn igloo
#

idk man. just check your code

#

that you're using on heroku

native tide
#

@thorn igloo so does pip freeze detect libraries that I use in virtual envionment, libaries that I imported?

somber garnet
#

how can i display my images in my folder without having to place them in static?

native tide
#

click==8.0.3
colorama==0.4.4
Flask==2.0.2
gunicorn==20.1.0
importlib-metadata==4.10.0
itsdangerous==2.0.1
Jinja2==3.0.3
MarkupSafe==2.0.1
typing-extensions==4.0.1
Werkzeug==2.0.2
zipp==3.6.0
How so that all of that is in requirements.txt but I just installed Flask and gunicorn?

somber garnet
#

those are depencies for flask

#

and possibly gunicorn

#

dependencies

#

it installs those at the same time because flask needs them

native tide
#

ah I see - how so that I didn't have to install them locally?

#

or it was done in background?

somber garnet
#

it was done when you did pip install flask

native tide
#

I see

#

@somber garnet Are you familiar with running virtual environment for Python?

native tide
#

I have the following flask application

#
from gan import EnhanceAgent
from basicsr.archs.rrdbnet_arch import RRDBNet
import flask
from PIL import Image
import io
import numpy as np
import cv2


app=flask.Flask(__name__)


@app.route("/enhance", methods=["POST"])
def enhance():
    if flask.request.method =="POST":
        if flask.request.files.get("image"):
            image=Image.open(io.BytesIO(flask.request.files("image").read()))
            image=np.array(image)
            upscale=EnhanceAgent(scale=4, model_path="ImageEnhance.pth", model=RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4), tile=0,)
            final=upscale.enhance(image, outscale=3.5)
            im=Image.fromarray((final*255).astype(np.uint8))
            im.save('final.png')
            return final
#

I am trying to make a curl post request to this, how do I pass in an image to the curl request?

inland oak
civic dragon
#

I'm new to flask and trying to do a bulk insert (for array of objects from a form) into postgres, but am running into issues. Even though I'm running in debug mode, part of my issue is being able to log the body for the post request in the console, in order to debug and figure out a plan.

inland oak
#

or actually just write small python script

#

that uses library requests to do that

#

and launch it with python3 scrip_name.py

hazy hedge
hazy hedge
#

I also recommend to try httpx instead of cURL.

daring isle
#

In react , basic level . Are we calling api through components and delivering to index to send to root? Or calling through index and delivering to components ?

#

Where’s the first point of contact for the data ?

thorn igloo
#

you can make an api call wherever you need it. no need to call it in index if you don't need it there

native tide
#

hello everyone

#

I am developing a python app flask which is called by an another app via URL : https://host name:port/arg1=mdp &arg2=user -->hostname is my iis web server where i deployed the app. I would like to have a log per user --> when the user run the app it should normally create his own log and write in it, but unfortunately the mainthread write in all the logs of all users . I have tried : lock thread, multilogging, semaphore, socketio, calling with start-newthread -->No success 😦 Thanks for help

raw spade
#

hello, does app.route just give you a page(that has been specified)?

native tide
#

it run correctlu for all users

#

but it write in juste one log which is the first user

#

i initialise the log in the upload fun with the username extrcted from thr url and i try to write in this log

#

but it juste create the log and write in it for all users

#

app.run(debug=True)
kwargs = {'host': 'ip adress web server', 'port': port, 'threaded' : True, 'use_reloader': False, 'debug': False}
flaskThread = Thread(target = app.run, kwargs = kwargs)
flaskThread.start()

blazing dove
#

I want to increment a value set in Jinja2

{% counter = 0 %}

how can I do this outside a loop?

thorn igloo
blazing dove
#

I can't do that, I need to increment it in the front-end

#

oh... I figured out why it's not working

daring isle
blazing dove
native tide
#

Am I right that when you use flask and react, you have to use authentication tokens instead of flask sessions? This because the client who communicates with the flask API is always react and therefore the session will always be the same?

thorn igloo
#

react is just a frontend tool

inland oak
native tide
thorn igloo
#

with react, it's still html, css and js etc, but it's a SPA

#

so for this, if you want to check if a user is authenticated or not using sessions, you basically have to get that info from the backend

#

you can just set a route in your backend to check if a user is authenticated or not and store this in a state in react

#

whenever you want to do something that requires authentication, you check in the backend first

#

that's one way of doing it

mystic wyvern
#

i want to learn redux but there is two type of redux the first is the redux itself and the second redux toolkit which one is best ??

native tide
rotund perch
#

Hello, what is Django queues? and what is it used for?

civic dragon
# inland oak and launch it with `python3 scrip_name.py`

I'll look into this, but will it tell me the data hitting the post route? I'm using Postman to send the request. I'm able to save a single dict, so trying to see what's going on to save an array of dicts. I'm assuming I'll have to loop through and manipulate the form data...I just don't know what it looks like / what format in Flask. Data sent from Postman looks like so:
[{
"company_id": "E436FFF8-EAD6-43F8-9038-5BD46DFDDC74",
"family": "Plasticos",
"material": "Plastico Empaque",
"presentation": "Paca",
"unit_measurement": "Tonelada Gruesa",
"current_sale_price": "49.99"
}, {
"id": "B4CTC728-7A28-32D3-96TP-TDE47IG23Y90",
"company_id": "E436FFF8-EAD6-43F8-9038-5BD46DFDDC74",
"family": "Metales Ferrosos",
"material": "Chatarra",
"presentation": "Granel",
"unit_measurement": "Tonelada Gruesa",
"current_sale_price": "150.00"
}, {
"id": "C4CTC728-7A28-32D3-96TP-TDE47IG23Y90",
"company_id": "E436FFF8-EAD6-43F8-9038-5BD46DFDDC74",
"family": "Electronicos",
"material": "Abanicos",
"presentation": "Tarima",
"unit_measurement": "Kilogramo"
}]

native tide
#

OMG Heroku doesn't work

native tide
#

yeah I think it's down right now

native tide
#
[
    {
        "id": "dart-monkey"
    }
]
from flask import Flask, render_template, request
import json

with open("./data/towers/all_towers.json", "r") as f:
    towers = json.load(f)

# with open("./data/towers/primary/", "") as f:
#     primary = json.load(f)

# with open("./data/towers/military/", "r") as f:
#     military = json.load(f)

app = Flask(__name__)

# Checks (to see if the tower/hero exists)
def check_primary_tower():
    pass

def check_military_tower():
    pass

def check_magic_tower():
    pass

def check_support_tower():
    pass

def check_hero():
    pass


@app.route("/", methods=["GET"])
def home():
    return render_template("index.html")

@app.route("/tower/", methods=["GET"])
def tower():
    tower_id = request.args.get("id")
    return towers[tower_id]


# api.add_resource(Towers, "/towers/<string:id>")

if __name__ == "__main__":
    app.run(debug=True)

The first message is my JSON File and my other message is my python script. How do I return dart-monkey via the main.py (other message)

native tide
#

Error:

Traceback (most recent call last):
  File "C:\Users\Piman\OneDrive\Dokument\BTDBattles2 API\venv\Lib\site-packages\flask\app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\Piman\OneDrive\Dokument\BTDBattles2 API\venv\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\Piman\OneDrive\Dokument\BTDBattles2 API\venv\Lib\site-packages\flask\app.py", line 1867, in handle_excep
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Piman\OneDrive\Dokument\BTDBattles2 API\venv\Lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\Piman\OneDrive\Dokument\BTDBattles2 API\venv\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\Piman\OneDrive\Dokument\BTDBattles2 API\venv\Lib\site-packages\flask\app.py", line 1952, in full_dispatc
    rv = self.handle_user_exception(e)
  File "C:\Users\Piman\OneDrive\Dokument\BTDBattles2 API\main.py", line 39, in tower
    return towers[tower_id]
TypeError: list indices must be integers or slices, not str
lapis spear
#

what this mean?

#

i have a django project from pycharm and created a django project there but now i am using vscode and just copy pasta that folder to a vscode workspace and then i try to run the project it gives me that error

#

do i need to reinstall django?

dense slate
native tide
dense slate
#

JSON deserializes into a python dict

#

So it looks like you're creating a python dict from a JSON string

native tide
#

i put in an id and it returns:

#

which is correct but the issue is i made a file for every single tower/monkey

dense slate
#

It made all those files but you wanted to only create one?

native tide
#

no it didn't make any files i made the files myself and im gonna store data in all of them

#

so if i send a GET request to the server and it says ?id=dart-monkey i want it to return everything inside the dart_monkey.json

dense slate
#

So is this your error?
TypeError: list indices must be integers or slices, not str

native tide
#

yes

dense slate
#

So how did you get the proper return if that error pops up.

native tide
#

i changed the json into only {}

#

but that's only for testing right now but im looking for another solution

dense slate
#

The error is saying that you are trying to do list["string"] when you need something like list[0]

#

so you need a dict if you want to seach by key-value pair

native tide
#

oh ok so i just remove the []

#

from the json file

dense slate
#

Your json should return something in {}'s

#

unless it is a list of objects

#

then it can be [{}, {}, {}, etc.]

native tide
#

im trying to achieve this:

#

but if i change url

dense slate
#

actually even then I think JSON needs to return {}'s.. but anyways

rotund perch
#

where are pip (Pypi) packages are stored in Django?

native tide
#

Example 1:

Example 2:

dense slate
# native tide

I'm not 100% off the top of my head, but I think you can just import the file if it's a list. If you import it, then json.loads, you convert it into json.

native tide
dense slate
#

I would structure it something like {{id: 0, data: "data"}, {id: 1, data: "data"}}, then you can select by id or whatever you want

#
def tower():
    tower_id = request.args.get("id")
    with open("./data/towers/" + tower_id + ".json", "r") as f:
      towers = json.load(f)
    return towers
#

Maybe something like that?

native tide
#

oh actually that might work

#

i'll try that

dense slate
#

That might be kind of insecure, I'm not sure. But if someone can write something into the URL that is m malicious, that might be a problem with this kind of code.

#

I don't know if that matter for you right now.

native tide
#

no that doesn't matter

#

right now

dense slate
#

Or you didn't run inside of an active virtualenv if you are using one (which you should be).

dense slate
rotund perch
lapis spear
dense slate
#

Only thing I ever added to PATH was python.

lapis spear
next mulch
#

Has anybody used pipelines on gitlab? I am unable to authenticate my user credentials it asks for card details (did that too, ) but still facing issue

solid karma
#

Error:
AssertionError: SessionMiddleware must be installed to access request.session Traceback

#

I don't understand because I clearly added it

#

~~Relevant Code:

import secrets

from fastapi import FastAPI
from starlette.middleware.sessions import SessionMiddleware

app = FastAPI()

app.add_middleware(SessionMiddleware, secret_key=secrets.token_urlsafe(64))```~~
solid karma
#

Fixed

native tide
#

.topic

fallow cairnBOT
#
**How has Python helped you in web development?**

Suggest more topics here!

native tide
#

is there anyway i could stop this from being spammed / running the python program more then once

       <?php


        if (isset($_POST['Play'])) {
            if ($gamerows['online'] == 1) {
                echo 'True';
            } else {
                $JobID = $gamerows['id'];
                $port = $gamerows['port'];
                $userid = $_SESSION['id'];

                $output = shell_exec("start OpenGameJob.py {$JobID} {$port} {$userid}");
                print ($output);
                echo "False";
            }
        }

        if($gamerows['status'] == "public") {
            $auth = $usr->{'auth'};
            $gameidjoin = $gamerows['id'];
            $uri = "Humanium16://$auth-$gameidjoin";
            echo '
            <form method="post">
                <input type="submit" name="Play" value="Play" href="'.$uri.'" id="MultiplayerVisitButton" class="btn-primary-lg VisitButton VisitButtonPlayGLI" placeid="<?php echo $gameID;?>" data-action="play" data-is-membership-level-ok="true">
                </input>
            </form>';
        } else {
            echo ' 
           
            <div class="rbx-visit-button-closed">
                Sorry, this place is currently closed to visitors.
            </div>   ';
        }
        ?>```
native tide
#

I am trying to deploy my Tensorflow 2 project with Flask on Heroku, but it seems that storage limit is exceeded - I already used Tensorflow-cpu and it didn't worked out.

Do anyone have any advice with regards to my problem?

Also, is there any other free hosting?

manic crane
#

i keep getting {
"message": "Invalid credentials, try again"
}. but the user is already created

#

my code => class LoginAPIView(GenericAPIView):
serializer_class = LoginSerializer

def post(self,request):
    email = request.data.get('email',None)
    password = request.data.get('password',None)
    
    occupier = authenticate(username=email, password=password)

    if occupier:
        serializer = self.serializer_class(occupier)
        return response.Response(serializer.data, status=status.HTTP_200_OK)
    return response.Response({"message":"Invalid credentials, try again"}, status=status.HTTP_401_UNAUTHORIZED)
#

class LoginSerializer(serializers.ModelSerializer):
password = serializers.CharField(max_length=200, min_length=6, write_only=True)
class Meta:
model = Occupier
fields = ['email','password','token']

    read_only_fields = ['token']
sweet karma
#

can anyone see what is wrong here?

#

does not show invalid email

coral wagon
opaque rivet
#

oh man, pycharm added fastAPI boilerplate option when creating a project. Is this a sign to learn it?!

stable yew
#

why does it say this

#

neeeeeeeeeeeed help

edgy hinge
#

Anyone can suggest me Django best book to learn in depth?

inland oak
edgy hinge
#

So where to start? Is it sorted list of 3?

inland oak
#

The look like this, except 3.2 is written

inland oak
#

the book about APIs tells about REST APIs

edgy hinge
#

Okay, I will decide it let me finish the first one first.

warped aurora
edgy hinge
#

@warped aurora I want to directly begin with django. Is there any problem if I begin with django ?

tight ocean
#

Hey guys!

#

I'm trying to run my flask website online instead of localhost

#

I have put my index.py file in the root directory

#

But it doesn't seem to work online

#

In localhost it showed the website perfectly

#

Anyone any idea?

golden bone
tight ocean
#

from

#

template/index.html

#

it all linked perfectly in localhost

#

so i just uploaded the files

#

but online i get a 403 error

golden bone
#

If your host is setup for static files, uploading Python there isn't going to work.

tight ocean
#

seriously?

#

i reserved hosting and a domain

#

how else do i get my flask application online

golden bone
#

Hosting where?

tight ocean
#

godaddy

golden bone
jovial mortar
#

Does anyone know the vulnerabilities with running django with the --insecure flag? (to serve static files). I thought it might be something with being able to query "/../.env" and access hidden files but I havent been able to recreate that in any tests.

stable yew
#

whats the difference between

#

and calling Usres() constructors directly in django

#

while adding users to the db

rigid loom
#

Please don't advertise here

golden bone
warped aurora
#

when doing alembic migrations i notice some tutorials import the models to the env.py and some don't and it works fine either way, sup with that?

strange charm
#

Hello everyone, can i use slack for messaging on my website? for group chat?

proper trench
south rivet
#

Which one will take the lead to dive into (Flask or Django)?

manic frost
jovial mortar
#

Flask is typically simpler and nicely suits smaller projects with an easy workload. django scales better if you're looking to become the next discord

#

But I've used both with no issues

jovial mortar
jovial mortar
#

You could always tie it into a discord webhook kek

golden bone
warped aurora
#

{% for field in form %}
{{ field.label }}
{{ field }}
How would make this loop only over the 1st two fields?

golden bone
wind lotus
#

i learned html and css, and now ima learn JS, but should i be learning how JS works with html and css, or does it not matter and I could just flip open a book and solely learn JS (I alrdy know python fyi)

warped aurora
golden bone
#

And still use a for loop

native tide
#

Is this Django? try {{ company|slice:'4:7' }}

golden bone
#

^^^ Better idea

native tide
#

Best way I've found for searching these is "django template <thing you'd do in python"

#

so I did "django template slice"

warped aurora
#

oh shit jinja takes python statements

warped aurora
native tide
#

jinja might be similar, I mostly use django

#

django templates are somewhat python, but often have their own syntax like you can't do form[0:30]

#

looks like jinja does have a |slice: though

warped aurora
sweet kraken
#

hello

daring isle
cold portal
#

Anyone have any suggestions on how to get a file upload to work with fastAPI? Getting this json response and my Google results aren’t helping….. {"detail":[{"loc":["body","file"],"msg":"field required","type":"value_error.missing"}]}

sweet kraken
#

this is my first time web scraping, and I don't know how to log in using Beautifulsoup4

#

Help pls

cold portal
#

Http 422 unprocessable entity

cold portal
golden bone
# sweet kraken this is my first time web scraping, and I don't know how to log in using Beautif...
#

Mindful of rule 5 though, I will assume you're not trying to break ToS

topaz thunder
#

Where do I learn web developement using python??

whole sierra
#

can anyone point me in the right direction to receive webhooks with django

stable yew
#

whats this error

mystic wyvern
eager relic
#

Is django slow?

stable bear
#

I am learning how to use django for a web application. How do I automatically update the time every few seconds, without having to refresh the page for the time to update?

eager relic
#

interval

ivory lotus
#

hurrr

#

I'm guessing I can't post html here

hasty oracle
#

can anyone point me to a discord server where I can ask questions relating to GIT repositories?

inland oak
manic frost
pine maple
#

Hi Guys!
I'm currently building my first microservice using flask and thinking about hosting it now.
Need to discuss somethings about best ways to host flask microservices with someone.
Would really appreciate the help.

golden bone
inner viper
#

Peace Be Upon All Of You Guys

ivory lotus
#

can I ask HTML questions here lmao

tawdry vault
#

Merry Xmas everyone. I got idea about more files in flask app like in one i have normal webpages without api sites, and in other file i will have only api sites like add something in database and so on. How should i do that ? Bsc when i use app.route('/add-item', methods=['POST']) I need to define function. But i want to call function from another file. Should I make function that will just call another function from another file ? 😄

inland oak
inland oak
#

long answer: you should have your views (function that is routed) being short enough, handling only really simpliest workflow with input/output data

#

most of the action should happen in your model, packages and e.t.c. Basically where the domain specific logic is supposed to be

ivory lotus
pine maple
#

I have been looking into lightsail EC2 and other stuff but not entirely sure about either'

inland oak
#

are you working in company or making it as pet project for yourself

#

what are other components existing in your architecture

inland oak
#

If you wish to have a simple answer...

inland oak
inland oak
#

it could be simpler to use a bit more simple provider

#

I would recommend to try a hand in Digital Ocean, Vultr, Linode.... or even Hetzner

#

They are all cheaper and simpler to use

#

AWS in my opinion is so overbloated in its interface, that without Infrastructure Provisioning (aka Infrastructure as a code) tools it looks a bit nightmare to approach 🤔

weary crane
#

i'm a bignner in web development , i have learned html and css to some extent , and also i'm currently working with python , i want learn frame work for web development , can someone suggest me how i can procide further in web development and also python , i'm currently in 12th standard opted python through school

#

that's why its also a bignning of python

native tide
#

just try to make something and look things up along the way

wise osprey
#

How can I run a Flask app on a different WSGI server then use Apache as a proxy on port 80?

#

Werkzeug worked fine but it is not recommended for production.

native tide
#

Run gunicorn and bind to a port, say 8080, then have apache reverse proxy traffic to the gunicorn worker running on 8080

wise osprey
#

supports FreeBSD which is good

native tide
#

then set it up as a service and it will restart if the server goes down, that's what I usually do. Little bit of setup, but then it's so easy to deploy, restart, etc

#

I do it with nginx and django, but same idea

#

.topic

fallow cairnBOT
#
**What tools do you use for web development?**

Suggest more topics here!

native tide
#

figma for design, flask for backend, css/html for frontend

wise osprey
#

To answer both:
FASP - FreeBSD Apache SQLite Python

FreeBSD SSH, Vim, Flask and SQLite for backend, html/css for frontend. I used Geany on Debian 11 to dev a webapp for a while before returning to using FreeBSD remotely.

native tide
#

For work: Postgres/Python/Django/GraphQL on GCP. Front end is React, but I don't work on it
Personal: Postgres/Python/Django/Flask/FastAPI depending on what I'm doing behind Nginx and usually deploy on Debian on Linode

patent glade
#

Quick Javascript question

#

The children attribute shows only the element children of an element, right?

#

While the childNodes attributes shows element children as well as text and comment nodes?

#

NVM

manic frost
#

my favourite one is the NOBODY EXPECTS THE SPANISH INQUISITION one

native tide
#

throwback to when LAMP ruled the web, maybe?

manic frost
wise osprey
#

think LAMP still runs the net, even substituting the PHP for Python

native tide
#

fair point

#

lot more nginx than apache now, lot more postgres than mysql

wise osprey
#

makes sense, have not used nginx much, kind of discouraging as a noob when you get 5xx errors when trying to use it for the first time

native tide
#

Yea. It takes a bit of getting used to.

lilac sedge
#

I have a question involving flask, and a website im making would that fit in here?

#

or would that be a different channel

wise osprey
#

yes, this one

lilac sedge
#

ok I just wanted to make sure, basically i'm trying to make a website where at the moment you can just enter something into a text field then it will print on my pycharm run console, but when you hit enter on the text field it just loads a new page saying method not allowed any ideas on how to fix this?

#

I can post some of the code if that would be helpful

native tide
#

Do you have your route allowing "GET" and "POST"

lilac sedge
#

from flask import Blueprint, render_template, request

auth = Blueprint('auth', name)

@auth.route('/', methods=['GET', 'POST'])
def root():
data= request.form
print(data)
return render_template("index.html", boolean=True)

#

yeah thats some of the code there

#

but even with this it's still saying method not allowed

wise osprey
#

Here is an example, if the request is POST, under else: handles it

lilac sedge
#

never mind i think i fixed it lol but thanks

wise osprey
#

np

#

No venv or proxy yet, would this work?

#

leaked the app name lol... whoops

native tide
#

That gunicorn command looks right. Might want to try 127.0.0.1 instead of 0.0.0.0 as best practice, but otherwise good.

wise osprey
#

If it binds to 127.0.0.1, it is not accessible but if it is going to be proxied, then I would use 127.0.0.1

#

as far as I know

wind lotus
#

if i had my width as 100%
but i also want my height to be as the same as my width, so that i get a square
i cant just do height: width;
what else can i do so that I can get my height == width

wind lotus
wise osprey
wind lotus
#

mm, not quite

#

it's like this and i want the width of each red square to be equal to the height when width is 100%

#

nvm, ig there's no way around it, i'll just have to use whatever width the parent is as the height

wise osprey
distant trout
#

how do you guys check for vulnerabilities on ur web apps?

#

for example i am finishing up implementing my own authentication library for react/nextjs, problem is i have no idea how to test for vulnerabilities. ive checked for obvious security flaws but that's about it...

lapis spear
#

i am planning to create simple website using django
is my erd on the right track?
a user can post and comment on posts

distant trout
#

how do services like auth0 and nextauth check for vulnerabilities?

lapis spear
#

on the react and likes feat where do i put em? on comments?

distant trout
#

id personally have a independent PostLike model for posts and have a user_id and post_id associated with it

lapis spear
#

do they need own tables? to show who liked or reacted?

distant trout
#

i implemented something like this with flask a couple years ago. this was my like model

class PostLike(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'))
    post_id = db.Column(db.Integer, db.ForeignKey('post.id', ondelete='CASCADE'))
#

shouldnt be much different from django

#

my user model for reference;

#
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True, nullable=False)
    username = db.Column(db.String(30), unique=True, nullable=False)
    password = db.Column(db.String(120), nullable=False)
    date_joined = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    posts = db.relationship('Post', backref='author', lazy=True, passive_deletes=True)
    comments = db.relationship('Comment', backref='author', lazy=True, passive_deletes=True)
    likes = db.relationship('PostLike', backref='author', foreign_keys='PostLike.user_id', lazy=True, passive_deletes=True)
lapis spear
#

i added 2 tables yeah maybe it will look like this?

distant trout
lapis spear
#

nice nice thank you sir 🥳 👍

timber pulsar
#

yo

#

I am using Quart (Async Flask), I've set SERVER_NAME to my domain name

#

in order to use built-in subdomain handling

#

BUT i've come across an issue

#

when doing requests without server_name

#

they are refused...

#

anyway around this, as I'd like to keep using the fast local requests to 0.0.0.0

serene prawn
#

You could use composite primary key, you wouldn't need an id and it would also provide uniqueness check

distant trout
jovial mortar
distant trout
#

dont think ive worked with many relational data since then

jovial mortar
#

but i'll rewrite it after we release

unborn oyster
#

I have a script that gets values from an api and uses flask to display them on a site

#

how would I get these to auto "refresh"

#

not refreshing the page but the values should refresh

simple phoenix
#

Store in json send json to page in client use javasript (arrg) some frameork like rescy

#

React or i forgot the others i hate client side lol

#

Much wow such hassle

#

What ever js framework your site use use it ... remember a sudo shibq has great power and responsibility not to put in too many frameworks of js for much confuse and such suffer

thorn igloo
#

you can use ajax calls to update the data every now and then

#

ajax calls + a setInterval function

#

no need to really use a framework for a simple thing

edgy lily
#

Hey, anyone here familiar with web3

#

I am looking tutorials on how to use web3 frameworks like web3.py but they only talk about interacting with the blockchain, but none of them talks about how to actually put a website up there

golden bone
edgy lily
#

thanks man

wise osprey
#

Is it possible to get the name of the WSGI server in a Python script?

golden bone
wise osprey
golden bone
grizzled verge
#

Does anyone have idea about hosting a Flask Socket Chat Room to Heroku

timber pulsar
#

I've set my Flask App SERVER_NAME to my domain name
yet when I try to access it with 0.0.0.0 I am no longer able to
anyway around this?

/usr/local/lib/python3.8/dist-packages/quart/app.py:851: UserWarning: Current server name '0.0.0.0:10511' doesnt match configured server name 'domain.com'
  return self.url_map.bind_to_request(request, subdomain, self.config["SERVER_NAME"])```
lapis spear
#

yo is django manytomany and onetomany like joins?

final fiber
#

Does anyone know of a good place online that I could use for programming a webpage?

wraith dagger
#

Hey there! I have "localhost didn't send data" error, when I try to send response to localhost:8000. I have dockerized django (I have exposed 8000 port, but it still empty response). What I forgot to do?

proper hinge
#

What IP is the server listening on? If you're starting the server with 127.0.0.1:8000, try using 0.0.0.0:8000 instead

wraith dagger
#

oh my, I totally forgot about networking 😄 ty, Mark

proper hinge
#

You're welcome

native tide
#

I am trying to dockerize my flask api

#

and the docker builds properly but when running the docker container, I see the following error message:

#
 * Serving Flask app 'enhance.py' (lazy loading)

 * Environment: production

   WARNING: This is a development server. Do not use it in a production deployment.

   Use a production WSGI server instead.

 * Debug mode: off

Usage: python -m flask run [OPTIONS]

Try 'python -m flask run --help' for help.


Error: While importing 'enhance', an ImportError was raised.
#

there is nothing wrong when I run the flask app on my local

#

any reason why you guys think this could be happening because I am lost

#

since it does work on local

real sparrow
#

I have a question regarding fastAPI if anyone wants to take a crack at it? over in #help-mushroom

manic frost
real sparrow
#

@manic frost you are amazing. I was starting to think it was something to do with the closure but wasnt able to find the words to describe it hha

timber pulsar
#

I've set my Flask App SERVER_NAME to my domain name
yet when I try to access it with 0.0.0.0 I am no longer able to
anyway around this?

/usr/local/lib/python3.8/dist-packages/quart/app.py:851: UserWarning: Current server name '0.0.0.0:10511' doesnt match configured server name 'domain.com'
  return self.url_map.bind_to_request(request, subdomain, self.config["SERVER_NAME"])```
inland oak
inland oak
timber pulsar
#

I want my bot to be able to locally request to webserver

#

without going through cloudflare unreasonably

inland oak
#

While having run prod instance separated

#

With running them with different env values

#

One thing should be possible to request by one domain, while other by another domain) like localhost

timber pulsar
#

sadge

inland oak
#

I think in some option you could accept requests from any domain

#

But I would hate it because of sniffers and hackers

#

Every IP address of any major cloud provider is constantly scanned for vulnerabilities by all sides of people

timber pulsar
#

i need subdomains

#

was wondering if instead I could route like in windows where you do hosts file

#

routing a server name to a local ip

#

but on linux

inland oak
#

Write example of the desired end result

inland oak
#

I think it should be able to listen to multiple domains and having different targets for each one

golden bone
native tide
#

I did run the shell of the docker image and enhance.py is in the project

golden bone
native tide
#

of course, thank you for agreeing to help me

native tide
native tide
native tide
native tide
#

nothing, you asked me to see how you used the precode, neat

native tide
#

I suppose you're supposed to set it to a color

#

and not a theme

#

hold on

#

background: #your color hex code here

#

;

stable bear
#

I am using django to build a web application. I would like my web app to update itself every second. How would this be done?

stable bear
#

like if i am displaying the current time on the page
i want the time to change by itself
and not for me to have to refresh the page

native tide
#

How can i scrap web site without blocked please (couldflare)

thorn igloo
#

with like the setInterval function you can regularly update

manic frost
lavish prismBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

edgy lily
#
from application import init_app
#

i have trouble installing this 'application'

#

it says that it did not find mysql_config

unborn pulsar
#

Hi guys, I have a question regardig python django. I am not sure if I understand it correctly but can I build web applications using Django and python ? Or is html CSS JavaScript needed as well in the process ?

edgy lily
#

i think html and css is needed

unborn pulsar
#

I was hoping it is not but yeah that's understandable hrh

native tide
#

you can use bootstrap

#

css/html not needed but it would be preferred

unborn pulsar
#

I do care about web apps and web development and I work for a corporation where python is recommended and now much of a typical html CSS JavaScript so that's a pretty good news

#

Not much *

#

Thank you for the answers guys I'm going to look into it ❤️

edgy lily
#

does anyone know how to make the wsgi.py in flask

#

nvm i got it

manic garnet
#

hi

#

just here wanted to ask something

#

what do you prefer the most

#

flask vs django

stable bear
#

how do i integrate javascript?

manic garnet
haughty isle
#

.mjs

#

and depends on the name of your app

#

are you using django?

stable bear
#

yes

haughty isle
#

yeah so you put it in app/static/app/index.mjs

#

or whatever you called your app?

#

cool

#

is it working?

stable bear
#

i have a variable 'now' created in views.py, and currently this is what i have in index.html. how do i update this 'now' variable using javascript?

haughty isle
stable bear
#

this is quite new to me - what is the syntax to do this?

tiny snow
#

Responsiveness (button events and such on the front-end)

haughty isle
tiny snow
#

Client stuff like changing text according to the current time should be easy to do with JavaScript

haughty isle
#

please don't use screenshots - just use

#

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

haughty isle
#

use


```html
<head></head>
 if you want to paste inline
#

no space between the ```

#

and the html

#

so you'd give the elements you want to update ids:

<h1>Is it New Year?</h1>
<h1 id="is-new-year">{{ newyear|yesno:"YES,NO" }}</h1>
<h1>The date and time today is <span id="now">{{ now }}</span></h1>
#

@stable bear ^

#

what do you mean by that?

#

?

stable bear
#
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Is it New Year's Day?</title>
    <link href = "{% static 'newyear/style.css' %}" rel = "stylesheet">
    <script src="{% static 'newyear/index.mjs'%}" type="module"></script>
</head>
<body>
<h1>Is it New Year?</h1>
{% if newyear == True %}
    <h1> YES </h1>
{% else %}
    <h1> NO </h1>
{% endif %}
<h1>The date and time today is <span id="now">{{ now }}</span></h1>

</body>
</html>
haughty isle
# stable bear ```html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta char...

in your .mjs file you can put:

const isNewYear = document.getElementById("is-new-year");
const now = document.getElementById("now");
const sleep = async (delay) => {
  await {
    then(fn) {
      setTimeout(fn, delay);
    },
  };
};
while (true) {
  const currentTime = new Date();
  isNewYear.innerText =
    currentTime.getMonth() === 0 && currentTime.getDate() === 1 ? "YES" : "NO";
  await sleep(1000);
}
export {};
haughty isle
#

you can add the code for updating now.innerText ?

stable bear
#

ill try it

haughty isle
stable bear
haughty isle
#

Show your html?

stable bear
#
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Is it New Year's Day?</title>
    <link href = "{% static 'newyear/style.css' %}" rel = "stylesheet">
    <script src="{% static 'newyear/index.mjs'%}" type="module"></script>
</head>
<body>
<h1>Is it New Year?</h1>
{% if newyear == True %}
    <h1> YES </h1>
{% else %}
    <h1> NO </h1>
{% endif %}
<h1 id="is-new-year">{{ newyear|yesno:"YES,NO" }}</h1>
<h1>The date and time today is <span id="now">{{ now }}</span></h1>

</body>
</html>
haughty isle
#

Why do you have newyear twice?

#

Just delete it

opaque rivet
#

I'm setting env variables in my docker-compose file, but they're not accessible by the application (KeyError when accessing os.environ["env_key"]). Any ideas why?

cosmic dirge
#

hey um, quick question. do i need to locally host a web server in order for flask to run

manic frost
#

How do you log stuff with uvicorn? The "simple way" with logger = logging.getLogger(__name__) and then logger.info("something") just... does absolutely nothing

warped aurora
#

trying to submit a wtform and getting this error Object of type StatementError is not JSON serializable..an error is being generated and somehow submitted in the form?

sweet karma
#

Hello boys and girls have a question how to write something like that validate_password in Flask because at the moment it throws error email attribute missing

glacial portal
#

When do we use sub url?

manic crane
#

anyone see anything wrong ?
ImportError: Could not import 'Occupier.jwt.JWTAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ModuleNotFoundError: No module named 'authentication'.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'Occupier.jwt.JWTAuthentication',
]
}

glacial portal
#

anyone see anything wrong ?
ImportError: Could not import 'Occupier.jwt.JWTAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ModuleNotFoundError: No module named 'authentication'.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'Occupier.jwt.JWTAuthentication',
]
}

#

why is it
'authentication'.
...

edgy lily
inland oak
violet dock
#

Is it possible to get users who connect to the socket on flask?

versed lotus
#

fastapi is nice, all async and stuff. but I also really like sqlalchemy, and sqlalchemies async support, while present, is still kinda meh.

warped aurora
#

Using] wtforms.fields.html5 import DateField..when the form field is empty it displays like this..is there a way to hide it? or make it blank

versed lotus
#

I think that's browser dependent, but try to set a placeholder text?

warped aurora
versed lotus
#

then I got no idea. it's probably not possible because browsers benjyvr_shrug

warped aurora
#

Lol

versed lotus
#

the great thing with type=date is, it's different for all browsers

#

so I usually end up using text with a js datepicker anyway ...

warped aurora
#

hmm

versed lotus
#

maybe you can overlay a text field instead 😄

#

and have them hook up with each other

#

not sure that's gonna work in a good way though

warped aurora
#

Gonna try the js datepicker

vast rune
#

I am having an issue with channels / django where fast real time data is being sent in intervals instead of when I call the group_send
Instead of sending the data via websocket. It tends to wait and then send ~10 messages together.

layer = get_channel_layer()
  async_to_sync(layer.group_send)("webapp",
     {"type": "dataSend","category": "imu",
      "data":[sess.id, imu_cnt, imu_time, ax, ay, az, wx, wy, wz, batt, rssi]})
async def dataSend(self, event):
     send_json = json.dumps({"type":"dataSend","category":event["category"], 
                             "data": event["data"]
                            })
     await self.send(text_data=send_json)
#

(the group_send is being called ~every 15ms) but instead of sending that "Data" in a self.send. It waits and sends ~ 10 together to my frontend

haughty isle
#

Also what web server are you using?

#

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

vast rune
#

I use the one django comes with on this cpu

haughty isle
vast rune
#
class ApiConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        self.group_name = "webapp"
        await self.channel_layer.group_add(self.group_name, self.channel_name)
        await self.accept()
        await self.cacheCheck()
        self.threadOn=True
        self.cache_touch =  threading.Thread(target = cacheTouch, args = (self,), daemon = True).start()

    async def receive_json(self, content):
        logging.debug("recieved... " + str(content))
        try:
            command = content.get("message", None)
            # logging.debug("msg... " + str(command))
            #  Under construction

        except Exception as e:
            # Catch any errors and send it back
            await self.send_json({"error": e.code})
        
    
    async def disconnect(self, close_code):
        logging.debug("Disconning Websocket.... code: " + str(close_code))
        self.threadOn=False
        await self.channel_layer.group_discard(
            self.group_name,
            self.channel_name
        )
    async def dataSend(self, event):
        send_json = json.dumps({"type":"dataSend","category":event["category"], 
                                "data": event["data"]
                                })
        await self.send(text_data=send_json)
        
    async def cacheUpdated(self, event):
        send_json = json.dumps({"type":"cacheUpdated", "cache_name": event["cache_name"],
                                "value":event["value"], "method":event["method"],
                                })
        await self.send(text_data=send_json)
#

oh

#

ok ill put daphne on this cpu and try again

haughty isle
#

What's cacheTouch?

#

Don't use threads like that with asyncio, use await asyncio.to_thread(sync_fn)

vast rune
#

yeah it is still the same problem (

#
    async def cacheCheck(self):
        data={}
        data['locator1_streaming']=cache.get('locator1_streaming', False)
        data['node1a_recording']=cache.get('node1a_recording', False)
        data['locator1_mac']=cache.get('locator1_mac', None)
        data['node1a_mac']=cache.get('node1a_mac', None)
        data['robot1_running']=cache.get('robot1_running', False)
        data['robot1_recording']=cache.get('robot1_recording', False)
        data['node1a_batt']=cache.get('node1a_batt', None)
        data['node1a_rssi']=cache.get('node1a_rssi', None)
        send_json = json.dumps({"type":"cacheInitial", "data": data})
        await self.send(text_data=send_json)

def cacheTouch(wbsckt):
    # layer = get_channel_layer()
    #keep cache alive while connected to
    while wbsckt.threadOn:
        cache.touch('locator1_streaming', 20)
        cache.touch('node1a_recording', 20)
        cache.touch('locator1_mac', 20)
        cache.touch('node1a_mac', 20)
        cache.touch('robot1_running', 20)
        cache.touch('robot1_recording', 20)
        cache.touch('node1a_batt', 20)
        cache.touch('node1a_rssi', 20)
        time.sleep(3)
        # async_to_sync(layer.group_send)("webapp",
        #                         {"type": "cacheUpdated", "cache_name": "dummy"})
#

I use memcached to store whether I am connected to devices or streaming the datato a queue

#

I need to keep those memcaches alive while the user still has browser open / websocket is open

#

I can remove that thread for now if you think that is causing my issue

rotund perch
#

Hello, is it possible to have a seperated app (another backend framework) that offers the authentication and connect it with django so django can recognise the tokens that came from the different app and consider it an authorized user

haughty isle
vast rune
#

hmm i don't think so

#

if I understand your quesion correctly... but I turned all of that off and I still have this delay

#

I even went to a sync consumer

#

same

#

the websocket keeps sending the group of messages every 1-2 seconds

#

plus cache.get only occurs on the connection. That all works well.. My issue is with the

    async def dataSend(self, event):
        send_json = json.dumps({"type":"dataSend","category":event["category"], 
                                "data": event["data"]
                                })
        await self.send(text_data=send_json)
#

Here is the function that reads from a queue and sends the data to the websocket

#
def consumeIMU(sess,imu_queue,cal_data=[]):
    #d=[67, 15345438, 2618, 13824, -5439, 8946, 8946, 3389, -1, -52]
    # [n, time, ax, ay, az, wx, wy, wz, batt, rssi]
    cacher("set",'node1a_recording',True,10)
    first_time = 0
    prev_time = 0
    update_time=0
    roll_cnt=0
    batty=-1
    ra = []
    cnt=0
    isCal = False
    with imu_queue.mutex:
        imu_queue.queue.clear()
    if(len(cal_data)==5):
        isCal = True
        ao = absOrientBasicCal(cal_data[0],cal_data[1],
                                cal_data[2],cal_data[3],cal_data[4])
    while (cache.get('node1a_recording',False)):
        while not imu_queue.empty():
            # qsz=imu_queue.qsize() # imu_queue.task_done()
            cnt += 1
            [imu_cnt, imu_time, ax, ay, az, wx, wy, wz, batt, rssi]  = imu_queue.get()
            imu_time = imu_time + roll_cnt*(2**24)
            if(first_time==0):
                first_time = imu_time
            elif prev_time > imu_time: #protect against 3-byte rollover
                roll_cnt += 1
                imu_time = imu_time + 2**24
            prev_time = imu_time
            imu_time = imu_time - first_time
            if(batt>0):
                batty=batt
            if(imu_time-update_time>25600):
                update_time=imu_time
                send_imu_data(batty,rssi)
                batty=-1
            r = IMURead(session = sess, imu_cnt = imu_cnt, imu_time = imu_time,
                ax = ax, ay = ay, az = az, wx = wx, wy = wy, wz = wz,
                batt = batt, rssi = rssi)
            ra.append(r)
            if(isCal):
                ao.update(wx,wy,wz,imu_time)
            if(cnt>5):
                break
#
        if(cnt>5):
            read_list = IMURead.objects.bulk_create(ra)
            layer = get_channel_layer()
            logging.debug(imu_time*39.0625/1000000)
            async_to_sync(layer.group_send)("webapp",
                        {"type": "dataSend","category": "imu",
                            "data":[sess.id, imu_cnt, imu_time, ax, ay, az, wx, wy, wz, batt, rssi]})
            if(isCal):
                q = ao.getQ()
                aOrient = AbsOrient(
                    imu_read = read_list[-1],
                    q0 = q[0],q1 = q[1],
                    q2 = q[2],q3 = q[3]      
                )
                aOrient.save()
            ra = []
            cnt=0
vast rune
#

Ok I think it is async_to_sync

#

I am not using redis and It may be queuing my messages in a way i don't understand

vast rune
#

Ok i solved. I wasn't using Redis for my channel layer. Once i started using redis it is flying

stuck ginkgo
#

Hi Im testing some Scrapy commands for my project and although I've been looking for some contexts in which the command "fetch" can be used I still don't know if I should use this command and selenium (if I can even incorporate it to scrapy) on these approximately two hundred web pages to get all the necessary elements, click buttons and basically interact with JavaScript. I also had some questions, Im willing to listen if anyone knows something which you could consider useful:
Should I create a new Spider for every URL even if it's on the same webpage? Do I have to create a Spider for every webpage? Am I able to incorporate Selenium to my Scrapy project to click buttons? Is it the best option or the only one?

austere relic
#

bruh

stuck ginkgo
#

I need help with Scrapy bro... 😭

#

its not deep

scenic citrus
#

Here is my question, please help me

eternal blade
weary spear
#

Hey guys, do I need to setup a cookie consent if I didn't set any cookies on my website?

inland oak
weary spear
#

As far I've checked in 2 browsers - Chrome and Firefox, there's no cookies (In the developer options)

inland oak
#

it says no

#

but

#

Do we need to ask for usage of localStorage? 🤔

weary spear
#

Why everything is so complicated right now? lemon_angrysad

inland oak
# weary spear Why everything is so complicated right now? <:lemon_angrysad:817323592693841961>
The cookie law is not actually about cookies (and its not actually called the cookie law). Its about tracking users, storing and sharing the information with third parties. Cookies are just the most popular method to track users.

If you don't want to show the "cookie warning" then just don't track the users beyond the session and don't share traffic data with third parties.

https://softwareengineering.stackexchange.com/questions/290566/is-localstorage-under-the-cookie-law

#
If you don't use cookies at all then it would be a huge misinformation to warn your visitors about using cookies. It may even be useful to explicitly state that you don't use cookies. Remember that warnings about cookies are for people who want to avoid cookies so they should know when they finally get to a rare website that doesn't use them. But you may still need to warn about other things, like local storage. Just don't call it cookies if those are not cookies because it would be a misinformation that can even be against the law.
#
According to The EU Cookie Law website:

Is is just cookies?

No - The law also affects anything that acts like a cookie, for example:

Flash Cookies
HTML5 Local Storage
The ICO has said that it isn't good enough to just re-implement the tracking some other way outside of cookie storage.
#
This is just my interpretation, and could be wrong, but as i understand it, if you use local storage in a way that doesn't allow you to identify individual users, it doesn't apply, so for example using local storage to store user preferences wouldn't require notification, but using it to store a session id that then automatically gets sent back to the server would. – 
Jules
 Sep 2 '15 at 20:00
1
@Jules: You are correct. You can also use cookies without having to notify the user. It is not a question of any specific tracking method, but rather if you store the traffic data or share it with third parties. – 
JacquesB
 Sep 2 '15 at 20:41
tawdry chasm
#

Anyone know of any https proxy server libraries/examples that are relatively easy to setup, and has the functionality of switching a domain with another?

inland oak
#

or even better we can warn that we don't use cookies!

weary spear
#

Okay, so I will skip that part, will DM you once I will be fined by the GDPR guys 😛

inland oak
weary spear
simple phoenix
tranquil monolith
#

pls tell me the error in this code

summer beacon
tranquil monolith
#

Actually this the only python code. I can share my html page that is related this

#

@summer beacon

summer beacon
#

Yep, I see that. Can you share the full error message

rotund perch
#

Hello, are there hosting providers that charge fixed amount monthly instead of usage/hourly rate that is not fixed

rotund perch
hexed night
weary spear
#

My hosting provider has a default route domain.com/phpmyadmin - can I overwrite it with flask somehow?

@app.route('/phpmyadmin')
and then redirect to 404 is not working

manic frost
weary spear
inland oak
#

ridiculous. how about to change hosting provider 🙂

#

or finding if they provide VPSes to host stuff

weary spear
#

There's not many hosting providers in poland that are providing python hostings in decent prices

inland oak
#

it looks like it provides VPSes

inland oak
weary spear
#

around 1usd/month

inland oak
manic frost
#

I want to use Tailwind with Parcel. I searched for tutorials, and they all use PostCSS. I don't need PostCSS or any other preprocessor. What do I do?

#

oh wait, Tailwind uses PostCSS?

#

I forgot how deeply nested and convoluted JS stuff is

weary spear
inland oak
#

apache web server in python mod perhaps

#

scan your hosted app to find out

#

or better host in VPS

#

using hosting like that is perversion

weary spear
#

a standard cPanel hosting so most likely it's apache, but how can I check it?

inland oak
#

and just request HTTP headers

#

they have mentioned your web server

inland oak
#

Never heard of this technology

#

heh. 10% of web sites use it.

#

All right, at least it is popular

ornate radish
#

Who are learning about js

inland oak
ornate radish
#

I think it different for html /Css

warped aurora
#

when you populate a wtform with an obj it just does it sequentially?

haughty isle
warped aurora
haughty isle
#

why are you re-assigning form?

warped aurora
#

form = test_form(obj=table_data)

haughty isle
warped aurora
#

Ye it does, so my question was the order in which it populates the form fields is simply the order of the table data?

hard schooner
#

Hello guys I am new with cloud flare, I have recently added my domain in cloud flare, problem is with ssl, SLL is working on main domain properly but not with sub-domain www how can i add ssl on "www". My DNS record of www is targeted towards my site.

haughty isle
hard schooner
haughty isle
#

right you'll need to get a cert on the machine that's terminating TLS then

#

or proxy it through cloudflare

hard schooner
haughty isle
#

why not proxy www then?

hard schooner
haughty isle
#

does it work?

hard schooner
#

nope

haughty isle
#

how long was the DNS cache time?

hard schooner
haughty isle
#

there's a number next to every dns record

#

you have to wait that amount of time each time you change something

hard schooner
#

I think it is 1min because i have changed dns records recently and it only took 1 min to show effects.

haughty isle
#

ok so it works now?

hard schooner
#

nope

#

does creating a origin ssl certificate and adding in my hosting cpanel and turning off sll from cloud flare will help?

hard schooner
terse vapor
#

How can I delete the children object before delete the parent object in sqlalchemy?

rigid laurel
#

Hello - I realise I'm asking somewhat in vain, but does anyone have an example of a large Dash app architected somewhat well? I'm forced to use Dash for something that should really just be a traditional web app, and it's getting very messy - and I see no real clear path to organising things neatly

real sparrow
#

Im using fastAPI for my application's backend but have no experience building frontend user interfaces, What is the industry standard to create a UI that will make the calls to the API backend?

slender isle
#

The industry standard is JavaScript or TypeScript alongside a framework of some kind. The most common frameworks are probably: ReactJS, Angular (a bit outdated at this point), or Vue. Svelte is also growing quite quickly and seems very nice to use

near ridge
rigid laurel
#

yeah, one of them was pretty helpful

near ridge
#

Awesome

rigid laurel
#

although they also kinda confirmed my suspicion that there's no good way to do this thing that the framework isn't meant to do

near ridge
#

Sounds about right. So why are they binding your hands with this?

rigid laurel
#

so what happened was. My boss said "We need this thing". I said <thing> is easy, I could crack it out in a day. So I made it in literally 20m using Flask and HTMX, but I was too lazy to add any CSS. I showed it to him with no CSS - and his response was "yeah, that's pretty cool, it does what we need, but lets just do it in Dash because it's a lot easier to make things pretty in Dash"

#

and then <thing> has grown to have a lot more features tacked onto it, including a database and authorization business logic and all sorts that just belongs in Flask/or some other web framework

near ridge
#

Is what you do heavily data science related? I'm trying to figure out why he would insist on Dash

rigid laurel
#

moral of the story: always add styles before showing anything to anyone

near ridge
#

True

rigid laurel
#

yeah - I'm on a data science team, what I'm actually building is a SPARQL query console which makes data scientists lives easier

#

think like an SQL console in the browser, with things like syntax highlighting and downloading your results as CSV and other things that are helpful

near ridge
#

That's a really solid concept, I like it

scenic citrus
#

Please help me

#

How to do?

dense slate
#

looks like it has an accepted answer

scenic galleon
#

How can i display the text being typed in a input box lively on a label basically a onchange event but it should work when typing instead of when u take the focus of the input box

#

(ping if you reply)

real sparrow
autumn veldt
#

idk if its web dev but im still goin to ask : how can i get canvas image (like save it) in selenium

#

like save an image from canvas

slender isle
# real sparrow Awesome, thank you, Ill start looking into react and svelte. (should probably re...

NP - there's a lot to front end development. If your interactivity is somewhat limited, then you don't necessarily need a whole framework, you could just stick with some vanilla JS for updating small parts of your website - the whole idea of JS (whether vanilla or in the form of a framework) talking to a backend is called "AJAX", which really just means requests over the web which are JSON instead of HTML

golden bone
steady atlas
#

Anyone here have experience with Django / crispy-bootstrap 5.?
I'm trying to upgrade from BS3 (using django-crispy-forms) to BS5. Since crispy-forms only has templates for BS3 and BS4, that second library (crispy-bootstrap5) was created for BS5.
My issue is that even though I setup everything as the Github readme suggests, I still constantly get a template doesn't exist: bootstrap5/whole_uni_form.html error. Its like it is not seeing the crispy-bootstrap5 template pack.

terse vapor
#

Is there a way for me to delete child object before the parent object was being deleted in sqlalchemy?

wind lotus
#

ima start learning JS for webdev, any tips? (i alrdy know python)

frank shoal
#

use eslint.

#

First thing you should do in a new project. npm i eslint

random oar
#

how do you bypass a website that detects and blocks proxy users? mention me when you reply thanks

frank shoal
#

most websites have a denylist of proxy hosts. If the request comes from an IP known to be a proxy provider, it blocks it.

random oar
#

even though my proxy is an elite proxy, it will raise a semaphore timed out error

frank shoal
#

proxies typically pass the headers through.

#

Unless it's a reverse proxy

random oar
#

ill try using couple new proxies

frank shoal
#

You might need to use your own or get an obscure paid one.

random oar
#

with the old proxy it shows the remote computer refused to connect

#

i am using aiohttp to request btw

rotund perch
#

how do I restrict a URL that no one can access unless paid or checked out (Such as can not access a course except if paid for it)

serene prawn
rotund perch
serene prawn
#

So you probably need a schema like this if you want to have some additional data in your relationship between courses and users:

class User:
    id: int
    username: str

class Course:
    id: int
    title: str

class PaidCourse:
    user_id: int
    course_id: int
    paid_at: datetime
serene prawn
distant panther
#

scroll animations are possible with flask ?

#

:/

inland oak
distant panther
inland oak
distant panther
#

fade in and out animations are possible with flask?

inland oak
#

anyway, lets say yes, they are possible

distant panther
inland oak
native tide
#

any ideas on how i can make these look better? i've done the 'art' behind them but i just dont know what to do with the cards

#

wrong channel sorry

knotty robin
inland oak
# knotty robin I am too noob in web development but can someone actually tell me if there's a w...

sure. why not. ¯_(ツ)_/¯
https://www.youtube.com/watch?v=c6rP-YP4c5I

"Try Everything" from Disney's Zootopia
Performed by: Shakira
Download/stream/buy the Zootopia soundtrack here: https://smarturl.it/zssta1?iqid=dmvevo.shakira

Stream Zootopia now Disney+.

Disney+ is the ultimate streaming destination for entertainment from Disney, Pixar, Marvel, Star Wars, and National Geographic. Access it all at https://disn...

▶ Play video
#
  1. get domain, (point it at your IP address of the server)
  2. setup ssl certificates, (buy them or get for free from https://certbot.eff.org/)
  3. attach certificates to web server,
  4. ???
  5. PROFFIT!
plucky cape
#

I'm using flask and MySQL to make a website where the login page redirects you to a specific page depending on whether you are an admin of the page or not. for this I've made a specific admin field in the table, where if its value is "yes" then the login page should redirect to an admin page which has a few more things compared to a normal users page.

The problem arises with the sessions, and I'm not sure how I'm supposed to go ahead with trying to fix the code so that it redirects to 2 different pages.

this is for the normal login:-

@app.route('/login', methods=['GET', 'POST'])
def login():
    msg = ''
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
        username = request.form['username']
        password = request.form['password']
        adm = request.form['adm']
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM accounts WHERE username = %s AND password = %s AND adm= null', (username, password,adm,))
        account = cursor.fetchone()
        if account:
            session['loggedin'] = True
            session['id'] = account['id']
            session['username'] = account['username']
            return redirect(url_for('home'))
        else:
            msg = 'Incorrect username/password!'
    return render_template('login.html', msg=msg)
#

this is the admin login :```py
@app.route('/admin_login',methods=['GET','POST'])
def admin_login():
msg = ''
if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'adm' in request.form:
username1 = request.form['username']
password1 = request.form['password']
adm = request.form['adm']
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM accounts WHERE username = %s AND password = %s AND adm = yes', (username1, password1,adm,))
account2 = cursor.fetchone()
if account2:
if adm=="yes":
session['loggedin2'] = True
session['id'] = account2['id']
session['username'] = account2['username']
return redirect(url_for('adminhome'))
else:
return redirect(url_for('home'))
else:
msg = 'Incorrect username/password!'
return render_template('admin_login.html', msg=msg)

#

this is the error im getting with this code

#

what exactly is wrong here and how do i fix it?

knotty robin
#

Plus I wonder if namecheap already gives ssl certificates

inland oak
#

certificates from namecheap last only one year, so a bit pointless to buy certificates longer than that from namecheap

#

certbot reapplies itself infinity times for free every 3 months if I remember

knotty robin
inland oak
#

no idea. I did not use it with student rights

knotty robin
inland oak
#

read the docs about student program

knotty robin
inland oak
inland oak
knotty robin
inland oak
knotty robin
#

It asked for CSR when I tried to activate the certificate

inland oak
#

and then submit csr to namecheap to convert it to other certificate parts

#

then you combine received new certificate parts into proper certificates

#

and attach them to web server

vague yacht
knotty robin
inland oak
knotty robin
#

The domain is clearly linked to my account

#

But it still asks for it

plucky cape
inland oak
#

it is just easy to check method which is hard to mess up

#

that works quite fast to verify

#

I just rent VPS for small time for that, raising in docker nginx there and putting the asked files

#

and changing my domain to point to ip address of the VPS

vague yacht
knotty robin
inland oak
knotty robin
inland oak
#

Github auto gives you domain / https and certificates

knotty robin
inland oak
#

if you wish your other domain to lead to it, just make CNAME record, that leads to your github page

knotty robin
#

Idk if I am acting dumb rn cuz I really dk a shit bout this

inland oak
#

everything is secure

knotty robin
#

But I wanted my domain to point at my github page

inland oak
#

in that case you can resolve the issue by...

#

....hmm

knotty robin
inland oak
#

thinking

#

how well would work reverse proxy in this case

knotty robin
inland oak
#

not sure for sure

knotty robin
#

Man I am confused......

plucky cape
#

wait i fixed the error

#

but now, its not redirecting to anything at all

#

it just shows the login page

vague yacht
# plucky cape how do i fix that?

depends on what you want it to do
if you dont want it to enter the if at all, you can add and 'adm' in request.form: in the condition like in the admin login

if you want it to enter the if and want to give it a default value like False if 'adm' is missing, you can do request.form.get('adm', False)

plucky cape
#

should i put the second thing?

#
@app.route('/login', methods=['GET', 'POST'])
def login():
    msg = ''
    if request.method == 'POST' and 'username' in request.form and 'password' and 'adm' in request.form:
        username = request.form['username']
        password = request.form['password']
        adm = request.form['adm']
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM accounts WHERE username = %s AND password = %s AND adm= null', (username, password,adm,))
        account = cursor.fetchone()
        if account:
            session['loggedin'] = True
            session['id'] = account['id']
            session['username'] = account['username']
            return redirect(url_for('home'))
        else:
            msg = 'Incorrect username/password!'
    return render_template('login.html', msg=msg)
#

this is the current code

vague yacht
#

actually, why are you creating the adm variable here at all? you don't use it

plucky cape
#

its not required?

vague yacht
#

adm=null is constant in the query

plucky cape
#

i just wanted to make it null

vague yacht
#

yes, it is null in the query

plucky cape
#

if i dont enter it its null right?

vague yacht
#

('SELECT * FROM accounts WHERE username = %s AND password = %s AND adm=null', (username, password,adm,))

there's only two %s in the query (for the username and password) adm is not a variable, its always null

plucky cape
#

so if i remove it from both the cursor execute and the request form thing it should work as null right?

vague yacht
#

you need to keep the AND adm=null in the query as it is

#

you do not need the adm variable that you create

plucky cape
vague yacht
#

yeah

#

you can yeet the variable

plucky cape
#

hmmm

#
@app.route('/admin_login',methods=['GET','POST'])
def admin_login():
    msg = ''
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'adm' in request.form:
        username1 = request.form['username']
        password1 = request.form['password']
        adm1 = request.form['adm']
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM accounts WHERE username = %s AND password = %s AND adm = yes', (username1, password1,adm1,))
        account2 = cursor.fetchone()
        if account2:
            session['loggedin2'] = True
            session['id'] = account2['id']
            session['username'] = account2['username']
            return redirect(url_for('adminhome'))
        else:
            msg = 'Incorrect username/password!'
    return render_template('admin_login.html', msg=msg)
#

how do i fix the admin login now?

vague yacht
#

you get an error here?

plucky cape
#

no it just doesnt work 😭

vague yacht
#

i'm confused about what you're trying to do
specifically the adm variable

plucky cape
#

nono see

#

like in the site im making

#

there are 2 places you can get redirected to

#

one normal site, and one admin site

#

the admin site has access to some stuff that the normal one doesnt have

#

so when you register you have to manually change the adm value to assign the admin status to a user

#

what im trying to do with this

#

is try to make it so that if you login with an account which has the admin status

#

it redirects to the other site

#

and not the normal one

vague yacht
#

okay yeah i'm gonna have to step back now; this is beyond my webdev knowledge lol

plucky cape
#

do you know of an effective way to solve this issue?

#

ok now a new issue, even though i enter the right details into the login page, it doesnt redirect to the other thing and still just stays on the login page itself

#

adm is the one thats supposed to check that

#

char

#

yeah because thats the value ive assigned to it

#

not really

#

not anymore

#

its just redirecting me to the login page now

#

which im already on?

#

where would i print it

#

in the terminal or on the site?

#

gimme a sec

#

wait its not printing

#

wdym?

#

how do i fix that

#

this is what i get

#

still shows the same error

#

which one?

#
import mysql.connector

mycon=mysql.connector.connect(host='localhost',user='root',database='project',password='--------')

cur=mycon.cursor()
cur.execute('SELECT * FROM accounts WHERE username = %s AND password = %s AND adm =`yes` ')
data = cur.fetchone()
print(data)
#

uhuh

#

OH

#

so i just have to remove them for now right?

#
import mysql.connector

mycon=mysql.connector.connect(host='localhost',user='root',database='project',password='password')

cur=mycon.cursor()
cur.execute('SELECT * FROM accounts WHERE username = `hi` AND password = `hu` AND adm =`yes` ')
data = cur.fetchone()
print(data)
#

does it have to do with the version of mysql im using?

#

yeah this is working

#

instead of single quotes?

#

lemme test that gimme a sec

#

this is what i get on the website

#

and this on terminal

#

i did

scenic galleon
#

i made a code seperaly and merged (copy pasted) the html js and scripts with the other main file now i get

Uncaught TypeError: Cannot read properties of null (reading 'find')

The code (this is the line console is pointing)

 var confirmBox = $("#confirm"); //this is triggered by a onclient event of a button
 confirmBox.find(".message").text(msg);

#confirm is

<div id="confirm">
      <div class="message"></div>
      <input type="text" id="link_url" class="link_url" readonly/>
      <div class="buttons_popup_share">
        <button class="copy">Copy</button>
        <button class="share">Share!</button>
      </div>
</div>

remember it works separately in another file without the other code for the main site (i have the same jquery for both files (http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js))

#

ping if you reply

plucky cape
#

should i remove the admin login thing and just try doing it from the login page?

#

or will that make it more complicated

#

wdym?

#

how would i alter the code

#

something like if adm == 'yes' redirect to admin if not redirect to normal?

#

it works

#

yeah that is what i want

#

wait no

#

i want it so that the admin can do normal stuff + admin stuff

#

which is there on my page

#

gimme a sec

#

now just try and run it?

#

wait the form doesnt take any input

#

for admin

#

you have to manually change it in the database

#

hmmmmmm

#

it still is just making it stay on the log in page

#

but oh well its printing the thing now

#

but its still showing incorrect password rn

#

for some reason

#

so remove the request form and then in the last line where im taking the adm1 thing?

#

username1 and password1 arent defined in this one

#

oh this is the for the admin login thing?

#

nope, its still saying incorrect

manic crane
#

anyone using DRF know how to fix this ? {
"detail": "Token is expired, login again"
}

plucky cape
#

aaaaaaaa

#

wait after the request.form thing?

#

its not being printed

#

what exactly is wrong with the form?

#
@app.route('/register', methods=['POST','GET'])
def register():
    # Output message if something goes wrong...
    msg = ''
    # Check if "username", "password" and "email" POST requests exist (user submitted form)
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'email' and 'adm' in request.form:
        # Create variables for easy access
        username = request.form['username']
        password = request.form['password']
        email = request.form['email']
        adm = request.form['adm']
                # Check if account exists using MySQL
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM accounts WHERE username = %s', (username,))
        account = cursor.fetchone()
        # If account exists show error and validation checks
        if account:
            msg = 'Account already exists!'
        elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
            msg = 'Invalid email address!'
        elif not re.match(r'[A-Za-z0-9]+', username):
            msg = 'Username must contain only characters and numbers!'
        elif not username or not password or not email:
            msg = 'Please fill out the form!'
        else:
            # Account doesnt exists and the form data is valid, now insert new account into accounts table
            cursor.execute('INSERT INTO accounts VALUES (NULL, %s, %s, %s, NULL)', (username, password, email,adm))
            mysql.connection.commit()
            msg = 'You have successfully registered!'
    elif request.method == 'POST':
        # Form is empty... (no POST data)
        msg = 'Please fill out the form!'
    # Show registration form with message (if any)
    return render_template('register.html')
#

this is my register code

#

if thats whats causing any problem

#

bur why wouldnt it fetch?

#
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Login</title>
        <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
        <style>
            body{
                background-image: url(static/car2.jpg);
                background-position: center;
                background-size: cover;
            }
        </style>
    </head>
    <body>
        <div class="login">
            <h1>Login</h1>
            <div class="links">
                <a href="{{ url_for('login') }}">Login</a>
                <a href="{{ url_for('register')}}">Register</a>
                <a href="{{ url_for('admin_login')}}" class="active">login as admin</a>
            </div>
            <form action="{{ url_for('login') }}" method="post">
                <label for="username">
                    <i class="fas fa-user"></i>
                </label>
                <input type="text" name="username" placeholder="Username" id="username" required>
                <label for="username">
                    <i class="fas fa-lock"></i>
                </label>
                <input type="password" name="password" placeholder="password" id="password" required>
                <div class="msg">{{ msg }}</div>
                <input type="submit" value="Login">
            </form>
        </div>
    </body>
</html>


#

if req is post

#

okay one sec

#

yeah i did it

#

one sec