#web-development
2 messages · Page 208 of 1
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
Yeah in kivy ages ago
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?
app = Flask(name)
where "name" is the name of the file?
Nope
it's __name__
Thats it? Damn
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?
where are you using the User component
i dont actually have a user component
this is what im trying to do
go from userlist component to a single user view
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
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
that function returns html right? or jsx etc, whatever you want to call it
.
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
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
can you reexplain if you dont mind, i think i missed something
what are you trying to achieve exactly?
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
yep , if i type the id into the address bar it gets the correct record
nice, seeing if there is any out there I could learn from
right, so are you using axios by chance? or just fetch
axios i believe, but im frankensteining the code as im trying to learn js
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
yeah exactly
then you can use axios to fetch the data from the id property
react router has a useparams constructor or function i believe
do you have an example? the tutorial i was following used href={'/userlist/' + user.id}>
yeah that works i guess
my code doesnt reach my useParams()
which react-router version are you using? 5?
i believe so
^^^
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?
you can check in package.json to verify
"react-router-dom": "^5.3.0",
ok, gimme a sec
@thorn igloo Could you please comment what I wrote above?
just push to your repo, and link the repo to heroku
it will automatically detect your updates
ok, so i just made this showing how to use useParams
so you can apply that to your application i guess
what does your procfile look like
web: gunicorn PhotoMathBackend:PhotoMathBackend
what's the name of this file?
no, they can be anywhere you want
i just like putting them in app
it's just a personal preference
has nothing to do with anything
@thorn igloo Do you know why I get error?
@thorn igloo Did I connect my GitHub repo and Heroku with this line
idk man
i use the gui on the website to connect
if you're gonna use the cli, i can't help you there
So all you did is use gui on website to connect and any change in your GitHub repo is automatically detected to Heroku?
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
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
can't say much about your app since i don't have the source code
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
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?
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
ok will do!
thanks for the help man
sure
Weird, in my local version it works without importing it
@thorn igloo I imported Flask, so there should bee request
@thorn igloo so does pip freeze detect libraries that I use in virtual envionment, libaries that I imported?
how can i display my images in my folder without having to place them in static?
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?
those are depencies for flask
and possibly gunicorn
dependencies
it installs those at the same time because flask needs them
ah I see - how so that I didn't have to install them locally?
or it was done in background?
it was done when you did pip install flask
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?
CURL is a great tool for making requests to servers; especially, I feel it is great to use for testing APIs.
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.
or actually just write small python script
that uses library requests to do that
and launch it with python3 scrip_name.py
I'm sorry but, why flask? Why not something like aiohttp or starlette?
I also recommend to try httpx instead of cURL.
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 ?
you can make an api call wherever you need it. no need to call it in index if you don't need it there
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
hello, does app.route just give you a page(that has been specified)?
for flask
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()
I want to increment a value set in Jinja2
{% counter = 0 %}
how can I do this outside a loop?
increment your values in the backend
I can't do that, I need to increment it in the front-end
oh... I figured out why it's not working
Are you sure ?
I spent a long time trying to work this stuff into jinja , a lot of the time figured it out , but then realised it can be done backend easier most of the time
after I figured out why it wasn't working I also realized there's a simpler solution in the backend 🙂
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?
you can use tokens or sessions
react is just a frontend tool
React is compiled into pure html/CSS/js and served to each client.
Frontend exists purely at client side in user browser.
If it is not using some SSRing with node.js serving
React connects to my API then react is the one communicating with my server right? How can i send sessions from the client?
if you look into flask sessions (i'm assuming it's what you're using), you'll realize that it basically sets a cookie in the browser that's sent with every request you make to the backend (provided the cookie is already created)
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
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 ??
Okay thanks!
Hello, what is Django queues? and what is it used for?
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"
}]
OMG Heroku doesn't work
yeah I think it's down right now
[
{
"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)
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
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?
Isn't tower an object? So tower.tower_id
I don't know that much about JSON but I think [] is a JSON Object and {} JSON Dictionary
JSON deserializes into a python dict
So it looks like you're creating a python dict from a JSON string
i put in an id and it returns:
which is correct but the issue is i made a file for every single tower/monkey
It made all those files but you wanted to only create one?
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
So is this your error?
TypeError: list indices must be integers or slices, not str
yes
So how did you get the proper return if that error pops up.
i changed the json into only {}
but that's only for testing right now but im looking for another solution
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
Your json should return something in {}'s
unless it is a list of objects
then it can be [{}, {}, {}, etc.]
actually even then I think JSON needs to return {}'s.. but anyways
where are pip (Pypi) packages are stored in Django?
Example 1:
Example 2:
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.
But the problem is i have tons of json files in one directory and how is my code supposed to know which one of them to return
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?
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.
Probably didn't install Django, like it says?
Or you didn't run inside of an active virtualenv if you are using one (which you should be).
They are stored in the python site-packages folder
Thank you
do i need to add this to PATH right?
\AppData\Roaming\Python\Python39\Scripts'
Uh, for what?
Only thing I ever added to PATH was python.
oh its already working hahah i got error the its not on path
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
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))```~~
Fixed
.topic
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> ';
}
?>```
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?
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']
please answer this question https://stackoverflow.com/q/70458483/17549908
oh man, pycharm added fastAPI boilerplate option when creating a project. Is this a sign to learn it?!
Anyone can suggest me Django best book to learn in depth?
Willian S. Vincent has three up to date for Django 3.2 books
Django for beginners
Django for professionals
Django for APIs
I did not read them, but I was eyeing them as the best source of going through django
Probably I should ready them already too
So where to start? Is it sorted list of 3?
The look like this, except 3.2 is written
Obviously from beginner one. Not sure which one to read as second
the book about APIs tells about REST APIs
Okay, I will decide it let me finish the first one first.
https://overiq.com/flask-101/ this is such a good flask tutorial
@warped aurora I want to directly begin with django. Is there any problem if I begin with django ?
No that's fine
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?
Show us your code repo? Where and how exactly are you running it?
public_html -> index.py
index.py returns a template
from
template/index.html
it all linked perfectly in localhost
so i just uploaded the files
but online i get a 403 error
If your host is setup for static files, uploading Python there isn't going to work.
seriously?
i reserved hosting and a domain
how else do i get my flask application online
Hosting where?
godaddy
See if this helps: https://kanishkvarshney.medium.com/hosting-your-flask-web-application-on-godaddy-5628a60e7151
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.
whats the difference between
and calling Usres() constructors directly in django
while adding users to the db
Please don't advertise here
Not sure about the implications of that flag specifically, but here's a nice little article about how some vulnerabilities in Flask work: https://blog.nvisium.com/injecting-flask
We’ve taken a look at some of the features provided in Flask for output escaping, the potential issues, and the fixes available should you come across some vulnerable code.
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?
Hello everyone, can i use slack for messaging on my website? for group chat?
Did you set up the worker file for your server?
Which one will take the lead to dive into (Flask or Django)?
depends on what you want to dive for 🙂
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
Yeah I was able to inject into the static files on my flask development server for another website, but I was wondering about django
You want to message through your website?
You could always tie it into a discord webhook 
Ah, my bad. Have you seen this? https://stackoverflow.com/questions/31097333/why-is-serving-static-files-insecure
{% for field in form %}
{{ field.label }}
{{ field }}
How would make this loop only over the 1st two fields?
Assuming I understand the question, call form[0] and form[1] directly instead of using a for loop
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)
What if i wanted to loop over 30 out of 40 fields, instead of calling them directly
That's a little more complicated but I think I would use enumerate with an if statement
And still use a for loop
Is this Django? try {{ company|slice:'4:7' }}
^^^ Better idea
Best way I've found for searching these is "django template <thing you'd do in python"
so I did "django template slice"
oh shit jinja takes python statements
flask
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
Cool i'll check it out thx
hello
I’ve used both and I suggest django , I prefer the workflow
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"}]}
this is my first time web scraping, and I don't know how to log in using Beautifulsoup4
Help pls
Http 422 unprocessable entity
I don’t know much about beautiful soup, but I suspect you don’t log in with it, rather you log in with the module responsible for the http request
Mindful of rule 5 though, I will assume you're not trying to break ToS
Where do I learn web developement using python??
can anyone point me in the right direction to receive webhooks with django
whats this error
You try to save user that doesn't belong to User model
Is django slow?
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?
interval
can anyone point me to a discord server where I can ask questions relating to GIT repositories?
JavaScript is the answer
It can change DOM/page values without making requests
Not sure if the next discord is a good use case for django :)
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.
Just ask, don't ask to ask
Not if you're doing it right. I've seen that Instagram and a lot of other major web apps run on Django
#tools-and-devops is a good place to start
Peace Be Upon All Of You Guys
can I ask HTML questions here lmao
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 ? 😄
Just ask, don't ask to ask
short answer yes
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
Already asked stack lmao
how do you suggest I should host the microservice?
I have been looking into lightsail EC2 and other stuff but not entirely sure about either'
what is your microservice containing
are you working in company or making it as pet project for yourself
what are other components existing in your architecture
basically, if you wish to answer the questions on your own, it would be not bad to learn a bit of System Analysis and Design
If you wish to have a simple answer...
Then just get Lightsail VPS for starting
Or actually I have even better answer...
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 🤔
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
just try to make something and look things up along the way
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.
gunicorn?
Run gunicorn and bind to a port, say 8080, then have apache reverse proxy traffic to the gunicorn worker running on 8080
Have not thought about gunicorn, thanks
supports FreeBSD which is good
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
figma for design, flask for backend, css/html for frontend
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.
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
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
why do people make these stack abbreviations 👀
my favourite one is the NOBODY EXPECTS THE SPANISH INQUISITION one
throwback to when LAMP ruled the web, maybe?
Node.js + ODBC + BSON + OWASP + DynamoDB + YAML + Erlang + XML + Puppeteer + Ecto + Cassandra + TypeScript + Semver + Teal + Haskell + ElasticSearch + Spring + PureScript + Angular + Nim + Idris + SQLite + Hack + IPC + Nginx + QBASIC + UML + IntelliJ + Scala + IELTS + Torrent + Isort + OpenSSL + NoSQL
think LAMP still runs the net, even substituting the PHP for Python
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
Yea. It takes a bit of getting used to.
I have a question involving flask, and a website im making would that fit in here?
or would that be a different channel
yes, this one
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
Do you have your route allowing "GET" and "POST"
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
Here is an example, if the request is POST, under else: handles it
never mind i think i fixed it lol but thanks
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.
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
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
CSS?
yes
something like this? https://www.w3schools.com/howto/howto_css_aspect_ratio.asp
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
turns out Hey worked good for load testing webapps https://github.com/rakyll/hey
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...
i am planning to create simple website using django
is my erd on the right track?
a user can post and comment on posts
how do services like auth0 and nextauth check for vulnerabilities?
this seems fine
on the react and likes feat where do i put em? on comments?
id personally have a independent PostLike model for posts and have a user_id and post_id associated with it
do they need own tables? to show who liked or reacted?
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)
i added 2 tables yeah maybe it will look like this?
yup seems about right. make sure to associate each of those table in your User model
nice nice thank you sir 🥳 👍
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
PostLike doesn't need it's own id though 
You could use composite primary key, you wouldn't need an id and it would also provide uniqueness check
Yup you're right. It was from one of my older projects and didn't really think about it much.
thanks, that's pretty much what i was guessing. I suppose I'll use it temporarily then because i'm on a tight deadline and rewriting code does not sound fun nor quick
dont think ive worked with many relational data since then
but i'll rewrite it after we release
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
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
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
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
Not sure if there's a full and ready tutorial out there but I would say you should learn a bit of Flask if you haven't yet. There's apparently a library for using it with web3 https://flask-web3.readthedocs.io/en/stable/guide.html
thanks man
Is it possible to get the name of the WSGI server in a Python script?
got it doing the system hostname already, I meant for it to print "Gunicorn" or "Werkzeug".
Does anyone have idea about hosting a Flask Socket Chat Room to Heroku
that worked, thanks
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"])```
yo is django manytomany and onetomany like joins?
Does anyone know of a good place online that I could use for programming a webpage?
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?
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
oh my, I totally forgot about networking 😄 ty, Mark
You're welcome
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
I have a question regarding fastAPI if anyone wants to take a crack at it? over in #help-mushroom
@real sparrow it's called the "closure gotcha" https://docs.python-guide.org/writing/gotchas/#late-binding-closures
@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
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"])```
Set Server name from os environ value
import is
os.environ.get('server_name','domain.com')
U will be able to override the env value for your Dev machine
python dotenv package will make it easy by allowing to write them in .env file
Or set Dev values as defaults. And override them to necessary values in prod
so I'd be able to still make a local request but with my domain name instead?
I want my bot to be able to locally request to webserver
without going through cloudflare unreasonably
U will need to run local instance for Dev purposes
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
sadge
As a different option, just don't restrict server name
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
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
What do u mean here
Write example of the desired end result
Anyway... I think everything u wish to achieve can be achieved at the level of nginx
I think it should be able to listen to multiple domains and having different targets for each one
I would attach to shell inside the container and see if your files are in the right location. I'm guessing enhance.py is missing or in the wrong place. Share your repo if you're still stuck
do you mind if I private message you the repo?
I did run the shell of the docker image and enhance.py is in the project
Sure, I probably can't look tonight but I'll look when I can
of course, thank you for agreeing to help me
I see
what's the problem bro
nothing, you asked me to see how you used the precode, neat
why background is white not dark
I suppose you're supposed to set it to a color
and not a theme
hold on
background: #your color hex code here
;
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?
update itself how?
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
How can i scrap web site without blocked please (couldflare)
you can use javascript
with like the setInterval function you can regularly update
!rule 5 we're not going to help you bypass protection
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
from application import init_app
i have trouble installing this 'application'
it says that it did not find mysql_config
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 ?
i think html and css is needed
I was hoping it is not but yeah that's understandable hrh
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 ❤️
hi
just here wanted to ask something
what do you prefer the most
flask vs django
how do i integrate javascript?
pls reply
make a <script src="{% static 'app/index.mjs'%}" type="module"></script>
.mjs
and depends on the name of your app
are you using django?
yes
yeah so you put it in app/static/app/index.mjs
or whatever you called your app?
cool
is it working?
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?
so you'd give the element you want to update an id
this is quite new to me - what is the syntax to do this?
Responsiveness (button events and such on the front-end)
if you !paste your template I can help
Client stuff like changing text according to the current time should be easy to do with JavaScript
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.
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?
?
{% 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>
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 {};
I don't see <h1 id="is-new-year">{{ newyear|yesno:"YES,NO" }}</h1> in your code?
you can add the code for updating now.innerText ?
ill try it
Did it work?
Show your html?
{% 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>
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?
hey um, quick question. do i need to locally host a web server in order for flask to run
How do you log stuff with uvicorn? The "simple way" with logger = logging.getLogger(__name__) and then logger.info("something") just... does absolutely nothing
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?
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
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',
]
}
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'.
...
flask, because it fits my needs, idk havent used django
some people answer: fastapi, but I chose django. But going to try... later... eventually... fastapi
Is it possible to get users who connect to the socket on flask?
fastapi is nice, all async and stuff. but I also really like sqlalchemy, and sqlalchemies async support, while present, is still kinda meh.
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
I think that's browser dependent, but try to set a placeholder text?
doesn't seem to work
then I got no idea. it's probably not possible because browsers 
Lol
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 ...
hmm
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
Gonna try the js datepicker
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
Show the rest of your code?
Also what web server are you using?
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
I use the one django comes with on this cpu
Ah you'll need uvicorn or Daphne or hypercorn to run async code efficiently
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
What's cacheTouch?
Don't use threads like that with asyncio, use await asyncio.to_thread(sync_fn)
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
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
cache.get does blocking IO?
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
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
Ok i solved. I wasn't using Redis for my channel layer. Once i started using redis it is flying
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?
bruh
I have first made category crud, and then product crud with many-to-many relation with category.
models.py (category):
class Category(models.Model):
name = models.CharField(max_length=191, blank=
Here is my question, please help me
Hello,
https://stackoverflow.com/questions/70375371/channel-layer-send-not-calling-event-handler
Please check my question, Thanks
Hey guys, do I need to setup a cookie consent if I didn't set any cookies on my website?
good question. I would like to have an answer for that too. I am in the same position 😆
As far I've checked in 2 browsers - Chrome and Firefox, there's no cookies (In the developer options)
it says no
but
Do we need to ask for usage of localStorage? 🤔
Why everything is so complicated right now? 
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
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?
I think as long as we don't keep User ID in cookies or local storage, or any other way to idenfity the user machine, we can avoid warning about cookies
or even better we can warn that we don't use cookies!
Okay, so I will skip that part, will DM you once I will be fined by the GDPR guys 😛
lets test who would be earlier fined then ;b
Deal!
Yeah interesting but it is necessary since cookies arent the only means of tracking. Unfortunate thou they should have called it online data privacy law . Lawyers there at least covered all bases but stuck with cookie lol
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
pls tell me the error in this code
I think it might be to do with your writing to database with content object, can we see the full error code?
Actually this the only python code. I can share my html page that is related this
@summer beacon
Yep, I see that. Can you share the full error message
Hello, are there hosting providers that charge fixed amount monthly instead of usage/hourly rate that is not fixed
have you tried BlueHost?
Nope, does it charge fixed amounts?
well the fix amount could increase if you reach a certain limit. you can check this out https://www.bluehost.com/hosting/shared#pricing-cards
View shared web hosting plans from Bluehost. Our Basic, Plus & Choice Plus plans are fast, reliable & secure to get sites off the ground fast!
Thanks
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
What hosting provider is that? It shouldn't be like that. Ideally they should just provide you with a blank VPS and don't touch it, and don't install anything on it
cyberfolks.pl - technical support told me it's not possible to change that and all I can do is just have a strong password...
ridiculous. how about to change hosting provider 🙂
or finding if they provide VPSes to host stuff
There's not many hosting providers in poland that are providing python hostings in decent prices
it looks like it provides VPSes
what's your current hosting price in dollars?
around 1usd/month
it would be hard to beat this price
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
but there's no way to overwrite this redirection in python or maybe .htaccess?
i have no idea in which way your applicaiton is hosted
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
a standard cPanel hosting so most likely it's apache, but how can I check it?
find any tool or online service to check headers of your web site
and just request HTTP headers
they have mentioned your web server
LiteSpeed
LiteSpeed Web Server (LSWS), is a proprietary web server software. It is the 4th most popular web server, estimated to be used by 10% of websites as of July 2021. LSWS is developed by privately held LiteSpeed Technologies. The software uses the same configuration format as Apache HTTP Server and is compatible with most Apache features. An open s...
Never heard of this technology
heh. 10% of web sites use it.
All right, at least it is popular
Who are learning about js
a bit briefly using it and learning in the process ;b
I think it different for html /Css
when you populate a wtform with an obj it just does it sequentially?
what do you mean by that?
if i do form = form(obj=model).. the form fields are just populated in the order the columns for the table are?
which table?
why are you re-assigning form?
I'm pre populating the form data from a table
form = test_form(obj=table_data)
does it work?
Ye it does, so my question was the order in which it populates the form fields is simply the order of the table data?
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.
the order of which fields?
are you not proxying www through cloudflare?
yes
right you'll need to get a cert on the machine that's terminating TLS then
or proxy it through cloudflare
I have proxied every record using cloud flare
why not proxy www then?
including www, changed recently to check if it workds
does it work?
nope
how long was the DNS cache time?
??
there's a number next to every dns record
you have to wait that amount of time each time you change something
I think it is 1min because i have changed dns records recently and it only took 1 min to show effects.
ok so it works now?
nope
does creating a origin ssl certificate and adding in my hosting cpanel and turning off sll from cloud flare will help?
?
How can I delete the children object before delete the parent object in sqlalchemy?
show your code?
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
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?
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
Did the example ones I found help?
yeah, one of them was pretty helpful
Awesome
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
Sounds about right. So why are they binding your hands with this?
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
Is what you do heavily data science related? I'm trying to figure out why he would insist on Dash
moral of the story: always add styles before showing anything to anyone
True
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
That's a really solid concept, I like it
I have first made category crud, and then product crud with many-to-many relation with category.
models.py (category):
class Category(models.Model):
name = models.CharField(max_length=191, blank=
Please help me
How to do?
looks like it has an accepted answer
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)
Awesome, thank you, Ill start looking into react and svelte. (should probably read up on javascript a bit as well lol)
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
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
Did you Google it? Multiple relevant answers on StackExchange come right up for me. Try those and see if you encounter a specific problem
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.
Is there a way for me to delete child object before the parent object was being deleted in sqlalchemy?
ima start learning JS for webdev, any tips? (i alrdy know python)
how do you bypass a website that detects and blocks proxy users? mention me when you reply thanks
Use a different proxy.
most websites have a denylist of proxy hosts. If the request comes from an IP known to be a proxy provider, it blocks it.
i thought it checks the header
even though my proxy is an elite proxy, it will raise a semaphore timed out error
ill try using couple new proxies
You might need to use your own or get an obscure paid one.
I used another proxy server, it works for other low security websites, but for this website it now shows a different error message='invalid constant string', url=URL('http://119.190.187.194:8060') seems like its working but not completely
with the old proxy it shows the remote computer refused to connect
i am using aiohttp to request btw
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)
What framework you're using?
You're probably looking for attribute based access control (abac)
As a simple example - imagine you have a User and Post
@dataclasses.dataclass
class User:
id: int
username: str
@dataclasses.dataclass
class Post:
id: int
user_id: int
title: str
All users might have read rights to posts, but only user with user.id == post.user_id would be able to modify it.
I am using Django, but what I understood from u is I can make for example a boolean of (paid =False) in the user field and whenever its checked out make the boolean True and any one with the (paid = True) can access the URL is that right?
You'd need a "secondary" table that would create a many-to-many relationship between users and courses, this can be done using many-to-many relationship
https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_many/
If you need to store information about paid course e.g. when user paid for the course, price at the time, e t.c. you'd need to create that table yourself
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
oh okay. Thanks!
And making simple boolean flag on user model won't work - you need to distinguish between paid and not paid courses for a specific user
Yes, I got that
depends on what is your definition of scroll animation
the fade in and fade out animations
when they are supposed to start and end
fade in and out animations are possible with flask?
when they are supposed to be triggered for start and end.
anyway, lets say yes, they are possible
how i can make them with python flask ?
I could recommend this book as an answer
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
I am too noob in web development but can someone actually tell me if there's a way I can convert my website to a secured connection on https://nc.me/
The Namecheap Education Program offers a free domain and website to university students worldwide.
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...
- get domain, (point it at your IP address of the server)
- setup ssl certificates, (buy them or get for free from https://certbot.eff.org/)
- attach certificates to web server,
- ???
- PROFFIT!
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?
3rd how??
Plus I wonder if namecheap already gives ssl certificates
i use namecheap and can say that it offers them for a price
https://www.namecheap.com/security/ssl-certificates/
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
Uhh I have github student plan if that changed anything
no idea. I did not use it with student rights
How can I check if I got the certificate??
open your client area and go to SSL Certificates section
read the docs about student program
Ah alr lemme see
check if you can buy certs for free when your student account is opened
Guess I have it
👍
But how to use it broo??
try and see in your client area
Nvm what is CSR??
It asked for CSR when I tried to activate the certificate
I don't remember how it is pronounced
but you generate with openssl tool key and csr
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
in the normal login, you try to access request.form['adm'] but the 'adm' key doesn't seem to exist in request.form
How do I compete the DCV method....
the process of verificating domain?
Yeah....
The domain is clearly linked to my account
But it still asks for it
but in the table the adm thing does exist?
I find the easiest way to verify through hosting the file at web server
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
the db is not relevant here, request is the incoming request from the client and request.form is missing the key
how do i fix that?
My webpage is hosted at GitHub pages
then why the hell do you need certificates
Idk....
Github auto gives you domain / https and certificates
NameCheap just shows insecure website
if you wish your other domain to lead to it, just make CNAME record, that leads to your github page
My CNAME record already leads to my github page
Idk if I am acting dumb rn cuz I really dk a shit bout this
https://dd84ai.github.io/darkbot/
I have github pages web site, it works splendidly
everything is secure
Same with me
But I wanted my domain to point at my github page
perhaps certificate should include source domain as well 🤔
in that case you can resolve the issue by...
....hmm
By?
What do I think?
not sure for sure
Man I am confused......
wait i fixed the error
but now, its not redirecting to anything at all
it just shows the login page
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)
for the normal login, the adm value is supposed to be null because the adm thing is supposed to let them open the other site
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
actually, why are you creating the adm variable here at all? you don't use it
its not required?
adm=null is constant in the query
i just wanted to make it null
yes, it is null in the query
if i dont enter it its null right?
('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
so if i remove it from both the cursor execute and the request form thing it should work as null right?
you need to keep the AND adm=null in the query as it is
you do not need the adm variable that you create
that i hav kept
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?
you get an error here?
no it just doesnt work 😭
i'm confused about what you're trying to do
specifically the adm variable
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
okay yeah i'm gonna have to step back now; this is beyond my webdev knowledge lol
thanks for trying tho lmao
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?
hmm
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
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
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
anyone using DRF know how to fix this ? {
"detail": "Token is expired, login again"
}
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