#web-development
2 messages Β· Page 146 of 1
the rest of the css seems to load just fine
it still doesn't work with btw :
body {
background-image: url('../static/img/bg.jpg');
}
is that exactly what you're writing?
is /static coming off the root domain?
maybe you just want
background-image: url('/static/img/bg.jpg');
? @karmic flare
Has anyone ever tried to do webscraping the twitter website. I keep getting this as HTML response:
<p>We've detected that JavaScript is disabled in this browser. Please enable JavaScript or switch to a supported browser.</p>
As others have suggested me, I also tried using Puppeteer. But this gave the same error :(. This is the code I used:
const puppeteer = require('puppeteer');
(async () => {
let twitterUrl = 'https://twitter.com/home';
let browser = await puppeteer.launch();
let page = await browser.newPage();
await page.setJavaScriptEnabled(true);
await page.goto(twitterUrl, {waitUntil: 'domcontentloaded'});
let bodyHTML = await page.evaluate(() => document.body.innerHTML);
console.log(bodyHTML);
await browser.close();
})();```
Or is it simply impossible because Twitter blocks web scraping so they don't overload their servers? Has anyone ever had this problem?
I also know the code above is not Python but Javascript but scraping twitter with python gave me the same error.
Don't know what I did but it seems to be working now π thanks !
ahh
im calling an api to refresh an access token, but it does it everytime the component is rendered
useEffect's second argument tells it when to run. You often do not want them running at the same time
the empty list tells it to run on mount and then never again
unless it gets remounted
basically
if it gets removed from the page and the put back on the page, it will run again
ahh i see
if i pass in a state in the dependency list, it will only run when the state changes?
yes
got it, thanks
π
Guys do youu know where can i ask for bs4 help
#βο½how-to-get-help claim a channel
anyone could help me with selenium.common.exceptions.ElementClickInterceptedException: ?
i send values to email input then send click on submit but when i try to send click on submit again it gives me selenium.common.exceptions.ElementClickInterceptedException:
here whati have tried
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Trying to migrate
getting psycopg2.errors.StringDataRightTruncation: value too long for type character varying(18)
that's a JS job, you should look into jquery
I'm looking for some advice here. I want to create a website that will link blog stories that can be commented on as well as have a twitter feed. Django/sqlite/react seems like the backend/db/frontend I want to do
But I'm super new to web frameworks so, any advice would be great.
Is there a "best" or recommended oauth2 library? (client)
actually, I'm using aiohttp already, so I suppose I should just use aiohttp-oauth2
Like for example I want to have 3 pages but I want different background for different pages
You can have different css templates for each page.
Ya if I thought of that π€ but I want to render the page dynamically
So will I have to use any other method
Like we do int:pk/ thing
Just keeping the format same and render different data
So by that I will be having only 1 html file and by templating I will be filling data , so is there any way to change background also like that @stable hemlock
You could feed the css url as a variable. @icy drift
hi guuys, can I make a landing page in react, build it into html,css,js and display that as a template in a django app ?
Only asking this for a single page and not the whole project.
@ashen sparrow I believe your react app is intended to be standalone, it runs independently of your back-end. In this case, I believe it's recommended to only serve data/json through your backend. So. basically you'd make an API for your react app
Why does this always say "invalid CREDENTIALS"
def customer_login(request):
if request.method == "POST":
email = request.POST['email']
password = request.POST['password']
user =authenticate(email=email, password=password)
if user is not None:
return redirect('homepage.html')
else:
messages.info(request, "INVALID CREDENTIALS")
return redirect('/customer_login.html')
else:
return render(request, 'customer_login.html')```
class customer(AbstractBaseUser):
firstname = models.CharField(max_length=30)
middlename = models.CharField(max_length=30)
lastname = models.CharField(max_length=30)
# email= models.emailField()
email = models.EmailField('email address', unique=True, db_index=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
USERNAME_FIELD='email'```
hey is it possible to control a python script running on a vps using a website based on php backend
i really wanna know
take screenshots and not pictures of your monitor
Can you help me
for i in range(X_FUTURE):
curr_date = curr_date + relativedelta(months=+1)
dicts.append({'Predictions': transform[i], "Month": curr_date})
new_data = pd.DataFrame(dicts).set_index("Month")
##df_predict = pd.DataFrame(transform, columns=["predicted value"])
new_data.to_csv(os.path.join("downloads", index = True, encoding='utf8'))
labels = [d['Month'] for d in dicts]
values = [d['Predictions'] for d in dicts]
colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
"#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
"#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]
line_labels=labels
line_values=values
return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values, filename = filename)
@app.route('/download/<filename>')
def download(filename):
return send_from_directory("downloads", filename, as_attachment = True)
<a href="{{ url_for('download', filename=filename) }}">Download</a>
Hi community, I m trying to save my to_csv into os.path.join and return the csv file from download button in HTML page, currently I m getting this error TypeError: join() got an unexpected keyword argument 'index', Does anyone excel in flask python, please correct me ~ Appreciate
How much can a Django application weigh - the basic one created in django admin without changes?
You don't do that through django admin but through django cli + why do you want to know that
I would like to put a page in Django on the hosting I choose, but I don't know how much it will weigh. The reason is hosting π
Class Post has not objects member
We're talking about python interpreter + dependencies or only the project?
@indigo orchid
from django.views import generic
from .models import Post
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'index.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'```
I will describe better what I mean. @serene prawn
HI I know how to do many to many between two models but how to do it between three models
`categories_sources = db.Table('categories_sources', db.Model.metadata,
db.Column('categorie_id', db.Integer, db.ForeignKey('categories.id')),
db.Column('source_id', db.Integer, db.ForeignKey('sources.id'))
)
class Sources(db.Model,UserMixin):
tablename = "sources"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
source = db.Column(db.String(200), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
#catgeorie_id = db.Column(db.Integer, db.ForeignKey('categories.id'))
date_created = db.Column(db.DateTime, default=datetime.utcnow)
categories = db.relationship('Categories', secondary=categories_sources, lazy='subquery',
backref=db.backref('pages', lazy=True))
def serialize(self):
return {'id': self.id,
'source': self.source,
'user_id': self.user_id,
'date_created': self.date_created,
}
class Categories(db.Model,UserMixin):
tablename = "categories"
table_args = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True)
category = db.Column(db.String(200), nullable=False)
#source_id = db.Column(db.Integer, db.ForeignKey('sources.id'))
date_created = db.Column(db.DateTime, default=datetime.utcnow)
keyword = db.relationship('Keywords', backref='categorie', lazy='dynamic')
def serialize(self):
return {'id': self.id,
'categorie': self.category,
'date_created': self.date_created,
}
s = Sources()
c = Categories()
c.categories.append(s)
db.session.add(c)
db.session.commit()`
it is already done many to many between sources and categories models
but I have other model keywords
with a relation between the two other models
the above models sources and categories
`class Keywords(db.Model,UserMixin):
tablename = "keywords"
id = db.Column(db.Integer, primary_key=True)
keyword = db.Column(db.String(200), nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
def serialize(self):
return {'id': self.id,
'keyword': self.word,
'date_created': self.date_created,
}`
Please help, thxx!
it is a project (as an example) that has:
- PostgreSQL with 200 lines (email, nickname and password - fields)
- DjangoRESTFramework CRUD with around 10 queries (GET
POST etc) - Swagger documentation
- some tests
rather, without the python interpreter, but with dependencies @serene prawn
200 lines - you mean entries?...
yes, entries
I found this but not so clear
I work with flask
flaskrest
Well, if you have crud api then it depends on how many data you will have in your postgres db.
What comes to weight of the project files - it's obviously less than 1 mb, and let me check about dependencies
Your deps shouldn't be bigger than 100mb
For just django and it's dependencies it's ~40mb
thanks for the help π
@app.route('/test', methods=['GET', 'POST'])
def download():
return send_file('modules/file_upload/piano2.wav')
what kind of immediate security issues does this type of usage expose?
@native tide Perhaps it's that this route is available for everyone π
just realized i copied and pasted the inverse of this lol one sec
@app.route('/upload', methods = ['POST', 'GET'])
def upload():
if request.method == 'POST':
f = request.files['file']
f.save(secure_filename(f.filename))
return "File/s saved successfully. You may close this window."
this is what I was supposed to paste sorry. @serene prawn
apart from basic things like file type filtering
Uploads should be only use POST method, not because of security, it's just a convention i guess
You didn't really check for filesize/ if file with that name already exists
Or for file type
Help me pls
yep, i haven't checked for file size or extension yet, but apart from those things what security risks does it pose? the file types expected are non executable
can i ask you a question?
sure
how do you render the message in this way?
@native tide Again, you didn't check if file with such name already exists
I realize that, as mentioned, I am YET to do that. So i am saying apart from basic filtering for extension type and file size limits, in general what immediate security risks does this usage have? the file types accepted are non executable media files such as .mxf, .wav etc @serene prawn
I don't really know then π I'm not very experienced in security
.
i have no idea what you're tlaking about
!code
π
stop it
i am trying to get the data from https://www.worldometers.info/coronavirus in a json format but i don't know how to do that...
Please help!!!!!
Live statistics and coronavirus news tracking the number of confirmed cases, recovered patients, tests, and death toll due to the COVID-19 coronavirus from Wuhan, China. Coronavirus counter with new cases, deaths, and number of tests per 1 Million population. Historical data and info. Daily charts, graphs, news and updates
hey@wooden ruin, sorry for the ping but I thought you'd have some insight into this (if you don't mind):
How can I go about changing a user's group within a channel layer? Let's say I accept a websocket connection for a user, and they connect to the waiting-room group. I now need to move them to the chat1 group. Then, I need to move them to the chat2 group.
However the issue I'm facing is that I cannot track which group the user is in. Any way to go about this? Do I use a database for this?
import pandas as pd
import re
import requests
html = requests.get('https://www.worldometers.info/coronavirus/').text
html = re.sub(r'<.*?>', lambda g: g.group(0).upper(), html)
df = pd.read_html(html)
df[0].to_json('file.json')
something like this should get you started
whats this
df = pd.read_html(html_source)
NameError: name 'pd' is not defined
check the edit
ok
what is html_source?
obviously not
oke it worked as expected
see my website
link?
i made a website that uses worldometer.info
sorry not that
this one
hope u like it @upper bronze
nice
can i print it instead of putting it in a file?
since the output is a pandas dataframe you can do with it what you want it is very flexible just lookup the pandas docs
oke thanks!
Anyone know how to get gevent working with selenium? I am getting a WebExceptionError SSL Protocol error (even after ignoring certificates and other SSL stuff)
guys what do you recommend for backend with python , what should I learn after flask ?
jinja maybe
curr_date = pd.to_datetime(list1[-1])
for i in range(X_FUTURE):
curr_date = curr_date + relativedelta(months=+1)
dicts.append({'Predictions': transform[i], "Month": curr_date})
new_data = pd.DataFrame(dicts).set_index("Month")
##df_predict = pd.DataFrame(transform, columns=["predicted value"])
new_data.to_csv(os.path.join("downloads", index = True, encoding='utf8'))
labels = [d['Month'] for d in dicts]
values = [d['Predictions'] for d in dicts]
colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
"#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
"#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]
line_labels=labels
line_values=values
return render_template('graph.html', title='Time Series Sales forecasting', max=17000, labels=line_labels, values=line_values, filename = filename)
@app.route('/download/<filename>')
def download(filename):
return send_from_directory("downloads", filename, as_attachment = True)
What do you mean ?
HTML > >><a href="{{ url_for('download', filename=filename) }}">Download</a>
Hi community, I m trying to save my to_csv into os.path.join and return the csv file from download button in HTML page, currently I m getting this error TypeError: join() got an unexpected keyword argument 'index', Does anyone excel in flask python, please correct me ~ Appreciate
I mean that what would be important after flask framework on my journey
start building projects
If I have an issue with flask cors should I ask here or in a help channel?
here is probably better
if something fits into a topical channel, it tends to be the better place
django
with the help of your code, i am able to make this:
import pandas as pd
import re
import requests
html = requests.get('https://www.worldometers.info/coronavirus/').text
html = re.sub(r'<.*?>', lambda g: g.group(0).upper(), html)
df = pd.read_html(html)
js = df[0].to_json()
js = json.loads(js)
fil = open("file.json","w")
json.dump(js, fil, indent=4)
def add(text):
with open("cases.txt","a+") as f:
f.write(text)
add("---------------------------------------\nWORLD \n--------------------------------\n")
add(f'{js["Country,Other"]["7"]}: \nTotal cases:{js["TotalCases"]["7"]} \nActive Cases:{js["ActiveCases"]["7"]} \nTotal Deaths: {js["TotalDeaths"]["7"]} \nTotal Recovered: {js["TotalRecovered"]["7"]}\n')
add("--------------------------------------- \nCONTINENTS \n------------------------------\n")
for i in range(5):
add(f'{js["Country,Other"][str(i+1)]}: \nTotal cases:{js["TotalCases"][str(i+1)]} \nActive Cases:{js["ActiveCases"][str(i+1)]} \nTotal Deaths: {js["TotalDeaths"][str(i+1)]} \nTotal Recovered: {js["TotalRecovered"][str(i+1)]}\n')
add("--------------------------------------- \nTOP 3 COUNTRIES \n--------------------------------\n")
for i in range(100):
add(f'{js["Country,Other"][str(i+8)]}: \nTotal cases:{js["TotalCases"][str(i+8)]} \nActive Cases:{js["ActiveCases"][str(i+8)]} \nTotal Deaths: {js["TotalDeaths"][str(i+8)]} \nTotal Recovered: {js["TotalRecovered"][str(i+8)]}\n\n')```
thank you very much!!
Hey, I'm looking for someone with experience in django. I have a deployment problem with the CSRF cookie
anyone knowledgeable on flask/html wanna hop on a voice call. I need some help with implementing flask class please
My question in stackoverflow if anyone would like to help please here or in stackoverflow
https://stackoverflow.com/questions/66970499/how-to-make-post-data-in-a-three-many-to-many-models-with-flask-and-sqlalchemy
@swift wren For the reminder service, I want to support SMS and email.
hey guys i need help
feel like thats gonna be some paid services
im getting this type of error
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> <?xml version="1.0" encoding="utf-8"?>
``` trying to load svg image in react, in my django server
i know
unless its a path error
how do i get loader app, i set up react manually, since im using python djangos server not a node server
This django and react tutorial covers how to integrate react with django and perform all of the necessary setup steps. We will be using webpack and babel to bundle our react app and have the django backend render a template that react will control.
π» AlgoExpert is the coding interview prep platform that I used to ace my Microsoft and Shopify i...
ive watched the entire series
he doesnt use images via react, the images he uses are static from django
then thats because django handles the static files
also svgs are bad and require to be handled by js
use pngs
its a loading pic
convert it and its going to save you alot of headache
have you used django without react?
did you make a serizliser?
i wanted to learn how to use react with serialzer but i found it hard
url routing. endpoitns is what i use for API.
i read a blog about it, and tbh tims video is also based off that blog
api routing? isnt a api used for data
also had to read abour django restframework first.
i said fuck off to the serializer and stuck to straight up html
for example. lets say i have a route. /api/data. in my website its www.website/api/data.
using pure django i can set the urls and the correspondent views. the view that hanles the ui rendering or content. Like homepage, about page etc
its basically just a page with json
@buoyant shuttle seems like you know about SPAs, have you worked with csrf cookies?
yes, buy you have to configure static files properly. when you compile a react app for deployment, you can serve the main file as any regular index.html
yep, its best to use things like staticdirs than hardcoding each link tbh
for django channels is it best to have one group per consumer, or multiple groups per consumer?
typically you would want multiple consumers per group
hmmm... what I'm doing now is having a client connect to something like ws://mysite:8000/<str:query_param>/, then connecting the channel to a group based off the query param.
But the user can change this query param and I want to change its group based off that. How should I do that?
I have 2 ideas:
- Make one consumer for each possible query param so there's one group per consumer.
- Make one consumer, and pass that query param via JSON, and have a database recording which group a channel is in.
I think the 2nd option is what most people do when they want to allow a channel to change groups, right?
a consumer is representative of a user, so i'm not sure how you would make consumers for every query. you might be able to change the channel using group_discard and group_add
yeah I don't think it's scalable (the 1st option), I can have 10 urls each with a seperate consumer and the client connecting/disconnecting between them
how do you usually track what groups a user is in? if it constantly changes?
self.channel_layer will give you any consumer's active channel layer
that just returns RedisChannelLayer(hosts=[{'address': ('localhost', 6379)}])
Can I make dynamic websites using flask?
What do you mean? You might have to add some front-end JS depending on what you want to do.
anyone made custom django middleware? why do you need a middleware factory (and not just a middleware function)?
why did netlify gave me "build.command" failed? ping if you want to help me
I am making a Django Blog website. I want to keep a list of authors the user has subscribed to. anyway to do this? Thanks!
Am I able to host a flask website publicly?
yes, a common setup is using gunicorn as a server and run it as a service using e.g. nginx
My hosting provider's webserver uses nginx. That might work :D
add a manytomany relation on the author and point it to the user model
:x: According to my records, this user already has a mute infraction. See infraction #31157.
:incoming_envelope: :ok_hand: applied mute to @wintry delta until 2021-04-06 23:28 (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
In django, if I want to have a field in my model where I store the related objects (for suggestions) how do I need to implement the manyToMany Relation?
Does field_name = models.ManyToManyField(Class) not work?
https://docs.djangoproject.com/en/3.1/topics/db/models/#intermediary-manytomany may of be of use as well
could you please elborate
thank you
for some reason, authenticate() is not working when i use a custom model
i even changed AUTH_USER_MODEL in settings to my custom user model
can anyone explain how i can fix this?
I'm trying to get the cartoon image to come half way out of the grey box. Is there a way to use negative padding or something else?
negative margin?
negative margin-top ought to be able to push it outside the container, as long as it's applied directly to the image.
thx
anyone familiar with Django Rest Framework?
Particularly authentication, bit confused on how it works confused to normal Django session auth
So I just need to provide an endpoint to submit username and password - ???
then the cookie will be saved and I can get the instance of the User object for each request
(I put more question marks next to the confusing bits)
Session already uses cookies
There was a page about auth on drf website
Django, API, REST, Authentication
They show here you can use this as a login page https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/#adding-login-to-the-browsable-api
Django, API, REST, 4 - Authentication and permissions
My goal is to create a custom login page, because I'm using react as the frontend, maybe I'm missing something
Where do you actually send the username and password to be authenticated?
Sorry for the spam, thank you
does anyone here know anything about the patreon API and could help me?
are you having your API and frontend running separately?
because if so you will have to manually configure the session cookies so logging in actually logs you in
hey, i wanna get certain paragraph on a webpage(s) using bs4, the problem is, it (the <p> tag) is not attached to anything with which i can fine-tune my find function and there are a lot of <p> tags with same name (of <p>), i want a robust solution for this problem because, i am doing it for multiple webpages (and they are quite inconsistent),soo what can be done?
Fixed it, ^^
does anyone have a recommendation when it comes to scheduling task for a django webapp? I tried dj-crontab and django-crontab (which are basically the same), but they dont seem to work reliable. I set two task up as described in the documents, but it seemed pretty random if they were actually executed. At first the first task wasnt running, but the second did, so i deleted the first one, then the second one didnt get executed aswell. No error messages, and it showed up with crontab list
celery works well. plus you can setup cronjobs with it π
as nicky said, celery is good for this and you can schedule tasks like in crontab: https://docs.celeryproject.org/en/stable/userguide/periodic-tasks.html
perfect, thank you guys
i have problems with django and django rest framework, i would be very grateful if anyone is free right now and can discuss and help me with code. i tried google and stackoverflow but i couldnt find a solution (probably because of my bad english)
I think freecodecamp.org can help you
what's up?
@@ it's some problems with drf and abstract models. it would be easier to explain with code but my neighborhood just black out. i guess i come back later in the morning
I have a quick question about flask. I am trying to use app.config["APPLICATION_ROOT"] = "/api/v1"as a prefix for all routes, but it does not work. Anyone have any suggestions.
I know I can use f strings for a prefix but I rather have it like this if it's possible
is there a way to track flask endpoint calls with custom options?
for example theres "premade/thing/<typesomething>"
and i want to keep track of the type something like
"premade/thing/typesomething":{
"pee":3,
"poo":5
}
thats just an vizulazation, can be completely different, but like in general is there a way to track it
convert = soup.find_all('span', {'class': 'DFlfde','class': 'SwHCTb', 'data-permissions'})
who knows why the error
<div class="recipe">
<p id = "recipe-header" style="text-align: center;">Creating a Recipe</p>
<form>
<div style="background-color:#D3D3D3;" class="recipebox">
<div class="recipecol">
<p> Select Ingredients</p>
<select name="ingredients" class="ingredient">
{% for measurement in measurements%}
<option value="{{measurement['Quantity']}}">{{measurement['Quantity']}}</option>
{% endfor%}
</select>
<select name="ingredients" class="ingredient">
{% for ingredient in ingredients%}
<option value="{{ingredient['IName']}}">{{ingredient['IName']}}</option>
{% endfor%}
</select>
</div>
<p> Add Instructions for Recipe</p>
<div class="recipecol">
<textarea name="instruction" rows="15" cols="40" placeholder="Enter instructions for Recipe"> </textarea>
</div>
</div>
</form>
</div>
I want to center this form, two columns. One for ingredient and other for instructions. Any guide
my css so far
#recipe-header {
font-weight: bold;
font-size: 26px;
}
.recipebox {
margin: auto;
display: table;
clear: both;
}
.recipecol {
float: left;
width: 40%;
padding: 10px;
}
hey Kala, are you good with css can help?
Hey Der, can you stick that into a codepen or something similar? Then I can have a look
!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.pydis.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.
Np
Here is the pen - https://codepen.io/cderon_/pen/OJWxmZP
Cool, thanks having a look now
Awesome, ty
I'd do the following:
- Create a parent div, put something like:
display: flex;
justify-content: space-between;
Then put the two divs inside, and unstyle them it should do the trick
<div class="recipe-col-parent">
<div> </div>
<div> </div>
</div>
Is this good for a first web-app with python? I used Quart
https://noice.link/rps
what is the best module to make a browser
@real hare could you edit the css
Django
Hey guys, I am working on social media site and I dont have idea how to connect post made by user to his place in database, can someone help please?
Please follow the steps provided that should get you into the right direction
Anyone can help me with FastAPI + Mypy?
I'm using dependency injection in my routes and mypy is saying that Default for argument "profile" (default has type "Depends", argument has type "Profile")
profile: Profile = Depends(profile_manager.with_profile),
despite that with_profile returns Profile object
Same happens with Cookie, Body and Query parameters
I want to do something like this to get the username in flask. How can i achieve this?
@app.route('/u/<string:username>', methods=['POST', 'GET'])
def userpage():
username=request.args.get('username')```
@signal bronze
@app.route('/u/<string:username>', methods=['POST', 'GET'])
def userpage(username: str):
username=request.args.get('username')
Thanks
Need help dm me
the idea is that you post it here
this doesnt seem to work. It keeps returning None
delete username=request.args.get('username')
your username argument will be passed into a function
hello , can someone help me?
Post your issue
the code?
oh
am i made a website with flask and when i runned it it says no module named website but i installed the module already
@signal bronze
what ide are you using?
your not on windows?
i am unable to help further
oh ok
but how to could i do it
because this site was for my mom she wants to sell cakes
Hello how can I send a public key , private key and username through a request in python
Like this
curl -u username --key "privatekey.pem" --cert "cert.cer" --cert-type PEM
ok but i still wanna know why this happens
Hi, why do I always have this error while I'm running my django web server ?
The error :
ConnectionAbortedError: [WinError 10053]
.
bruh
that error is not framework-specific.
did you re-activate your virtual enviroment and install the dependancies? can you show us your filestructure?
we need more information about your error to diagnose your error.
maybe something is already taking up port 8000?
idk what you mean but wait
this happens when i run my web server
well, yes - because where is the website module?
I don't use Flask, but either website is not a real module or you have the wrong path to something. Do pip list and you'll see your dependancies.
Also I don't think you're going the right way about settings up a Flask app, it should be something similar to this:
from flask import Flask
app = Flask(__name__)
then in terminal
$ export FLASK_APP=flaskr
$ export FLASK_ENV=development
$ flask run```
where did website come from? I checked on pypi and there's no such module, and it's not in your filestructure
i use flask
you mean that?
so, you can't explain your import?
I gave you the solution - my question to you is why are you doing from website import create_app
i don't need the link. website is not a valid module (it's not found in pypi). You are better off reading official docs
In this video, I'm going to be showing you how to make a website with Python, covering Flask, authentication, databases, and more. The goal of this video is to give you what you need to make a finished product that you can tweak, and turn into anything you like. We're going to also go over how you create a new user's account, how you store those...
id not check it
what?
i do not check it
so... maybe check out the docs then?
I gave you a solution above
but it's good if you understand the solution rather than just copying the code
link to the docs?
if you're using blueprints, 'website' should be the name of the folder where you have the init.py file with the create_app function
yeah i use blueprint
if you see here, the guy has a folder called website, that's why it works for him,
but can you explain to me how to fix it i am a beginner
ok, where did you put the init.py file?
in the website folder
in website mamma?
rename it to like website
normally it's right click and rename, but i'm not sure how it's done on mac
alright
pip3 install flask doesnt work? wtf
alright, so, is your terminal opened in the same directory as vs code?
wait let me see
error with postgres, can anyone help?
django.db.utils.OperationalError: FATAL: database "db" does not exist
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'db',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': 'localhost',
'PORT': '5432',
}
}
But, I do actually have a database created with pgAdmin called db.
@thorn igloo yea i am in my python directory there is my main.py file and the website stuff
ok, do you access python 3.8 with python3 or just python?
i use python 3.8 python3
try python3 -m venv venv
let me know what it says
python3 -m venv venv run this in the terminal
your code runs now?
yes baby
alright
Not sure if this is the right place to ask this but here goes anyway. I have a website and app which interacts with a Python package/few functions which are files through a flask restful API I built. It's just being hosted on my laptop atm as everything is still in development stage. Now where is a good place for me "host" my python code? I basically just want something thats going to be fast and fairly cheap and easy for me to setup, maintain and make changes to my code. Also my code runs at about 20 seconds each time atm so I am planning on perhaps implementing multiprocessing so the hosting platform would need to support that. If anyone has any experience or ideas that would be great. Thanks
yo if anyone has any experience with using php please @ me or message me asap
Hey @native tide!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
@covert bloom I've used it before, I may be able to help
There's a good tutorial though from Miguel Grinberg
I fixed the issue I was having before actually! Helps if you remember to actually write the right things in lmao
yee, they're good
anyone used postgres w/ django? ever had an issue where you do makemigrations but the database schema isn't updating? I've been stuck on this all day
somehow need to understand migration files π€¦
Hi, just started in react and found this line in index.html
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
And I wonder why it is called logo192. I guess it means 192x192px, but why exactly 192? is this some kind of apple touch icon standard? SO post said to use 180x180 px for apple icon and 192x192 for android
(please ping me)
From all that I have seen there is not good tutorials out there for updating a flask webpage without refreshing using AJAX could someone help me in #help-carrot ?
@maiden tulip https://bit.ly/3mr4FLl
thanks
if a have a model like this
class ModelA(models.Model): file = models.FileField(upload_to='media/')
and i want to store uploaded files in different locations based on the file type such as jpg,png into media/images and doc,docx,pdf into media/documents
how can i achive this
.topic
I use DRF and try to create a user, but I have an error "email": "This field is required." I don't know how to fix this, can anyone help with problem?
### Models ###
class User(models.Model):
full_name = models.CharField(max_length=255)
password = models.CharField(max_length=255)
birth_date = models.DateField(blank=True, null=True)
contacts_number = models.PositiveIntegerField(default=0)
creation_date = models.DateField(auto_now_add=True)
def str(self):
return self.full_name
class Email(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email = models.EmailField(unique=True)
is_activated = models.BooleanField(default=False)
last_modified = models.DateTimeField(auto_now=True)
def str(self):
return self.name
### Serializers ###
class EmailListSerializer(serializers.ModelSerializer):
class Meta:
model = Email
fields = ['email']
class RegistrationSerializer(serializers.ModelSerializer):
email = EmailListSerializer(write_only=True)
class Meta:
model = User
fields = ['id', 'full_name', 'password', 'email']
def create(self, validated_data):
received_email = validated_data.pop('email')
print(received_email)
email = User.objects.create(**validated_data)
print(email)
return email
...why are you popping the email
do you know what .pop does?
what is the best way to build the realtime stock dashboard with django? to use webhook? or frequently request the api?
Use webhook
Does Django has api for setting up with webwook?
Can you explain why?
with flask_sqlalchemy can i create another table in a class.
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), nullable=False, unique=True)
email = db.Column(db.String, nullable=False, unique=True)
password = db.Column(db.String, nullable=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
still_active = db.Column(db.Boolean, default=True)
admin = db.Column(db.Boolean, default=False)
def __repr__(self):
return '<Task %r>' % self.id
class PostsCreated(db.Model):
post_count = db.Column(db.Integer(), primary_key=True)
link = db.Column(db.String, nullable=False)``` like that?
I think you have to use relationships
Great idea though ^^
Btw web folks check out this project: Allows you to use Django features in Flask: https://github.com/Abdur-rahmaanJ/shopyo
At this stage i need feedbacks. Ping me here or open an issue. Much much appreciated
By feedback i mean just run the project and see what rings fake with the experience
If Flask have a resource class then store file type and file name. store where you like
Ever tried third party services like namecheap? Else why not take a very cheap vm? If you need a very cheap vm ping me as i'm too lazy rn to look for that German sounding company
Today discovered the Web Dev channel. I sense that i might be able to give some Flask help ^^
Don't use flask-mail, no longer maintained. Something like flask-mailman might be better and guess what they made it like django's in-built mail utility
im using django
Ah ok!
it ain't for anything permanent, so idm
but I will look into flask mail man, thank you
so is there a way to do so with django ?
websockets π
Can you explain why?
websockets allows the server to communicate directly with the client, instead of having to have the client initiate a request to the server and await a server response like a usual api.
@frigid fiber I'm also using them for a realtime stock dashboard
Okay, I will take a look at WebSocket, thanks for information! Btw, if I have further questions can I dm you?
if u got more qs then just put em here
im trying to map a url and under url patterns i wrote path('', views.index, name='index'),
] but it gives me an error which says AttributeError: module 'learning_logs.views' has no attribute 'index' can anyone help?
Do you have a views.py file in your learning_logs app?
yep
And have you defined the index function in views.py?
wdym?
Could you show us the code in views.py?
def index(request):
'''the home page for learning log'''
return render(request, 'learning_logs/index.html')
i wrote that
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.pydis.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.
Have you got any imports in views.py?
yeah
Could you paste those too?
Is that from views.py? That looks like it's from urls.py
what does models.ForeignKey() do?
The foreign key refers to the primary key of another model.
For example I might have a users model, and I want it to link up with the primary key of 'songs'. The primary key of another model is called a 'foreign key', relative to the first model.
Yes
wow thanks
thanks π
Did it work?
yep : )
Nice!
Is it possible to change the style of a specific object using flask?
can anyone help me in django
Ask away!
^
What object do you refer to?
Nvm I got it, I used style in the tag, it was an h2 object
oh i'd expect the word tag
actually I am building an ecommerce site and i need make a popup form apper for some special product
@frozen abyss i am adding an feature to the site which make it easier for the product to stock if its gone finish in your home.. for this if the product is listed as prescribed then a form should popup and then the information in the form will be used to calcuate a time to sent a web push notification to the user.
Ok I don't know anything about this kind of thing. But setting up a #βο½how-to-get-help room might get you better answers
Also I'd specify what kind of 'popup' you want - a Django message? A Javascript pop up? A browser notification?
When you start a help room, be as specific as you can about what you're trying to set up
@frozen abyss can you help now
hello guys, can you recommend me any address validation api or library? It would be really nice if it is working with django form
I don't know anything about notifications. But people should hopefully come to your room and help you out.
Sorry I can't be more helpful!
@frozen abyss no just help with some related stuff
I can use your knowledge , notification i will do i my self using js
Which channel is your help channel?
@frozen abyss code /help 1
Ah I can't do voice chat
Go for #help-cupcake
is there a way in Flask to stop direct access to routes. like only render template if redirected to the routes
My best bet is to include a flag when redirecting else i don't see how to detect redirection on the receiving end
can i use session for this?
i just need to create a small presentation lol
can someone help me on how to update a mongodb database through a quart webpage update button
like this
I already connect to get the settings to appear in the box but I dont know how to update it from the html file
<div id="">{{ form.username.label1 }}</div>
^
Hey anyone know how to manage proxies on selenium?
#unit-testing might have more help for you about Selenium
thx you
yes as an internal flag like setting session[redirect] = True then check before rendering if session[redirect] is true
ingenious solution ^^
@native tide https://dontasktoask.com π
Me ^^, shoot your question
This part of code doesn't work, because I have an error "email": "This field is required.". I'm just trying different approaches,
are there any advantages of token auth over sessions?
I'm writing Jinja templates in vscode, and for some reason whenever I write a statement, like {% ... %} on a single line, and press enter, it auto-changes to % ... % (It removes the curly braces). Does anyone know why, and how I can turn off this behaviour?
are you using a formatter for some reason? that might be why
can anybody tell me why there is a large area above my header div?
html {
padding: 0;
margin: 0;
height: 100%;
}
body {
padding: 0;
margin: 0;
height: 100%;
background-color: #aca1a1;
}
header {
padding: 0;
margin: 0;
width: 100%;
height: 10%;
background-color: rgb(68, 68, 68);
}
header .company {
height: 100%;
width: 20%;
font-size: 32px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="description" content="Website for my raspberry pi">
<title>Samirs Raspberry Pi Ui</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="resources/index.css">
</head>
<body class="nice">
<header>
<div class="company">
<p>PiGui</p>
</div>
</header>
</body>
</html>
without the company class the header aligns to the top without issue
fixed, needed inline block
How do I redirect a user back to their original destination after an oauth2 login? For example, I have a /subscribe page that requires user login, so if a user is not logged in they get sent to the oauth login page, and then after I want them to go back to the /subscribe page. (This also applies to several other pages on the site)
how would I make a save button in html that updates a mongodb database with text entries in the html
im using quart
I researched on that again, seems like the apple docs recommend using 180x180px - so "logo192" is misleading
You mean Flask? Well your question is more about Mongo than Flask
quart
I switched
Just a note: using some plugins/libs might save you lot of pain as they do the ping pong for you
Like what? Examples?
I know how to add stuff in python to mongodb but cant figure out how to run python code with a button
The oauth server should redirect you back to your app
You are using what framework?
Django.
You need a endpoint in your app for callback, which you give the oauth to redirect back to
Aie see forms in html with POST method
Clicking on a button will send inputs to the endpoint where you catch then add to the db
I don't follow. I have the view and path that I want to redirect back to, so I would need to give that to the oauth redirect?
Yeah
Can you point me to an example? I don't know where in the oauth2 uri to put the redirect.
@wispy quail is there a way I can make it so there is a hidden thing that the form gets
when it submits
What hidden thing?
nvm I figured it out
I was trying to have the user code and the guild id hidden
so the user couldnt change it
but it still got picked up by the form
@mint folio I have a question bc you seem to know how to use oauth. How would I see if a user has a specific permission
The user can always change data on the frontend, which is why you should always validate in the backend.
like administrator or manage server
fair
Admin for what?
When you authenticate the user with discord they will give you an token which you can use to make requests to discord on users behalf
I already have that
I have the whole dashboard working other than everyone can change everything
what request would I need to make to see what perms they have
yes
I did ctrl f permission
and looked through the permissions
but couldnt find anything
Maybe this is what your after? https://discord.com/developers/docs/resources/user#get-current-user-guilds
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
You could check if they have the admin role in a server, or check if they are the server owner.
How would I do that?
OHHH
I already have that
Yes I understand that but if I have the permission numbers I can just check for the admin permission number
Or tha manage server permission number
Idk which one Iβm doing yet
how would I make it so the user can't change the text in this box <input type="text" id="prefix" name="prefix" value={{ prefix }}><br><br>
give it the disabled attribute
<input type="text" id="prefix" name="prefix" value={{ prefix }} disabled><br><br>
Does anyone have a good source to help me start web development, for my anti-nuke??
#help-potato if you know flask :)
Also make sure backend that the value remains as it was
it doesnt really matter that it cant be changed
but I am just making it so it cant be changed
do I even need web framework?
my server has 4 endpoints
2 for ML model, 1 for getting the result(db), 1 for submitting feedback(db)
Should I just serve them via uwsgi?
hey if anyone is on i had a question
i have a linux laptop and a windows 10 computer
if my laptop sshs into my computer and runs a flask server, will my computer be able to develop on that server or will my laptop be limited to the server only
is there a way where i can have my windows 10 server running on a linux laptop and edit my files on my windows 10 computer?
print(request.url)```
`RuntimeError: Working outside of request context.`
yo can someone give me some good reasons to use Django over NodeJS,
I wanna win against my js addict friend with my django love (python in general)
I saw it
HAHA
database yup that's a reason I have in mind, but want something better to support my choice
Easier, more secure
but yeah there is no point for that argument in the first place
everyone uses whatever they like, feel comfortable with π
the thing is that we both are comfortable with with both but I'm a bit biased towards django (python on general)
and he is with nodeJS
I didn't study Js, is js hard to learn?
aren't we all like that haha
hahaha
Js is pretty easy
but in this comparison (NodeJs vs Django) I think django is much easier and straight to point
and because it's python, you can do literally anything
It will work in route function/method
Like how you called it now flask has no idea what request was being addressed
Was just a cautious not as front end is not a reliable value definer
So my flask app is not recognizing my css files and i have no idea why
<link href="/static/css/404.css" rel="stylesheet">```
Use the url_for helper
<link href="{{ url_for('static', filename='css/404.css') }}" rel="stylesheet">
i tried this but it does not work
https://docs.microsoft.com/en-us/windows/wsl/faq
I Hope this helpsπ
Oh nice Good job ππ
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 11, in main
from django.core.management import execute_from_command_line
File "C:\Users\GKMSHIPPING\Envs\testyy\lib\site-packages\django_init_.py", line 1, in <module>
from django.utils.version import get_version
ValueError: source code string cannot contain null bytes
i got this when i tried python manage.py runserver
solved the issue thank you very much it was related to browser cache just added a dynamic variable
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
{% for post in posts %}
<div class="post-preview">
<a href="{{ url_for('post', post_id=post.id) }}">
<h2 class="post-title">
{{ post.title }}
</h2>
<h3 class="post-subtitle">
{{ post.subtitle }}
</h3>
</a>
<p class="post-meta">Posted by {{ post.author }} on {{ post.date_posted.strftime('%B %d, %Y') }}</p>
</div>
{% if post == posts[-1] %}
<br />
{% else %}
<hr />
{% endfor %}
hi im making a web application on flask and this is the snippet of my code to the articles template I have a sqlite database that contains the articles, how can I make an if statement that detects if the post is the last in the loop since im making an hr per article {% if post == posts[-1] %} doesn't seem to work
flask question :
css is not being applied
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Major Chat</title>
<link rel="stylesheet" href="G:\My Drive\Chat app\static\style.css">
<link rel="stylesheet" href="G:\My Drive\Chat app\static\bootstrap.min.css">
</head>
<body class = "text-center">
<form class="form-signin" action="{{url_for('chat')}}" method = 'post'>
<h1 class = 'mb-3 font-weight-normal'>Major Chat</h1>
<input type="text" id = "username" name="username" class='form-control' placeholder="Username" required autofocus>
<br>
<input type="text" id='room' name="room" class='form-control' placeholder='Room' required>
<br>
<button class = 'btn btn-lg btn-primary btn-block' value="submit"><b>Start Chatting!</b></button>
</form>
</body>
</html>```
this is the code
use static files
i did
you did not load it
??
{% load 'static' %}
yep above the doctype
k
and also paste this in your settings
os.path.join(BASE_DIR, 'static')
]```
so it can find the css files
sorry men
Why?
Use if posts[loop.index] is None
normally you'd do if posts[index+1] is None but since loop.index is already incremented, just use it as such
why don't you use /static/... ?
Are you using Django with a virtual environment?
The problem with Dynamic vars is that you have to have a really random var else you'd unexpectedly get the same style. I suggest you make the variable a version based thig, as css libs do. Some webpages use libx?v=5 to ensure that updates are actually being applied
Hi guys can anyone join the vc and help me with styling django forms
use crispy forms
easy style
trying to access models within my channels consumer:
group = await database_sync_to_async(Groups.objects.get_or_create(name=f"{content['selectedEquity']}-intraday"))()
channel = await database_sync_to_async(Channels.objects.get_or_create(name=self.channel_name, group=group))()
getting this error:
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
But I am using sync_to_async?
its because you're directly calling the function which will immediately call the function instead of actually running it in a thread
yeah I realized I had to input a callable instead of actually calling the function
sorted it like this
group, created = await database_sync_to_async(functools.partial(self.get_group, content))()
thanks π
π
oh ok thanks
Maybe someone will take advantage of this:
Great opportunity, Cisco International announced the launch of five (free) remote training programs
Cisco International announced the launch of (5) distance training programs (for free) via
Cisco Virtual Academy, with a total of (245) hours in the following fields:
1- Introduction to Cybersecurity - 15 hours
2- Introduction to the Internet of Things - 20 hours
3- Entrepreneurship - 70 Hours (Entrepreneur)
4- Programming Essentials in Python - 70 hours
5- Linux Essentials - 70 hours
And the beautiful thing is that the application is available to everyone free of charge
Also, training in several languages
https://www.cisco.com/c/m/en_sg/partners/cisco-networking-academy/index.html
any help that i can get? why is there errno 48 already in use wtf
Your port already in use it seems
try passing port=5001 in app.run(...)
Flask is probably easier for beginners.
Well any videos u would recommend for learning it ?
not offhand, there are lots of tutorials out there, just Google and poke around.
Well ok thanks
ok thanks i ll try
Flask is:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello Worldβ
if __name__ == '__main__':
app.run()
Well I tried flask
^^, quite simple
But I got demotivated
y?
Somethings were not going good
how?
Well bro how will I learn flask ?
Do a project with it. Learn as much as you need ^^
If I just watch video and do what is shown in video
Like have an idea of your own
Okay
Lets say a simple todo app
use flask_sqlalchemy
Bro u know flak?
you can use sqlite, you dont even need a db
Yes ^^
You can say, i'm one of the organising members of a conference called FlaskCon it seems
Give me 15mins i come back
Ok
See this FlaskCon interview from someone called Abhishek Kaushik who has a hobby project called creatorlist: https://www.youtube.com/watch?v=OneNCbMrib4 . Not learning for the sake of learning. It's learning to put into practice. To do what you want, you'll come across challenges. To overcome those, you'll learn what you need to learn.
Abishek discovered Flask on a summer internship, and then Creatorlist (https://creatorlist.tech) was born. He shares his journey of how he learnt Flask from scratch and the resources used. While building the platform, how he set up his implementation criteria, server setup and the use of Miguelβs built SocketIO to make the website.
https://flas...
I suggest to you corey schafer's playlist for Flask: https://www.youtube.com/watch?v=MwZwr5Tvyxo&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH
In this Python Flask Tutorial, we will be learning how to get started using the Flask framework. We will install the necessary packages and get a basic Hello World Application running in our browser. Let's get started...
The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python/Flask_Blog
Djang...
It's kind of great to go along
Ping me with any question you have ^^
faster than quart ^^?
not sure
well quart is expected to be merged with flask ~
as it's a flask experiment
it's by a flask maintainer btw
right now if someone wants asgi flask, use quart. same code exept in edge cases. basically just change imports
Idk where you got the whole merged with flask thing
Quart was and is developed completely separately from Flask and will continue to be separate systems
Quart is also about the same speed as flask
people just dont know how to properly scale Flask to offer as much performance as Quart because Quart forces you to use the systems that make it fast on IO
Quart in reality is by far one of, if not the slowest asgi framework around because it goes with the whole trying to mimic flask which was designed to be used with an entirely different event loop and async design
@quick cargo you follow the latest flask dev actualities?
i do not, no
^^
I would find it very odd and concerning if flask moved to be quart
the pallets server has more conversations on the subject
Flask moving to async would break so much stuff and ruin alot of the eco system it built up
what do you mean by ruining a lot of the ecosystem?
Well Flask's current ecosystem is built around being Synchronous and eventlet / gevent based
moving to python's asyncio would strip out any eventlet / gevent support
as well as remove any support for most DB drivers (if you want to actually gain the benefit of being async)
well have you seen quart's support for the current ecosystem?
that's not the issue
quart is currently a optional thing you can do
which is fine for the people who want to use it
but if you're a large company that basically means completely re-writing the code base to keep with updates if flask merges into quart or vice versa
it would also mean you loose the incredible amount of db drivers like psycopg2, flasksqlachemy, datastax driver (scylla, cassandra etc..), mySQL etc...
i mean sure you can still use them
but then you completely loose the benefit of asyncio
@quick cargo You seem to know about flask a bit. do you think you could help me with long polling with flask?
as in updating the webpage without have to refresh
is anyone willing to help me with these?
- how do i change my http this (http://IP:5000/) to https?
- how would i program something to receive https POST requests?
mmm its not something i would recommend really because it really hurts scaling and also eats up ports making it more vulnerable to attacks also things like tcp keep alive will prevent it working correctly alot of the time
then again any sort of constant connection opening like that unless you're using eventlet / gevent as flask's backbone is gonna be awkward but i would consider using a websocket because it's more widely supported and fixes keep alive issues
As far as i can see and you can check, async is coming to Flask ^^
how do i change my http this (http://ip:5000/) to https?
You need to setup TLS/SSL with certificates etc... to become 'secure'
how would i program something to receive https POST requests?
Nothing changes framework side just server handling side which your webserver should do for you
thats a yikes from me
Thanks CF8 I will look into it
also flask is already async, just not asyncio's async
hence why i think moving to asyncio's async is a determent to the framework not a improvement
Not that Async, there'll be an announcement soon
i'm asking for more details for the first one and what program i need to run to do something when it receives a POST request
what program i need to run to do something when it receives a POST request
You dont run anything extra
What framework are you using?
i do not know yet
It doesnt do anything to me* but i can see alot of people being bummed about it really
Aie you should select one then ask question else the question is really vague
probably flask then
Because there is some maintainer 'excitement'
Forcing https can come from what you use to serve your app. This is something you must decide also
is it not just in the code?
let cf8 speak
nothing you need to worry about code wise unless you're writing your own server
your webserver handles all that stuff
all you need is a cert and key file from a given provider and give it to the webserver to handle
gunicorn, hypercorn, uvicorn etc... all handle this for you
and force https if you want from the webserver
okay, thanks
what would i program to have my website do print() when a POST request is made?
Oh you really need to learn Flask, there is kind of much to be written
Something around here: https://flask.palletsprojects.com/en/1.1.x/quickstart/#http-methods
what's the benefits of asgi over wsgi? wsgi can't handle 2 concurrent requests?
Not so true according to Quart's maintainer
In reality it is, Quart compared to any other ASGI framework is pretty slow but in reality gevent and Flask already does a great job and provides performance enough for most people's need
That's it
the only advantage that really is useful with quart over flask is that you can:
a) use websockets in a sane way
b) use background tasks without a OS thread
c) make use of asyncpg
comparing side by side is not the perfect picture
in reality that's how everyone is gonna compare it because that's what matters
should we change our entire code base for a little more performance if we follow all these prerequisite? or should we just stay with our existing system that works well enough
not so as many people use flask 'plain'
yeah, but they're perfectly capable of just switching to gevent it's easy enought to do without modifying the existing code base much
some people do it, it seems https://medium.com/snaptravel/how-we-optimized-service-performance-using-the-python-quart-asgi-framework-and-reduced-costs-by-1362dc365a0
don't blame me for some bad explanations in there though
i've seen that article already yes
im not saying it wouldnt be useful for some
but my original point that it's not useful enough to warrant upsetting the whole ecosystem
which is why im against the idea of flask going into the whole asyncio section when quart exists
but ig we'll just have to wait and see what happens
Well let me ask you: what is your framework of choice?
FastAPI probably
in the modern world of client sided apps and ajax like react, vue etc... FastAPI is basically the best tool you could ever have with python
The front-end world is decoupled and api-driven
Why not other frameworks? Why Fast api?
This i know why its great
auto doc page generation, validation, model creations, native support for pydantic, type conversion, great middlewares, performant
Tiangolo made sure to even provide a frontend demo
the fact it produces OpenAPI spec files that is built off the models you use is probably the biggest pull factor of the framework
i think embedded type validation gave it a pragmatic seal
because it means you can use any system that support OpenAPI and requires little to no effort on your behalf
those are a pain to write
i am currently writing those by hand
@router.endpoint(
"/{bot_id}/hide",
endpoint_name="Hide Bot",
description=(
"Hides the bot from the public listing until it is re-approved.<br>"
"*naturally this requires a super user key*"
),
methods=["POST"],
response_model=GeneralMessage,
responses={
401: {
"model": GeneralMessage,
"description": "The lacks the authorization "
"to perform this action.",
},
404: {
"model": GeneralMessage,
"description": "This bot does not exist in discodlist.gg",
},
},
tags=["Bot Endpoints"]
)
async def hide_bot(self, req: Request, bot_id: int):
...
with a cheaky little custom framework wrapper ez pz
i guess this shows that being specific can give you edges. like a web framework can be a web framework but being api focused, it added stuffs to make writing apis enjoyable
its the whole do one thing and do it well principle
just hope i can get my webserver upto a stable enough state to use with my fastapi stuff π
one thing i cant find is a good mail sending and receiving soft for vms
if you have vm, you'd want mail sending. lets say you dont want the mailgun way
shared hostings wire mails nicely for you
not something ive worked with
all that sort of stuff i leave to 3rd parties to deal with
could you please walk me through that code?
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.
Could someone please tell me how to host a Flask app? I want to host it on a hosting service called Sweplox Hosting, it uses nginx for webhosting. I heard that it's possible with nginx.
Do you have a VPS or web hosting? To host a Flask app you need a WSGI server, too, which runs your Python code and "translates" the HTTP requests from Nginx to a format that's understood by the WSGI server
I do have a VPS
I'd recommend this tutorial https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-ubuntu-20-04
It walks you through setting up Python on the server, installing and configuring a tool called uWSGI for the application server and Nginx for the webserver
alright let me check
If you don't have an Ubuntu server some of the commands will be slightly different, but it should get you on the right lines, especially around the config files
I'm new to flask, do i always have to put something in a <form> tag to get data?
no, not necessarily but what do you mean by getting data
like a entry field, buttons
I have build a small dynamic website with (mostly) Python. Till now I have only ran it locally (as all my projects till now). But iΒ΄d like to deploy it. The problem is that I have no experience in server security and am worried that my AWS instance I want to host the Website on will be hacked. What things do I need to consider to make my server secure, or can anyone of you point me to resources which might help me educate myself on the subject?
Hey, I'm running a page using aiohttp.web, but I was wondering if it's possible to run a task on the background that when a specific trigger is activated it opens a page
or maybe inside the html file using a JS script? 
what I'm trying to do is, just when a page is opened, I have a barcode scanner and when I scan something I'm hoping to make it go to a page, like /scan/<barcode>/
So you want to connect your barcode scanner to your web app?
yes
and open a specific page when a barcode is scanned
but preferrably in background, so I dont need to press a "scan barcode" button
I haven't used AIOHTTP
But your scenario is a bit broad, so your barcode scanner is connectected to a computer?
You want it to open a web page on that computer that it's connected to only ?
Easiest way to do this in the background would be to use selenium or something
Upong scanning have a background code that checks for barcodes scanned then have it open the browser /scan/<barcode>/
never used selenium before 
Ah seems like you don't even need Selenium
Open Web Browser Python 3 - In this tutorial we are going to learn how open web browser in python 3.
If you want to go the JS approach
https://stackoverflow.com/questions/42325613/how-to-use-barcode-scanner-in-web-application/42325855
But this would require the user to have the web browser open, to read the data then on the web browser load. Again it depends on your needs if you need a background approach just scan and open a page, if not say your providing a bar scanning service web app then the second approach works.
this seems interesting. tested it locally, but sadly it opens a new tab rather than using the tab thats open... Thanks for the tip, I think I can make this work 
What's sanic @delicate nest
I will try it once I do flask properly
Is there any difference with flask and sanic ?
Can we make money with flask and other stuff ?
Anyone who has experience with building PayPal based payments with Python & Flask?
Why not go for shared hosting?
An asgi framework. Btw sanic does not exist in Scrabble XD
It's your idea that matters ^^
Okay bro
How can I make render_template pass in variables as raw HTML in flask? It shows "s around the variables and renders them as text.
Solved:
from flask import Markup
@app.route("/")
async def return_some_html():
return Markup("<p>Hi!</p>")
oh shoot so low quality
how can I add this feature
"Add new author"
so when the button is clicked, a new form entry appears
im using Flask
i assume this is javascript? but then how can i then receive it on the backend
return '<b>some text</b>'
doesn't work
just return it as a normal string
no it doesn't work inside rendertemplate
no return a raw string
it will return a quoted string
i solved it anyway, you can just do
return render_template("file.html", var=Markup("<p>text</p>"))
works
ok ^^
TIL about Markup
anybody know the answer to my question?
.
yeah you need javascript
make a flask route and then make a http request to it containing all the data you want to transfer, in json
@wind walrus
doesn't matter, they do the same thing
oh okay
I'll dm you a js guide to follow, it's a good one
oh thx
i'm getting a TemplateDoesNotExist at /categories/new
categories/category_form.html
TemplateDoesNotExist at /categories/new
raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: categories/category_form.html
is init file supposed to be empty?
both are empty
u are pointing to wrong file
#dont forget to import os
'DIRS': [os.path.join(BASE_DIR, 'templates')],```
Anyone know anything about beautifulsoup ?
yep
where can I load the code?
wdym?
I have 75 lines I'm keen for someone to look at re bs
bit of a style overview
I have a couple of bs issues
# Calculate highcharts values from chart svg line coordinates and yaxis
from bs4 import BeautifulSoup
import locale
locale.setlocale(locale.LC_ALL, '')
gn = { "k" :' * 1e3', "M" : '* 1e6'}
def asnum(s):
# Calculate number from short description
return eval(''.join([gn.get(c, c) for c in s]), {}, {})
def get_yaxis_labels():
# Should call with soup.find.string
soupy = soup.find('g', {'class' : 'highcharts-yaxis-labels'})
yaxis = []
for i in list(soupy.children):
yaxis.append([int(i.get('y')), i.text, None])
yaxis[len(yaxis)-1][2] = (asnum(yaxis[len(yaxis)-1][1].strip('$, ')))
return (yaxis)
def regression(yaxis):
# Calculate slope from first and last points.
# svg uses a top left coordinate system so intercept is chart top value.
yaxis.sort(reverse = True)
m = (yaxis[len(yaxis)-1][2]-yaxis[0][2])/(yaxis[len(yaxis)-1][0]-yaxis[0][0])
b = yaxis[len(yaxis)-1][2]
return (m,b)
def get_data_series(nseries):
# Should call with soup.find.String('g', {'class' : 'highcharts-series-'+str(series)})
soupd = [[],[]]
d_list = [[],[[],[]]]
for series in range(nseries):
soupd[series] = soup.find('g', {'class' : 'highcharts-series-'+str(series)})
d_iter = iter(list(soupd[series].children)[0].get('d').split())
d_list[series] = [[field, float(next(d_iter)), float(next(d_iter))] for field in d_iter]
return (d_list)
def rnum(m, x, b):
# Calculate number from regression
return (m * x + b)
def ascur(s):
return eval(''.join([gn.get(c, c) for c in s]), {}, {})
def main():
pass
main()
# url = "https://www.investsmart.com.au/invest-with-us/investsmart-growth-portfolio"
filename = "urlPageSaved.html"
soup = BeautifulSoup(open(filename,'rb').read(), "lxml")
yaxis = get_yaxis_labels()
m,b = regression(yaxis)
d_list = get_data_series(2)
# Calculate yaxis values from chart svg line coordinates
# xaxis is one value at end of each month commencing Oct 2014
# each row
for r in range(len(d_list[0])):
# each series
for s in range(len(d_list)):
d_list[s][r].append(rnum(m, d_list[s][r][2], b))
print(locale.currency(d_list[0][r][3], grouping=True), locale.currency(d_list[1][r][3], grouping=True))
# print(*locale.currency(d_list[0][r][3], grouping=True), locale.currency(d_list[0][r][3], grouping=True), sep='\n')
I'm not sure why I can't use requests to grab the data. i had to download the page to a file
Maybe the website is not allowing you because you dont have a useragent
hmm, I don't really know much about js. Only really understood that the content doesn't exist until it is created in your browser which I understand it the issue.
something like this : ```from bs4 import BeautifulSoup
import requests
import lxml
def get_link_data(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
'Accept-Language': "en",
}
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.content, 'lxml')
OK I'll look into that. What do I search for? BeautifulSoup agent ??
A fair amount of the site is secure scripts
but the download works to the cent.
in $15k
reconstructing with regression
Would I be able to pass soup.find('g', {'class' : 'highcharts-series-'+str(series)}) as an argument?
or something similar
The last double for loop is a bit of a train wreck too
The best way of using locale.currency has me a bit confused
!close
is there a way to hide all of the codes and stuff from the url of a formhttps://fsdfdsfsdfsdsdfsdfs/dsdfsdfsdffsdsdf?code=&id=742942218687479828&prefix=.&welcome=795853980932505611&announcement=743525344900022363&logs=802882486090072104&join=808200474674069514&voice=%F0%9D%90%8C%F0%9D%90%9A%F0%9D%90%A2%F0%9D%90%A7&ticket=tickets&mute=743201784327045130&auto=743099370039410719&helper=743095944018526381&dj=743203167587532851
Hello bro i have learned basics of django but i want to learn advance like how to insert data,deleting , edit and update ?
Learn the Python Django framework with this free full course. Django is an extremely popular and fully featured server-side web framework, written in Python. Django allows you to quickly create web apps.
π»Code: https://github.com/codingforentrepreneurs/Try-Django
βοΈCourse Contents βοΈ
β¨οΈ (0:00:00) 1 - Welcome
β¨οΈ (0:01:14) 2 - Installing to Get ...
just go to the section your interested in
how do i change what is displayed on the django admin page from email to a username
hi jakey
hi
go into the model and change the __str__ dunder method
class Model(models.Model):
def __str__(self):
return self.username
thanks
split_url = url.split('?')
domain_and_path = split_url[0]
query_params = split_url[1]
All query params follow the ? operator so split it there.
but would that hide it in the browser
is there an API available which can give me access to audio files of all songs ?,trying to build a web music player
like make it so its only domain/dashboard not domain/dashboard?sdfdsfsdfsdfsdfsdfsd
well from your example, you would be left with this https://fsdfdsfsdfsdsdfsdfs.com/dsdfsdfsdffsdsdf
ok
how would I tell the browwser to only return the domain
and not the query params
just keep splitting
yes I understant I have to split the domain and the query params but if the browser used the codes how do I change it from with to without the codes
what?
like how do I show the user the domain without the code
what code
in their browser
https://fsdfdsfsdfsdsdfsdfs.com/dsdfsdfsdffsdsdf without the stuff after the ?
split_url = url.split('?')
domain_and_path = split_url[0]
query_params = split_url[1]
Thatβs your domain root so just point it there
split_url = url.split('?')
domain = split_url[0]
query_params = split_url[1]
will that show the domain in the browser?
its not the root but that wont help I am trying to show a page just without the stuff after the ?
You need to understand what you are doing, here you are only splitting your URL at the ? character (splitting between your domain and the query params).
I donβt understand. Why is that stuff their in the first place? What are you doing?
like this
you see all of that stuff
I dont want it to be there but for the codes to still work
Ok so are you submitting a form? Making a request? What is it your doing
submitting a form
So use POST request to submit the form
Then the parameters will be sent in the request body
that data is there because you sent a GET request. Any data sent with a GET request are sent as query params...
Yeah
ok
Itβs just submitting data
You post data to some endpoint, from there you can get it from the request
I got a function that parses data, and it returns a JSON string, but I wanna use that in my POST data but it sends the literal string as part of the query params, how do I construct a request in Flask to send it "properly"
?
the data shows like the following in the request.
"β[31mβ[1mPOST /fetchmetadata/%5B%5B%22Return-Path%22%2C%20%22%3Cxxxxxx