#web-development
2 messages · Page 52 of 1
but why should I store the ID in the session
someone could just guess it
or look at the API which shows the user IDs
that way you can check if the user is logged in or not
you dont return the password on an API call. also your password is hashed even if they have the password its no good
yeah sure
i hope youre hashing your password
password is hashed
in the session store something like username or id that you can if needed query the DB
but I need some kind of token in there in order to verify if the user is authorized to view the page
and the user ID is publicly accessable
so?
so should the userID be the only thing in the session?
if so, an attacker could just look at the user id of another user, set that as their session and have access to all data of the other user
you can add other things as well but you also want something that can be used to query the DB
the only way to set the session is by loggin in
yeah
the session is set by the server not the client
yeah
even if the attacker has another users ID they cant really set the session to that ID
oh, is the session hashed?
yes there is a SECRET_KEY that you can set that is used by Flask to hash the session
ah, that makes sense
so when an attacker gets access to the DB/the file the SECRET_KEY is stored in, they'd have access to every user's data
yea i guess you could say that. but if the attacker can get access to the secret_key you would have bigger problems at hand
How i can login in Django admin if I created new project with PyCharm?
Can someone help me please?
ngl this server is popping
let's not speak off-topic here, mods like to keep to the rules
i created flask graphql api back in february, it has event-based databased design
like you can join and leave
something like likes and dislike, you can like and dislike a photo
Okkk
@nimble epoch it's a bit of different talk when it comes to comments
what if i comment on a comment
how would you store that
well, that would be a database flood, really :p
miguel grinberg made an article about nesting comments and such
I suckkkk😎
i would highly reccoment to read that article, he talks about it implementing 2 algorithms/methods if you can call them that
sending the article right now
Thnx
All about these stuffs?
@nimble epoch he talks about nesting comments, like reddit has
when you comment on a comment, someone comments on your comment etc
well, you can't really deal with it differently
It return None as fast as the options being rendered
Im @nimble epoch 😎😈👹
i mean you can but you would be making a query for every comment which can be very exhausing your database
Any ideas about how I can make the program wait until the user can choose his option?
@feral minnow what do you mean it returns none as soon as its rendered?
im guessing youre using flask-forms
you mean request.form?
no Flask-Form
Im doing it from html
so you are using request.form method?
yup
if request.method=="POST":
session["link"]=request.form["link"]
link=session["link"]
res=requests.get(link)
res.raise_for_status()
soup=bs(res.text,"html.parser")
Elem=soup.select("body > div.body-site > div.container.container-main > div.container-main-left > div.panel-story-chapter-list > ul a")
ChaptersName=[]
for i in range(len(Elem)):
href=Elem[i].get("href")
regexName=re.compile(r'chapter_\w+\.?\w*/?')
regexFind=regexName.search(href).group()
fullName=regexFind.replace("/C","",1)
fullName=fullName.replace("_"," ",1)
ChaptersName.append(fullName)
return render_template("manga.html",ChaptersName=ChaptersName ,link=link)
session["start_chapter"]=request.form.get("start-chapter")
start_chapter=session["start_chapter"]
print(start_chapter)
return render_template("manga.html")```
you are doing a big bazinga here, i see
bazinga ?
session["link"]=request.form["link"]
link=session["link"]
res=requests.get(link)
res.raise_for_status()
do you need to set up session every time?
if not, this can be done with 2 lines
I need it to another function
the select Element
I want the user to choose a chapter
then I get this value and do things to it
or the program*
i see 2 selects, which one are you targetting
both
that's gonna be real tough
oh
i would say take a look at flask_wtf and wtforms
if you rewrite that with wtforms you are gonna save yourself both time and reduce code complexity
if you continue to target forms with bs4, it's gonna be a big mess
One none important quesssttioon
@native tide quick question, aren't sessions supposed to expire after some time? when I have a static password and a static value to encrypt, the session cookie always has the same value and therefore it won't expire. Did I miss something?
Is like system like >>>
tags = db.Table('tags',
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True), db.Column('page_id', db.Integer, db.ForeignKey('page.id'), primary_key=True)
)
class Page(db.Model):
id = db.Column(db.Integer, primary_key=True)
tags = db.relationship('Tag', secondary=tags, lazy='subquery',
backref=db.backref('pages', lazy=True))
class Tag(db.Model):
id = db.Column(db.Integer, primary_key=True)
Nut with some differences
i already see symptoms of longlineivitis :))
@nimble epoch if it's pure sqlalchemy, folks over at #databases will probably know it better
@vagrant adder Im using bs4 to get something from another page then add them to options
No its flask_sqlalchmey
it's pretty similar
🙏
@feral minnow you are scraping data real time while serving site?
that sounds messy
does the site allow scraping?
I scrape it before if that what you mean?
so you make a request to flask, flask scrapes the site and gives back the response?
is that the process order right now
yup
that sounds really really messy
like illegal?
nope, just bad practise
making a request while handling one can be resource intensive
Ok @vagrant adder in Comment Replies the comment model has been related to itself but ....
What is a remote_side?
The id is added to it like a list type
And when adding commet
Is it parent or parent_id?
Oh oh ok thats in backref
But what is remote_side
What it does?
i think folks over in #databases can explain it, only thing i know it does is it helps with self-referential databases
Okk thanks
maybe this helps
How i can login in Django admin if I created new project with PyCharm?
hmmm I'm trying to use sse for loading status update for my react frontend
keep on getting this error MIME type ("application/json") that is not "text/event-stream".
this is my python code:
def publishLoadingStatus():
sse.publish({ "percent": "10", "message": "creating user directories..."}, type="update")
return { "status": True }
# return flask.Response({ "status": True }, mimetype="text/event-stream")
This is react code:
componentDidMount() {
this.eventSource.addEventListener('update', e => {
this.updateLoadingScreen(JSON.parse(e.data))
})
}
updateLoadingScreen(data) {
console.log("this function is called: ")
console.log(data);
}
interesting
tried the flask.Response(, mimetype=) but get a cors error, maybe my syntax is wrong? but not too sure
tbh.,, not sure what to put inside flask.Response() first argument
I'm going to setup a test application doing the same thing and see what I can get
thanks, really relaly appreciate it
been stuck on this for awhile now...
this.eventSource = new EventSource('https://api.server.com/events')
// this.updateLoadingScreen.bind(this)
}
componentDidMount() {
this.eventSource.addEventListener('update', e => {
this.updateLoadingScreen(JSON.parse(e.data))
})
}
updateLoadingScreen(data) {
console.log("this function is called: ")
console.log(data);
}
this is the semi-full react side code
yeah I'll just spin up the baseplate react app and put some stuff in
my frontend and backend are bothing running https
i dont think that sshould matter too much tho
so @smoky skiff is this the error you get? Access to resource at 'http://localhost:5000/send' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
(with different domains)
okay so, I can get everything working locally
@smoky skiff make sure you are connecting the event source to the URL you pass into the bit here:
app.register_blueprint(sse, url_prefix='/stream')
not the one that you use to publish events, otherwise it will break
are using flask.Response(mimetype=)?
hmmm, i got rid of the app.register_blueprint(sse, url_prefix='/stream')
cuz i wasnt sure how my endpoint pointing thing worked
that code basically says 'okay, clients connect to /stream and wait for events'
then you have an endpoint where you call sse.publish
sse.publish pushes that event to all the clients who are waiting on /stream
ahh okay
you'll need to add back the register blueprint bit
# @cross_origin()
def publishLoadingStatus():
sse.publish({ "percent": "10", "message": "creating user directories..."}, type="update")
return { "status": True }
# return flask.Response({ "status": True }, mimetype="text/event-stream")```
then in this app.route what is this doing?
if everything is waiting on /stream
ah so, that is just example code
when you visit /events in your browser, sse.publish will put an event on /stream
you do not
ah well
you do need that to route your users
because somewhere in your code you need to run sse.publish
you'll need to have something trigger the function but yes
so since im doing loading screen status sort of thing
im planning on exeuting this function with percentage argument
react will update the state with new percentage value
yeah, but something needs to trigger the function to be called on the API
so something needs to run publishLoadingStatus
when will publishLoadingStatus know how to start running?
that can be just ran inside the python script
lets say i have 5 function which are basially steps
it can, but something needs to start the functions running
aftter each complete just execute the function
the normal way of doing it would be websockets usually or a request from react saying "okay start the loading"
and then flask can run functions
because flask is a web framework it only really will run functions when it gets a request
yeah that could be it
so that react has something to tell the API that it is there and it is ready
no worries
the docs arent too great for sse
so i was veryt confused...
nnot much resource on online too
oh kay
it worked
@kind steppe Actually thanks so much
holy shit
No problem
If things get ridiculously complicated then there are alternate methods, either through websockets or even just AJAX polling
Access to resource at 'https://api.domain/stream' from origin 'https://domain.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
didd u also get this? how did u solve it?
the @cross_origin?
either that or the resource specific
hehe i do have cors enabled tho
app = Flask(__name__)
app.config["REDIS_URL"] = "redis://localhost"
app.config['CORS_ORIGINS'] = ['*']
app.register_blueprint(sse, url_prefix='/stream')
CORS(app, support_credentials=True)
im thinking error in my ode
just have CORS(app)
seems like it throw this error if i have error in my code
also support credentials is a bad idea
cuz its not able to reach the @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', 'Accept,Content-Type,Origin,Authorization') response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') response.headers.add('Access-Control-Allow-Credentials', 'true') return response
ah okay
try set app.config['CORS_ORIGINS'] = ['app.domain']
also, you don't can remove that after request thing, this should handle it all
If I set this: {'works':True} on python, then I send it over with http and receive it on js, will the True be a boolean so it is written as true or a string?
using what framework?
>>> json.dumps(True)
'true'
JSON specification means all booleans are lowercase, so I'd be surprised to see uppercase booleans
Say I received it using fetchapi and sent it using flask
Will it still be a bool?
So in this case
def data_to_jwt(data):
headers = {'alg': 'RS256'}
key = read_file('./privateKey.pem')
token = jwt.encode(headers, data, key).decode('utf-8')
return token
def get_cookie_data():
token = request.cookies.get('user')
data = jwt.decode(token, read_file('publicKey.pem'))
return data
if data contained a bool
it would act as as string?
no problem
😄
Hello everyone ! I have a question about the 400 error in Django.
@cosmic lantern cookies do indeed expire. and you can set expiration time on flask-sessions.

So using this class I am getting the following error
class User_Model(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
discord_id = db.Column(db.Integer)
username = db.Column(db.String(500))
email = db.Column(db.String(500))
subscribed = db.Column(db.Integer)
plan = db.String(db.Integer)
discord_status = db.Column(db.Integer)
profile_picture = db.Column(db.String(1500))
def __init__(self, discord_id: int, username: str, subscribed: int, plan: int, discord_status: int, email: str,
profile_picture: str):
self.discord_id = discord_id
self.username = username
self.subscribed = subscribed
self.plan = plan
self.discord_status = discord_status
self.email = email
self.profile_picture = profile_picture
TypeError: %d format: a number is required, not String
Full traceback
Any ideas on why that could happen?
I am not sure how to fix this
;D
@rustic pebble
plan = db.String(db.Integer)
should be
plan = db.Column(db.Integer)
happens to the best of us
😄
Resolve it via a link table
Like?
This page explains pretty well https://docs.sqlalchemy.org/en/13/orm/basic_relationships.html#many-to-many
I meant how can i work with api
So how to query with a many to many relationship?
Yeah
That wasnt what I expected
Ok ok
I think i got it
Thats working
Thanks though man
Go rest
Again a question
Imagine a user can like another user just once i gotta do something with my models or i gotta add conditions?
I cant process it🤨
Any selenium users here ?
@dusk zodiac Whatsup
@rustic pebble i am having hard time with this issue
From what I can hardly see you are missing the chromedriver
The chrome driver is there... the interpreter can load it
The executable of chrome browser is located in the path I wrote in the code, the error message says it can't locate it
hi all, I'm trying to make a website checker. I can get to the website on a normal browser but when I tried wget there's a 500 internal server error.
oh and GET brings back well something, background image is listed as a image/png; base64 data
does anyone have any ideas how to alternatively query the site that might work?
not sure if I the normal site would return something different then an error
Which are the biggest difference between flask and django? At first i did't know which one learn, but i red some articles on internet that say if you are a beginner in backend, it's suggested to start with flask. Now im learning flask, but honestly i don't really like it, often im confused and stuck. I would try to use django, just to try it, and see if I like it more than flask. i need to talk to someone (possibly in dm) about this. 😅
And why flask is suggested for beginners in backend?
Man man
Im stuck too
I have learned flask and djngo
But flask is easier and i think more fun
Flask with its extensions is great
@toxic marten flask has "do it yourself" approach
you aren't given a function that magically solves 50 problems, you get to tackle the logic at lower level and therefore refining your thinkin skills
and django is more batteries included
you get almost everything in the box, less stuff to fiddle
But i dont see any special thing with django
Django
Why?
I have worked with both man
Can we talk in dm?
@kind steppe back here again.. sorry bout that.. I was wondering if theres a chance uwsgi or nginx is blocking the connection to sse?
@smoky skiff https://serverfault.com/a/801629 regarding nginx, this seems to handle it nicely
I've read a bunch of different questions on what Nginx configuration is appropriate for SSE and came up with some confusing results regarding what settings to use:
https://stackoverflow.com/questi...
u think its nginx not uwsgi?
Hey guys I'm making a form in flask. There's a select field with the options 1 through 7. How can i make it so that depending on the users choice(1 through 7) that many string fields will be made for the next question on the form.
Youre using flask_wtf?
yes
I'm trying to make it dynamic. For example, so that when the user selects 3... 3 stringfields are available to write 3 courses
Okay no problem
@kind steppe hmmm doesnt seem to fixx it
now getiting timeout error
*14 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 69.172.162.104, server: api.io-powered.app, request: "GET /stream HTTP/1.1", upstream: "uwsgi://unix:///home/jason/io-backend/main.sock", host:
i think it has to do with trying to connect to redis-server
Guys how I can return a value from a selector Elem using flask?
@mighty herald youre gonna need some JavaScript magic.
listen to an on change event on the options and depending on the selected value create the required amount of input fields and append to the div
Anyhelp pls
So, I have DEBUG=True in my Django project, and I am using a ModelViewset to send serialize a model, and I am getting a 400 error when I try and post to this ModelViewset through the API. Is this a normal error, or have I done something wrong ??
for this https://paste.pythondiscord.com/ojoyilocil.py
returns
from: can't read /var/mail/flask_test```
I'm using latest flask and sqlalchemy. I've got an MofN relationship between Person and Event with a backref of attendance_records and I notice that when I inspect the variables I can see that person is the same as person.attendance_records[0].person and that this nests recursively all the way down, e.g. person.attendance_records[0].person.attendance_records[0].person.
Is this expected? If this scales to 100s of people and 100s of events is this going to cause a major resource hit?
is there anyone interested in jumping into a private project on github? It's a personal project whose purpose is to allow developers to get hands-on experience. The ideal candidate should have notions of how to work with git and github, and have basic knowledge of front-end technologies. Even if one does meet the requirements, please pm me should he/she be interested to know about the project.
Does anyone know how to setup PayPal subscriptions in a flask app?
I am getting a hard time implementing it
😦
Hi everybody, I'm new with Flask and I am struck with sqlalchemy to implement an one-to-many relationship. I have a models.py file and inside it I have many models like Group and Skill (I am implementing an api for my portfolio). A group can have multiple skills. When I try to import my db object (created in int.py ) in the python shell I get an error :
sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class Group->Group, expression 'Skill' failed to locate a name ("name 'Skill' is not defined"). If this is a class name, consider adding this relationship() to the <class 'portfolio.models.Group'> class after both dependent classes have been defined.```
Here is my code :
class Group(db.Model):
__table_args__ = {'schema': 'portfolio'}
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(255), nullable=False)
text = db.Column(db.Text, nullable=False)
activated = db.Column(db.Boolean, default=False)
skills = db.relationship('Skill', backref="group")
class Skill(db.Model):
__table_args__ = {'schema': 'portfolio'}
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(255))
logo = db.Column(db.String(255))
activated = db.Column(db.Boolean, default=False)
group_id = db.Column(db.Integer, db.ForeignKey('group.id'), nullable=False)```
Can someone tell me why Group can't find the relationship? Thank you in advance.
!codeblock can you use a codeblock to format your code please? thanks!
@jagged lark Yeah, sorry
I tried to send a message using flask_mail but it says:
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine activity refused it
Whats the reason?
Well
Well?
First of all, it is actively not activity, and second, are you sure that there are ports open to receive the email?
Yeah yeah
Obviously the target machine won't accept your request or is not reachable at all
Is it related to the MAIL SERVER
?
Could be?
Or port or sth?
Yeah man it was related to MAIL SERVER configuration in the app
Thanks though
Oh shoot
I am drawn into my flask app, I was having a huge problem setting up paypal, glad to see you fixed it @nimble epoch
😛
😉
hey everybody. About a year ago i started a project using Django Rest Framework. Im resuming it now and trying to run it, but I cant get python manage.py runserver
I really have no idea how i set up the project last time, would really appreciate some pointers. Similar issues ive found on stackoverflow talk about virtual environments and python3 which i am sure I did not deal with before.
My current python version is 2.7.17
my manage.py looks like this:
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cotizaciones.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
dont know what other info i can give but id be happy to if someone is willing to help 🙂
the error i get with python manage.py runserver is:
File "manage.py", line 14
) from exc
^
SyntaxError: invalid syntax
i really have 0 python knowledge except for the little django rest framework backend I did a year ago
raise x from y is a python 3 construct if I remember correctly
Yup, python 3 construct.
Python 2: raise_stmt ::= "raise" [expression ["," expression ["," expression]]]
Python 3: raise_stmt ::= "raise" [expression ["from" expression]]
I am creating a shop right now and I want the admin to be able to generate coupons through a discord bot.
Supposedly the discord bot sends a request with a coupon in its body
@app.route('/coupon', methods=['POST'])
def create_coupon():
data = request.json()
if data['key'] == 'NcJ92yVJtmmYUDAACF8WMCC':
new_coupon = data['coupon']
with open('./coupon.txt', 'a+') as coupons:
coupons.readlines()
exists = False
for coupon in coupons:
if coupon == new_coupon:
exists = True
if not exists:
coupons.write(coupon + '\n')
return {'coupon': new_coupon}
return {'coupon': 'There has been a problem registering the coupon.'}
@app.route('/check')
def coupon_check():
data = request.json()
user_coupon = data['coupon']
with open('./coupon.txt', 'a+') as coupons:
coupons.readlines()
for coupon in coupons:
if coupon == user_coupon:
return {'exists':True}
return {'exists':False}
would the first route successfully append the coupon to the coupons text file?
And if yes. When I did the check in the second route, would it return {'exists':True} if it found the correct one?
I really don't want to do this in the wrong way
@rustic pebble yea your first route should work fine. couple things id change would be to read one line at time rather than read the entire file. and just return after exists= True
I have changed it up a bit
👍
Thanks for answering tho
no prob.
Of all the errors that I've gotten since I started Python, sqlalchemy.exc.IntegrityError or something along those lines is probably my least favorite one to get. Basically the reason why is that it means "shut the server down, drop the entire database, attempt to get working whatever wasn't working exactly, create the table, repopulate the table with exactly the necessary data.... It's really probably the lamest process ever.
Is a good solution to this getting Alembic set up so that I can just migrate changes?
I think Im gonna set that up before I mess around with it anymore because Im tired of that above process.
The main reason why this sucks so bad is that I cant just crunch out the entire database in one go.
I tried to do that. What it results in is not being able to identify the source of why things dont work. Because its my first time I have to develop each part of it and because SQLAlchemy is frankly such a mess... learning to do each relationship is...
I just have to set up migrations haha.
Im sure that will make it a lot better
<!DOCTYPE html>
<html>
<head>
{% if title %}
<title>Flask Blog - {{ title }}</title>
{% else %}
<title>Flask Blog</title>
{% endif %}
</head>
<body>
{% block content %}{ % endblock %}
</body>
</html>
I am getting this error from jinja
jinja2.exceptions.TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'endblock'. The innermost block that needs to be closed is 'block'.
Ben Fenerbahçe’de çalışmayı çok istedim. Bundan da gurur duyuyorum. Fenerbahçe’den gitmek kolay mı? Ama kalmak da çok kolay değildi. Kulübümde kalmak için çok çalıştım. Bunun bilinmesini isterim. Ama şunu da unutmayın. Benim istifam teknik bir karardır. Ve tekrar rica ediyorum speküle etmeyin lütfen. -Ersun Yanal
@small crest you still get the error?
Yeah
that was the problem, silly me
<body>
{% block content %}{ % endblock %}
//^ that space caused an error
</body>
for anybody wondering: DO NOT MAKE THIS MISTAKE
tips from a fellow newbie
template languages make me cranky
jinja, e.g., kinda seems like it's just python. But it isn't.
Hey.... I'm starting on a new web application, and have been looking into using UUID so someone with the primary key can't simply go up or down one to discover new objects. However, from what I've read, using UUIDs as primary keys seems to make queries run a bit slower.
I was thinking of some hybrid approach to get around this where its "real" primary key is still an auto-incrementing integer, while an extra web_slug attribute can hold the UUID, that is both displayed in the url, and is what is queried when a new URL is requested.
Does this sound alright, or is there a better approach? My main priority is simply removing the ability for users to discover new objects by messing with the object ID in the URL. Thanks
I wouldn't worry about the slowness
I mean, try it and see
I will bet you won't notice
complexity is the root of all evil. Don't do the "hybrid approach" unless you're certain it's necessary.
@quasi ridge I will, thank you for your answer.
What is bulma and where can it be used?
I saw the video on their official website which says it is a css framework
But I don't get it, why would you need one?
Isn't css itself enough for that?
Also, is there a web framework like django or flask anyone would suggest me?
I feel like I'm living on the edge
@frank crater I've never used Bulma before but have used Bootstrap (another CSS framework) pretty extensively. CSS frameworks to web design are 3rd party libraries to Python programming. CSS frameworks define all kinds of components and building blocks that you would otherwise have to explicitly code yourself. This can save you a lot of time. Just like with programming in Python, its much more efficient to find a library for something you need done rather than reinventing the wheel yourself and spending the time building whatever. Hope that answers your question.
@native tide Thanks a lot mate! I'll try bulma for now, if I feel its not matching my needs, I'll try your suggestion; bootstrap
People speak pretty highly on both, depending on who you ask.
As for a web framework, both Flask and Django are excellent. One isn't "better" than the other, but rather are better depending on what you're trying to do.
But popularity is what I am searching for
They aren't popular without having some tight underwears
Flask is small, lightweight, and its basically up to you to build all of the systems up. Django is larger but takes the "batteries included" approach so a lot of functionality is directly included (orm, authentication, etc)
They are both popular
I've used both, if you're learning either the support online for them is fantastic. Any question you have has likely already been answered on stack exchange 1-5 years ago on the top of your Google search results.
@native tide Is there a tutorial series on django that you'd suggest me?
there is, one second
In this Python Django Tutorial, we will be learning how to get started using the Django framework. We will install the necessary packages and get a basic application running in our browser. Let's get started...
The code for this series can be found at:
https://github.com/Core...
if I had a friend new to programming ask me this same question, I'd tell him to learn flask first. If you don't understand any of the underlying concepts of how frameworks work, its not only a lot more difficult to understand whats going on with Django, but it doesn't really give you the right perspective in choosing one over the other for a given project.
with Flask if you follow Corey's other tutorial, you'll see step by step how to build a little web application with a nice assortment of features, along with a good understanding of the underlying architecture
and then with Django, it all comes together with all of its included features
the tutorial I'd recommend for Flask is this one: 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://githu...
all of the code is available for download in the description, so its very easy to follow along if you aren't making it alongside (which I recommend)
I have to go now, but I hope I helped you
whats a good db to use with flask?
Postgresql or sqlite
Thoughts on mysql? @rigid laurel
Can you read the values of HTML forms in a flask app (not flask forms) with python? Inclusive dropdown forms with <option> tags?
request.form @cold horizon
hey guys sry if I am inturupting. But I have a small question. I was asked to submit project at
You can submit via submit50 or, if comfortable with git, by pushing to https://github.com/me50/xWaterBottlex.git
but when I push I get this error
do you have an upstream set?
fatal: repository 'https://github.com/me50/xWaterBottlex.git/' not found
remote: Repository not found.
fatal: repository 'https://github.com/me50/xWaterBottlex.git/' not found
make sure our commands are correct
its origin
go to github and check if the repo name is correct
no I accidently named it arigin I guess
arigin https://github.com/me50/xWaterBottlex.git (fetch)
arigin https://github.com/me50/xWaterBottlex.git (push)
@native tide so request.form reads the selected <option> tag? Generally its able to read these with ease? Any advantage of forms created in flask instead of html?
flask-forms allow for you to add validation logic very easily
it does CSRF validation as well
go with flask-form
so @native tide from the above it can only be that the repo url is wrong right. I mean my procedures were correct right?
Its for an offline app, used internally. So validation is not that necessary. I know html forms very well thats why im asking.
yea you initialized your repo, create an up stream to github and then start pushing to it
ok thank you.
Hey was wondering something about SSE, once the user has connected to /stream Am i able to publish anything the frontend channel is listening to? or do i have to execute the @app.route("/somepath") everytime?
If a website owns an ssl certificate, meaning it loads on https. If someone tries to access it by typing http://example.com will they get redirected to https://example.com?
hwy I want to create a website
really basic
(new top py)
no html or CSS
But I know python
like intermediate
@shadow orchid I think you should at least have HTML knowledge to build a website with Python.
Also, does anybody know how to make a button to do something when it's clicked with Python flask?
@native tide you need to send a request to the server
I usually use fetchapi and add an onclick attribute to the element
Mhmm
Let me try and write an example for you
I think I need to find a toturial since it's hard to do it like that.
It is not that hard
<button onclick='send_request();'>click me</button>
async function send_request();{
let url = '/your_route_here';
const response = await fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
redirect: 'follow',
referrerPolicy: 'no-referrer'
});
return await response.json();
this makes a request to your route when you click the button
@native tide
This is Python?
This is html + javascript
you can embed it on your html by doing
<script>code here</script>
I don't think so
Maybe if you add a form and then make the button submit that form to a route
Example:
<form action='/your_route_here' method='post'>
<button type='submit'>click me</button>
</form>
This would do the same as the one I sent you earlier
But you wouldn't be able to handle the response
I see
Thank you.
Np
If I want to make web with flask or Django I must learn html and css or I can use bulma or bootstrap?
#Django
class Race(models.Model):
race_name = models.CharField(max_length=50)
When i create a second model and try to migrate it, i get the error that it needs a default. I get that i guess, but i have another model where this is apparently not required for the same field type. Anyone can explain ?
hey is there any way to send a post request to django from a external python script, I've tried it but I get a csrf token issue, I also tried the work around by using the decorator to disable csrf requirement for a specific function in the view, but I'm looking for a more secure of by the book method for achieving this
i'm doing a project where i build a website and talk about the history of html, css and Javascript
part of the marking guide is to use a wide range of elements . For me this is kind a vague as I'm pretty new to this. What would you guys consider to be a wide range of elements?
I'd guess it means use of semantic tags in place of divs everywhere. e.g article, section, navbar, header
ah righ thanks @rigid laurel
another question
I'm soo bad at design, how do you suggest choosing a font for my subheadings?
Just pick a font for the whole site
and stick with it
it might not look perfect
but it wouldn't be that bad
roboto is a solid choice
ty !
why is css so hard?
and html
i breeze through C and Networks but this is just whack
It's just nothing like those things. If you do it enough you can get better at it.
Also, I found a way around my problem of repeatedly needing to drop my database and add new users every time I make small adjustments during design (problem i complained about the other day)
from shellmancer.models import *
from faker import Faker
def populate_test_users(db, num):
fake = Faker()
for i in range(num):
if i == 0:
user = UserAccount(email="admin@admin.com", password="password", is_admin=True)
else:
user = UserAccount(email=fake.email(), password=fake.password(), agree_over_18=fake.boolean())
db.session.add(user)
db.session.commit()
def drop_create(db):
db.drop_all()
db.create_all()
Highly recomend.
I wouldnt normally use star imports but its only purpose is doing testing with my models so it makes sense here imo
I am having an error with Django Rest Framework, and it's a problem I was sure I fixed. Here is the error.
Could not resolve URL for hyperlinked relationship using view name "blog-detail".
But here is my code -->
serializers.py
`class BlogSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Blog
fields = ['blogger', 'date_added', 'blog_name',
'blog_post', 'blog_picture_context', 'url']
extra_kwargs = {
'url': {
'lookup_field': 'blog_name'
}
}`
views.py
`@method_decorator(ensure_csrf_cookie, name='dispatch')
class BlogViewset(viewsets.ModelViewSet):
queryset = Blog.objects.all()
serializer_class = BlogSerializer
lookup_field = 'blog_name'
def get_serializer_context(self):
return {'request': None}`
I should not be getting this error, but it literally just appeared back in the stack trace.
I fixed this error, and I have a Gist for anyone who may have come across this.
hi guys , i wont to install mysqlclient in python but it return error can help me
@gaunt walrus Can you post the errors?
yes
Hey @gaunt walrus!
It looks like you tried to attach file type(s) that we do not allow (.txt). We currently allow the following file types: .3gp, .3g2, .avi, .bmp, .gif, .h264, .jpg, .jpeg, .m4v, .mkv, .mov, .mp4, .mpeg, .mpg, .png, .tiff, .wmv, .svg, .psd, .ai, .aep, .xcf, .mp3, .wav, .ogg, .md.
Feel free to ask in #community-meta if you think this is a mistake.
Collecting mysqlclient
Using cached mysqlclient-1.4.6.tar.gz (85 kB)
Installing collected packages: mysqlclient
Running setup.py install for mysqlclient ... error
ERROR: Command errored out with exit status 1:
command: 'c:\users\user\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\user\AppData\Local\Temp\pip-install-4k6sbmbl\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\user\AppData\Local\Temp\pip-install-4k6sbmbl\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\user\AppData\Local\Temp\pip-record-0d3bwbam\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\user\appdata\local\programs\python\python38-32\Include\mysqlclient'
@static night You will need to use HTML and CSS. You will use Bootstrap in your html docs. There is a Flask-Bootstrap that can extension that can help, if you choose Flask.
i using django
@gaunt walrus Have you upgraded pip and setup tools in your environment?
pip 20.0.2 from c:\users\user\appdata\local\programs\python\python38-32\lib\site-packages\pip (python 3.8)
@elfin mountain yes
@gaunt walrus https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient
Download the wheel file and install.
@elfin mountain ok thankyou so much
Can someone help me?
how to use servlets witth mysql data base without IDE??
Hi, do you know why Django still renders admin templates from django.contrib.auth for builtin view after I set up my template dir via TEMPLATES['DIRS'] settings.py?
What is a good library to use to create a REST api?
what is better to learn Django or Flask
also which is better to make an online chat application'
@ me if u have answer, cause I am stumped on what to do
you can use Django with Flask
in fact I believe you use it by default
@small crest
@misty goblet What do you mean you can use Django with Flask? They are two separate web frameworks.
@small crest Don't worry so much about which one, just pick one and start learning. There is no better or worse for making a chat application.
I am just going to find the door :( (I got something mixed up there)
Guys anyone know how to return a value from a flask Selectfield form?
nevermind
I got it
I used form.choice.data
after 3 days of searching and asking people lol...Thanks @native tide
Hey so this is a pretty broad question, but Django or Flask?
Let me give more context. I'm a web developer with a workable competency in python, though I'm no pythonista. I currently have a node/express project that I'd like to port to Python. I've tried Django before, and found it to be great when I needed to do something it allowed, but it was a pain to configure and work around when I needed something more custom. I also really like it's admin panel, built in auth, and how it interacts with SQL. I don't know any flask, and while I typically prefer flexibility, this project I'm working on is fairly serious and I need to make sure things are done correctly, especially auth.
Django IMO. Flask is a BYO (build-it-yourself) in my experience. Django has everything there already.
Though it is more restrictive.
Yeah, that was my issue with it before. It just seemed really restrictive, and it seemed like I was constantly trying to find some workaround to do something that wasn't strictly within it's paradigm, and that was a pain. I'm just not sure if rolling out my own ORD, Auth, and Admin GUI (if I even do) would be less painful than dealing with Django's restrictions.
I doubt it.
The admin is one of the most powerful features of Django - literally 20 lines of code and you've got a frontend to your DB.
Not sure if there is even a contender let alone an equivalent in Flask.
I haven't used it enough to know, to be fair.
I mean I'm sure there are pip libraries. I don't know for a fact since I haven't tried, but in express there are npm libraries that help me set up a DB fairly quickly in what is otherwise a minimalistic framework. Definitely still isn't as convenient as Django is though.
Django also has amazing TDD support.
If that's the way you want to go.
Whereas with Flask you'd be managing the tests fully yourself.
That's actually very true, I forgot about that
@native tide I've used it for many projects, always wonderful to work with. I've never personally felt restricted by the framework though, granted, I've not made a "proper" project in it yet (working on one right now).
That's good to know, thank you. I'll probably go with it to be honest.
No problem. Flask is a really cool framework which I've enjoyed dabbling in, but I can't see myself writing a full project in it, though it has been done.
Anyone have any ideas on why a cookie gets disappears after redirect?
The whole Flask / Django argumentation: Two different projects with totally different goals, Django is more of a "batteries included" framework, Flask is more like "Batteries? Make your own batteries"
This makes Flask much more flexible, but also requires a great deal of development time to produce the same results as 30 lines of Django code could do.
It (Flask) also makes no (or very few) assumptions and is quite the opposite of Django's more pragmatic "one best way" philosophy in terms of ORM, frontend frameworks and the likes
@rustic pebble Depends on the redirect and how the cookie was set. when you set a cookie ti comes with a "scope" that's by default only the current url it's set on and any suburls, so that's probably what you're running into
yeah, for some reason, newbs (myself included) often come at Django/Flask with the idea that Django is harder. If anything its exactly the opposite.
I love certain features of Django so much that I lament not being able to have them every second that I use Flask. At the same time, Flask has taught me more about backend procedure. I think that nothing short of learning to use both of them makes sense after using both of them. Both teach me different lessons and bring different things to the table.
So I think if you're in a position of deciding which to use, it doesn't matter. Pick one. When you're ready, start the other.
I think if either or is your first web framework, there is no way thta someone explaining the difference to you will make any sense. thats why everytime someone tries, newbs come away with the wrong impression of what the differences are. At least thats my experience.
Hey guys
Hello
Can I ask some advice?
Do it. (I might not have answers but someone might)
Okay, thanks. I’ve been feeling conflicted about my thought process regarding some code. So in my teams project, we have leaflet map markers with only one category: cities. So I am thinking to use the default marker image and stick with that. If we had other categories like entertainment, weather, transit, etc, there would be other marker images. But we don’t. So I am hardcoding it to use one image only and the team lead is against it. He says it’s good coding practice to make the image field generic enough to where if we want to change the image (for different cities or categories), we can. Having that option goes against the integrity of the blueprint. I don’t see a use for having different image for each city marker (it’s tacky) and we don’t even have other categories. I feel he is making new rules along the way. Is it bad coding practice to make the image field constant if there is no plan to have it change?
It is generally bad practice to hard code anything, but it's also poor design to spend extra time making room for features that you arent going to use. At the same time, if your project lead things that you will need something, maybe he has plans down the road that you dont know about? Arguments get made for both approaches all the time and both have valid points. It depends on the circumstances.
Well he calls it hardcoding but it’s just using one basic image path in the JavaScript and that’s it. We wouldn’t manipulate it in the dictionary. He’s the team lead for a class project so the project will be done when the class is. There are no further features or versions of the app.
I just feel it’s unnecessary if it’s not usable
Ah, yeah thats a weird situation. At first I thought you were arguing with your boss for no reason and was going to tell you, "Maybe dont do that" haha
But in this case yeah...
Spending time on features that arent going to be used is a waste of time
Definitely 👍 and yeah wouldn’t argue with my boss at all 😂. Thanks!
Maybe you should cite the concept of agile development to the person you're working with as your reasoning
@forest aurora say that you understand why that would make sense if there were plans to do that because it would save time, but... also point out that spending time on features that arent being used is a waste of money
Of course in classroom settings
There is always the argument, "we are doing this to learn how to do it"
which is also valid...
That’s perfect reasoning. We learned about that this semester. The class is called introduction to software methodology. At the moment though, I just said “gotcha” and ended the argument. If asks why I didn’t do it, then I’ll explain. I think his ego is hurt and he is trying win in any way by making new rules or calling anything illogical “good coding practice.” @native tide
I think a regular thing you will encounter in the world of programming is trying to get people who are very rigid about things being done a certain way seeing when its not best to do it that way.
Personally its a thing I have to struggle with myself sometimes.
Its good to be aware of it as a programmer I think.
It’s definitely new territory and I gave myself high BP with his circular reasoning so that’s why just succumbed and ended the argument prematurely. I just don’t want to waste time on useless features just because I’m told to do so by the self-proclaimed team lead. I even told our professor about it and he said he’ll have individual phone calls with us since his rigidness, disrespect, along with superiority complex has been going on since the start.
Yeah, people like that typically do not do well being in charge. Its a common problem in classrooms because the best person for the job doesnt always get the job, because so often it goes to whoever is most likely to say, "I am the leader" and thats all it takes.
I actually didnt do programming in school.
But I remember that problem at school
I totally agree. My professor told me not to worry as my grade will not be affected by the lead’s evaluation.
How many years have you been coding professionally?
I didn’t realize before coming into the field that there are so many non-programming skills that are extremely essential to understand
Yeeeah, they say that the days of the asocial hacker who never leaves his room and relies on some business guy to make everything work financially are over.
lol
Haha definitely 💯 totally agree 👍
Now if only the days of the business guy who relies on programmers to do all his work would be over 😛
We’d become obsolete and jobless! Gotta keep them dependent 😂
@forest aurora You can create a dictionary that holds values category icon_url and then a function that builds the categories by taking input from the dictionary
That would mean that you would be able to add as many categories as you'd like without actually having to recode the same thing
Are you making this on flask?
No
React?
Well, actually whatever you use you should always consider CI(continuous integration)
Django framework
Which means making things easier and more agile to changes
Yea unit testing is pretty important although I usually hack my way through it by testing each different component individually
This is where React is good at as you build each element as an individual class or function
Would need to definitely learn that library
Heard it’s very useful
Plus easier than other stuff to learn
React is okay but you will get a hard time setting it up if you are not using an IDE. afaik PyCharm has built-in support for it, but for projects that involve react I use a WebStorm which is a similar IDE to PyCharm
If you want to go easy first and learn other the harder stuff later you should consider checking Vue.js
I am decent at react if you need pointers
my github @forest aurora @rustic pebble https://github.com/impetus1
Nice!
Ayyy thanks guys for tips and resources... will be sure to try to IDE and look into the github... appreciate it @rustic pebble @dry cobalt
Sure thing
I use PyCharm currently so should be a good transition
You have a Mac? Me too. I use vscode and vs for work atm
They have a MS full stack and prefer to use everything Microsoft
Doesn't really matter, your websites are going to end up in a linux container after all haha
😛
Lol true. I should get bootcamp for windows to try out the experience. Last time I tried it, it didn’t work and my computer never got its partition back
I'd rather use VMware
I have that too but stuff is slower on there like building apps and stuff. That’s what I’ve heard.
Well it depends on the app you are making
If you are developing on C# then windows is a must
Same goes for Swift
Mac is a must
Yeah my boss found some workaround for my Mac because he thinks VMware won’t be a fuller performance but my bootcamp never returned my partition so idk
Personally I believe a webapp nowadays should consist of the following. Backend bone in whatever language you want, Node + Docker is very good, web interface build on the framework of your choice, native windows app through C#, native mac app through Swift
I haven’t used docker but wanna try it
That is how I perceive fullstack nowadays. In our days almost anyone can pick up flask + markup and call themselves fullstack. That is not the case anymore
Well here is the essence of docker:
Person 1: Yo the website doesn't work..
Person 2: Hmmm, it works on my pc
DOCKER
Well once you deploy it you are going to need to ssh in order to use it
But docker is as simple as running a shell script
I see. Sounds cool. I’m really interested now. I just used AWS and I really liked that 👍.
I am building a metaengine for a game now and I will be using Kubernetes which is a docker framework in order to handle many requests almost at the same time
Yeah AWS is awesome
Niceee and yes it’s AWeSome
Make sure to check out AWS Lambda, I have used it in a few projects and it provides you with a stateless-ultrafast response environment
I will for sure. Thanks for all the tips and insight. I feel like I could learn a lot from you.
Haha, sure! Thanks
oof
Hi ! I'm new to Python ! Can we make website or game using Python 3 ( or in PyCharm maybe....) ?? Sorry for Stupid question, I just want to know orientation .....
Thanks
I'm I'm trying to push a boilerplate app to heroku to learn heroku...
I'm getting caught up here
remote: ERROR: Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r /tmp/build_efcd190cbdfc460c757ff45a1a85ce9b/requirements.txt (line 7)) (from versions: none)
remote: ERROR: No matching distribution found for pkg-resources==0.0.0 (from -r /tmp/build_efcd190cbdfc460c757ff45a1a85ce9b/requirements.txt (line 7))
remote: ! Push rejected, failed to compile Python app.
remote:
remote: ! Push failed
remote: Verifying deploy...
remote:
remote: ! Push rejected to virucount-stage.
remote:
To heroku.com:virucount-stage.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@heroku.com:virucount-stage.git'
(env) virufac@box:~/Projects/flask-by-example$ cat requirements.txt
click==7.1.1
Flask==1.1.2
gunicorn==20.0.4
itsdangerous==1.1.0
Jinja2==2.11.1
MarkupSafe==1.1.1
pkg-resources==0.0.0
Werkzeug==1.0.1
What is that pkg-resources about and why would it think it needs 0.0.0
I'm just gonna remove it
@vale cove you can make webservers that serve static web pages with python and we can make games with python with something like pyGame
okie
Is it hard to learn django or flask? I have done other style projects, and I know to do web development for static webpages. But now I am in a project where I would need to do login and third-party's login (like steam, instagram). Should I go with one of this two options, or do it with passports.js and node? My biggest concern is security
I'd look for the most complete 3rd-party solution you can find
@light oracle These 3d parties use OAuth2 which you can setup in 10 lines 🙂
Login with Facebook Login with Instagram Login with discord Login with gmail Login with Apple are all the same in the way you setup them up backend-wise
They all use OAuth2 protocol
Soo in these sense, they are the same. Still I don't know which one to choose
I have done many things with python (user-interface, web scraiping, discord bots, and scraping) but never done dynamic webs. It looks to me, that node is better or at least more used and easy acces to learn
Is it absolutely necessary to go through this every time
$ git push stage master
Counting objects: 3, done.
Delta compression using up to 12 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 312 bytes | 312.00 KiB/s, done.
Total 3 (delta 2), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote: ! Python has released a security update! Please consider upgrading to python-3.8.2
remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes
remote: -----> Installing SQLite3
Like that is just the process getting started. It seems like I already installed all that stuff, doing it every time I push seems weird
2020-04-07T16:29:03.796450+00:00 app[web.1]: SECRET_KEY = os.environ['SECRET_KEY']
2020-04-07T16:29:03.796450+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/os.py", line 675, in __getitem__
2020-04-07T16:29:03.796450+00:00 app[web.1]: raise KeyError(key) from None
2020-04-07T16:29:03.796451+00:00 app[web.1]: KeyError: 'SECRET_KEY'
How do I set environment variable on heroku?
heroku config:set SECRET_KEY=$SECRET_KEY --app appname lets try this
et work
I dont know why I ask questions in chat that I proceed to immediately answer myself.
hi i try to run this function in flask with "input" display in html (like a terminal but with a simple function) no success 😦 def monprog(): while True: command = input('> ') if command == 'hello': print('hi') elif command == 'exit': exit() else: print(command)
So, the user has no access to the terminal on the server... So you can't do terminal based input from a flask app because its running on a server somewhere removed from the user who only sees an HTML page served to them. You have to somehow display the form as HTML and then have it submit the input as a POST request to the flask app.
I use WTForms which makes it pretty simple.
Or am i missing something maybe?
yes i think that's it. My explanation was not very clear but I will try that
I am learning how to use git bash ...committing a new branch gives error untracked files present...how to tackle that?
try git add . which should track all files in the current directory. If you have files you don't want git to deal with, add them to .gitignore file so that you can continue to just add everything your directory without worrying about it.
if you have multiple directories to add git add * might be better
Pretty much every time you make a change you have to add those files to that list before commiting
Otherwise there is nothing to commit. If there are things going on in the directory that git isnt sure about when you try to commit it will tell you so that there arent inconsistencies going on
Hrm
Its cool, its usually something like that.
Gotcha👍👍
One thing
After the merge command we have to approve commit from git hub?
Can't be done using git bash?
To be honest, I dont have a lot of experience merging pull requests. Ive done it maybe one time ever. I just pull down and push up haha. Im sure you can.
See i ran the merge command and there is a new pull request shows up in git hub...but it's not commited yet so i have to create new pull request from git hub and merge
Hi, I am having a problem installing an SSL certificate in a Flask APP
Basically I am getting the following
[Tue Apr 07 18:34:21.505950 2020] [ssl:emerg] [pid 31437] AH02562: Failed to configure certificate ip-172-31-37-206.us-east-2.compute.internal:443:0 (with chain), check /etc/pki/tls/certs/server.crt
[Tue Apr 07 18:34:21.505982 2020] [ssl:emerg] [pid 31437] SSL Library Error: error:0906D06C:PEM routines:PEM_read_bio:no start line (Expecting: TRUSTED CERTIFICATE) -- Bad file contents or format - or even just a forgotten SSLCertificateKeyFile?
[Tue Apr 07 18:34:21.505991 2020] [ssl:emerg] [pid 31437] SSL Library Error: error:140DC009:SSL routines:SSL_CTX_use_certificate_chain_file:PEM lib
AH00016: Configuration Failed
2020-04-07 18:32:29,721 INFO spawned: 'httpd' with pid 31280
2020-04-07 18:32:29,784 INFO exited: httpd (exit status 1; not expected)
2020-04-07 18:32:32,472 INFO spawned: 'httpd' with pid 31288
2020-04-07 18:32:32,523 INFO exited: httpd (exit status 1; not expected)
2020-04-07 18:32:35,965 INFO spawned: 'httpd' with pid 31309
2020-04-07 18:32:36,016 INFO exited: httpd (exit status 1; not expected)
2020-04-07 18:32:37,018 INFO gave up: httpd entered FATAL state, too many start retries too quickly
2020-04-07 18:34:15,298 INFO spawned: 'httpd' with pid 31401
2020-04-07 18:34:15,351 INFO exited: httpd (exit status 1; not expected)
2020-04-07 18:34:16,356 INFO spawned: 'httpd' with pid 31429
2020-04-07 18:34:16,407 INFO exited: httpd (exit status 1; not expected)
2020-04-07 18:34:18,411 INFO spawned: 'httpd' with pid 31433
2020-04-07 18:34:18,461 INFO exited: httpd (exit status 1; not expected)
2020-04-07 18:34:21,466 INFO spawned: 'httpd' with pid 31437
2020-04-07 18:34:21,518 INFO exited: httpd (exit status 1; not expected)
2020-04-07 18:34:22,519 INFO gave up: httpd entered FATAL state, too many start retries too quickly
Both of these blocks happen many times
I am really not sure what I have done wrong
I also have a slight problem.
This is the example of setting up alembic that Im using.
https://realpython.com/flask-by-example-part-2-postgres-sqlalchemy-and-alembic/
It makes a foot note that its using flask_script, which is no longer needed because there is now a CLI built into Flask.
But for the purposes of the above example, can I just remove everything related to flask_script?
import os
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db
app.config.from_object(os.environ['APP_SETTINGS'])
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
@native tide Yes you can
Actually, they way you are using it
It might not be possible
Well I just copied that from the article. It specifies that its using an old way of doing it
🤷♂️
I kind of just wonder what the new way is
I'm so excited to have migrations set up
wordcount_dev=# \dt
List of relations
Schema | Name | Type | Owner
--------+-----------------+-------+----------
public | alembic_version | table | postgres
public | results | table | postgres
Pretty cool. Looks like it will work exactly like Django now. Im excited.
Anyone experienced with Django?
yes - if you have a question, just ask it
Hello
I am trying to turn a python script into a web service
I would consider my knowledge in general python intermediate
but I have no clue how to transform it thoo
This .py file I intend to deploy as REST api
doesn't intervene with a database
it just takes in a server IP and a zip of textual files I intend to preprocess to extract content and metadata
anyone could help please
Flask is probably what you want to be looking at
what about django ?
Django is more oriented around CRUD apps than Flask is
and as you don't need a database
I don't think its a great fit
although it probably would work
DRF would work yes - but you're getting a lot of features you don't need to use
such as ?
thank you
hi all, i need help with Django. I'm doing some tutorials and I'm stuck at the start of tutorials. I don't what I did wrong but I keep getting errors even though I checked and it's same as tutorials code. Anybody?
quite a noob to add on this
is this even the right channel to ask for help?
@hardy silo Yes, this is the correct channel.
I did find the answer. I was doing creating ForeignKey to another class/table and, even though tutorials didn't use this, I googled and found out that I should add on_delete=models.CASCADE
what is this code?
how come tutorials didn't apply it? django updated this?
I'm in process of getting along with stackoverflow, sry for bothering you with this
No problem. Any confusions/questions?
one question, probably not that smart one
No such thing as a bad question.
if I use SET(...) instead of CASCADE - for example if I delete post "message" and I want to keep that post, i can use SET to set default "message? for example: "this post was deleted because of reasons"?
hosts
I believe I saw some options in cpanel for this https stuff, when you install certificate. i used Let's encrypt, it's free
try
What are you trying to do?
How to access cPanel
You can access your cPanel from your User Area -> My Accounts tab -> Go to cPanel button. This will automatically log you in the cPanel of your accou
if I use SET(...) instead of CASCADE - for example if I delete post "message" and I want to keep that post, i can use SET to set default "message? for example: "this post was deleted because of reasons"?
@hardy silo Sorry, missed the message. It's definitely possible to keep the post, but most likely you won't have to do the queries as Django will do it for you, if that's what you mean.
Good answer for me, i think i understand now. One more thing i have to do, try it myself. Tnx 😉
@hardy silo Sorry I couldn't answer in more detail - quite difficult without understanding the components being worked with.
No need to apologize. You were quite helpfull. I'm at the beggining of tutorials, long way to go.
Hey I'm watching this video https://youtu.be/3fDy_CKO-hI and for some reason the code doesnt work for me, it's being buggy
Thanks for watching! If you enjoyed the video please be sure to like and subscribe for more videos. Have any ideas for me to make a video on? Let me know and I will most likely make a video on it!
Video Resources:
Visual Studio Code - https://code.visualstudio.com/download
...
I'm not going to watch a video and transcribe code from it to help you.
paste the code here, or get someone else to help
@heavy ibex Please put the code here so we can see what is the problem
I'm having trouble with migrating my database on heroku. It works on the local server but on the staging server it doesnt.
I'm sorry if this is a lot of info, I just dont know what it could be that would lead to answer.
(venv) virufac@box:~/Projects/shell_hacker_game$ heroku run python manage.py db upgrade --remote stage
› Warning: heroku update available from 7.39.0 to 7.39.2.
Running python manage.py db upgrade on ⬢ sdfdsafdsafs... up, run.9750 (Free)
INFO [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO [alembic.runtime.migration] Will assume transactional DDL.
(venv) virufac@box:~/Projects/shell_hacker_game$ heroku psql --remote stage
› Warning: heroku update available from 7.39.0 to 7.39.2.
--> Connecting to postgresql-clear-asdfdasfdsafdsafdsaf
psql (10.12 (Ubuntu 10.12-0ubuntu0.18.04.1), server 12.2 (Ubuntu 12.2-2.pgdg16.04+1))
Type "help" for help.
dsfdasfds::DATABASE=> \d
List of relations
Schema | Name | Type | Owner
--------+-----------------+-------+----------------
public | alembic_version | table | nbwcmytpvtdpir
(1 row)
You can see here that after migrating there arent any changes. In fact, the only reason this doesnt error saying that it cant find the empty migrations/versions/ directory is because I touch migrations/versions/.somefile to make git track it and upload.
When I check the logs to see what causes the error when I attempt to use the database
stagemancer::DATABASE=> \q
(venv) virufac@box:~/Projects/shell_hacker_game$ heroku logs --tail --remote stage
2020-04-08T00:44:54.821422+00:00 app[web.1]: sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "user" does not exist
2020-04-08T00:44:54.821423+00:00 app[web.1]: LINE 2: FROM "user"
This shows that the models are not being migrated.
But over here on the dev server everything runs fine
shellmancer_dev=# \d
List of relations
Schema | Name | Type | Owner
--------+----------------------------------------+----------+----------
public | alembic_version | table | postgres
public | campaign | table | postgres
public | campaign_campaign_id_seq | sequence | postgres
public | character_sheet | table | postgres
public | character_sheet_character_sheet_id_seq | sequence | postgres
public | gamemaster | table | postgres
public | player | table | postgres
public | user | table | postgres
public | user_id_seq | sequence | postgres
You might be interested in this
(venv) virufac@box:~/Projects/shell_hacker_game$ heroku config --remote stage
› Warning: heroku update available from 7.39.0 to 7.39.2.
=== stagemancer Config Vars
APP_SETTINGS: config.StagingConfig
DATABASE_URI: sqlite:///test3.db
DATABASE_URL: postgres://sdafadsfdsafdsafdsaf:sadfdasfdsafdsafdasfdsafdsafdsafdasfds@sdafdasfdsfdsafdsadsa.amazonaws.com:5432/dsdafdsafdsafdsafdsafdsa
SECRET_KEY: dsfdsafdsafadsfdsa
Note that, having the DATABASE_URI: sqlite:///test3.db is a mistake. I dont know how to remove that. The app isnt using it.
Also note that everything sensitive has been (hopefully) replaced with dsfsafsdaf
What is going on?
I'm working on a djnago based web site and I wanted to implement a autocomplete feature in a textbox. After some searching I found that I should either data list of possible string in a JS list of I should use tries. I wanted to know how to implement this from a django perspective
I figured out the answers to my problem. All it took was dropping my database and starting over.
TBH, I am fearful of the day when simply dropping the database and starting over is not an option. That's how I fix so many problems.
@lilac root you pu the the JS to do it in your static directory and load it up in your template and run it.
Django is for backend. It can display the form. It can send the contents of the form to the server. It can render something on the server based on that and send it back to the user.
But if what you want is some interface quality of life feature in the browser, your only answer is JS
or often CSS but not in this case
Think about it this way...
If you want something to happen on the page that doesnt involve moving to another page or redirecting to display the changes, you need CSS or JS. IMO you would preferably use CSS for anything that CSS can do, and JS for anything it cant
https://github.com/GoogleCloudPlatform/flask-talisman Im thinking about using this to enforce SSL
I hope it works
Use nginx rather
The limitation is working through heroku.
As far as I know, the only way to do it is at that application layer
Guys I want to create something which let the user download something . So If he did he will not be able to download another thing for an hour...I can do this with flask?
Yeah you could do that. If you wanted to do it without forcing them to make an account, you'd probably do it by IP (which they could get around just by tunneling, but it takes a smart user to do that). You could make it even more difficult by forcing them to make an account, but thats up to you.
I'd probably search to see what methods people are using to get the best results, but yeah flask can do that
oh ok I don't think i will create a login page because the goal of the website is just to let the user to download his thing then he can leave
@feral minnow Restricting the functionality of your site to make people pay up is a stupid idea
let's not pretend
this isn't my first day
It sounds a lot like one of those shitty share sites where you have to pay to get more downloads once you have downloaded something or get a stupid restriction which you can remove with your credit card
If the functionality of your site is downloads, then don't restrict
make the user stay
so i embedded a forum on a github page but the forum doenst show
nope and nope and nope... I didn't say something about I want the user to pay anything
And I will not do it
Then what is the goal of restricting a download to once an hour?
who will pay for something that a lot of other website offer
Its to control the downloading thing
I think if you have limited bandwidth it makes sense.... Like if its your little app that will get shut down if people are using it a lot.
Otherwise I agree with scorch
Eh, traffic is not expensive
I don't see the point of it
My VPS costs 2.98€ if I wouldn't get it for free and it includes 20 TB
so, why annoy a user with a restriction when it's so cheap?
Your VPS costs how much? Where do you have this at?
the VPS I have seen are pretty expensive. I havent exactly shopped around
But I definitely have looked at the plans and thought "Wish I had money for that"
where you host your app??!
@native tide There are options out there, but this a really small one with 1 vCore and 2gb ram
I only use it as a jump server for home office
so its not good
my point was the traffic though, not its computing prowess
I think i have to do the 1hour thing
I might have to look into that. I like the idea of having one a lot
@native tide 1 vCore, 2 GB RAm, 20GB NVME SSD, 20TB Traffic and 0.0004 / h computing
anyway thx guys and @tired root if you try to relax and ask what the person is trying to do this would be better😀
I am relaxed
I just oppose control through restriction
And you are losing users by doing that in the future
but if you want to do it that way, then more power to you
Do you think if you send too much requests to another website with no time to cool down this will be good??!
Oh you are talking about web scraping. Say that :P. Well, depends on if you breach their TOS....
Also, you can use caching methods
and make sure to use the ETag header
then you simply get a 302 if the data hasn't changed
Well I didn't find any TOS... about the second thing whats is it?
The ETag or entity tag is part of HTTP, the protocol for the World Wide Web. It is one of several mechanisms that HTTP provides for Web cache validation, which allows a client to make conditional requests. This allows caches to be more efficient and saves bandwidth, as a Web s...
what about caching methods?
cache popular content on your end, but again, that depends on what you are delivering
in case of your tube videos it is probaly not legal
Anyone familiar with flask socket?
socket.emit('update', data={ "message": "Hello this is the message", "percent": "10" }) socket.sleep(0)
I'm trying to emit a response at certain point of my function
emitting event "update" to all [/]
a69ccc7849b8483891571dc88d9ac14f: Sending packet MESSAGE data 2["update",{"message":"Hello this is the message","percent":"10"}]
This is what I get in logs... but my frontend isn't receiving this emit
socket.on('update', (data) => {
console.log("is this even getting called")
console.log(data);
})
Today, I finished going through the Flask blog tutorial. Really happy with the results, and the framework in general. Going to go through their "ideas to continue" list at the end and make Flaskr into something of my own
so, I'm using flask
and flask-socketio
for server
and javascript socket.io.js for client
<input type="file" id="application-icon" name="img" accept="image/*">
I have this input
And I want to emit the file
Maybe something like
socket.emit('send the file over event', { file: $('#application-icon') })
I've searched all over but I couldn't find any way to do it through socket.io.js
And no way to receive it through flask-socket-io
Should I just use POST requests?
@quiet mirage Great man and yes flask is amazing keep going
Thank you, def appreciate it. Been wanting to put a website together for the longest
print(response.text)```
for some reason when I run this code response.text prints just a long string of characters that look like this Z3ғڋ#R�z Tgb���ן>���M��^N��$��S�ܑ�O}=�o�fx~t�;��L��N�?nG�X�z"��7
does anyone have any solutions?
you are trying to send a request to a website?
@somber fiber you can try requests
response= requests.get("https://www.sneakersnstuff.com/", headers=headers)
you have to import it first
JavaScript is hard and I hate it.
I just need to get a book and read it, from the beginning, instead of just trying to use it.
This is Javascript to me
(function () {
.wgfdsafs => function ([$bullshit, $poop) {
})];
) function () { someOtherStuff;
)}();
And im just like what the fuck is all the punctuation
lol
python is the best(:
Its better when its able to do the job but its not always.
I need to just use vanilla, any time I need JS, and stop trying to use these frameworks.
The thing is, when I started Python, I enjoyed every moment of it. All the little details from the beginning, it was so fun for me and interesting.
JavaScript is literally a means to an end.
I hate every moment I have to touch it
So I try to skip things and make it worse.
I just need to learn it better and deal with it
I do have feelings for Python.
for me I just learn some html and css for the front end and everything else is from bootstrap (:
ya its amazing
If I had to describe my relgiion, I would say Python.
I love it
I know HTML and CSS pretty well.
I am building an electron app but one of the modules that I am using requires NODE v8.11.3 Electron was built using v12.13.0
When I install electron I get this error:
Is there a way I could get around this?
I have no problem there
hey y'all can anybody of you have a look at #help-popcorn ?
idk if it fits in web-development. i have a problem with requests and beautiful soup
@native tide the Elem is returning None
but it prints keywords
can i see the value of it?
print(keywords1) returns e.g. this: Metallzuschnitt, Kunststoffzuschnitt, Blechzuschnitt, Metallkonfigurator, ProKilo
oh so what are you trying to do?
well i want to crawl websites and take their keywords and append them to a list
so i do a request, take beautifulsoup to extract the content and then i want to append it to 'data'
this is a traceback to the code that i posted in help-sodium:
Traceback (most recent call last):
File "C:\Users\LuMi\AppData\Local\Programs\Python\Python38-32\Lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\LuMi\Desktop\Programming\saas\flask\routes.py", line 723, in run
worker(url)
File "C:\Users\LuMi\Desktop\Programming\saas\flask\routes.py", line 733, in worker
keywords1 = soup.find("meta", {"name":"keywords"})['content']
TypeError: 'NoneType' object is not subscriptable
Metallzuschnitt, Kunststoffzuschnitt, Blechzuschnitt, Metallkonfigurator, ProKilo
notice how it says typeerror even though it prints the keywords
yes
i want to accumulate from different websites and they all shall append them to data
data.append(key)```
but i have different threads that all write into data
thats why i use acquire and release so that they do not interfere
do you think it is a multithreading problem and not related to the BeautifulSoup?
give me a sec
Im not sure what are you trying to do
does strip return a value??
yes
i think
remove the ['content'], only do that after checking its not None
Guys anyone know why if form.validate_on_submit():
is not working
and here's the flask class form
Link = TextField("Enter the manga link here")
startChapter= SelectField("Start Chapter", choices=[])
endChapter= SelectField("Start Chapter", choices=[])
submit= SubmitField("Choose")```
I have a csrf_token at the html file
any help?
@feral minnow still have problem with your form?
@nimble epoch yup
help
anyone here using FastAPI for webapps development ?
So I have a python script that I want to run on my device that I'm hosting a rudimentary django server on. I'm trying to get a button on my webpage, via javascript, to cause that python script to run and do its thing. I've figured out that it looks like I need to make an ajax request, but I can't figure out where to go from there. Pretty much all documentation is based around sending some info to the server and then getting some info back, and the documentation kind of explains all of that in detail, but that's not what I'm trying to do. I'm just trying to run a script on the machine.
What is this called? Like what are the keywords for this issue so I can google search them and at least get a lead?
Please @ me if you decide to respond. Thanks <3
Also posting this in a help channel, cuz I figure this channel is dead this time of night.
Anyone uses Xpath helper extension in chrome?
what is the best framework for backend use
hi team I need a little help with django models if anybody here is willing 🙂
I have 3 models from django.db import models, connection
class Users(models.Model):
username = models.CharField(max_length=30)
def str(self):
return self.username
class Buch(models.Model):
name = models.CharField(max_length=4)
user = models.ManyToManyField(Users)
def str(self):
return self.name
class AdmList(models.Model):
adm = models.CharField(max_length=30)
bukrs = models.ManyToManyField(Buch)
user = models.ManyToManyField(Users)
def str(self):
return self.adm
and i need a hierarhical view, in other word dependant dropdown query... What do you think..
Guys anyone know why if form.validate_on_submit():
is not working
and here's the flask class form
Link = TextField("Enter the manga link here")
startChapter= SelectField("Start Chapter", choices=[])
endChapter= SelectField("Start Chapter", choices=[])
submit= SubmitField("Choose")```
I have a csrf_token at the html file
you dont have any validators?
you'd need to import from wtforms.validators @feral minnow
Hey, anyone familiar with progressive web apps and flask? I added the pwa logic to flask-cookiecutter app, and it seems to mess with form submit logic
As far as I can tell, with the PWA enabled the login form submit sends a GET instead of POST, causing the page to refresh instead of checking user login
@surreal tangle did you add it like:
if request.method == “POST”:
.....
elif request.method == “GET”:
....
the login route is unchanged from flask-cookiecutter:
@blueprint.route("/", methods=["GET", "POST"])
def home():
"""Home page."""
form = LoginForm(request.form)
current_app.logger.info("Hello from the home page!")
# Handle logging in
if request.method == "POST":
if form.validate_on_submit():
login_user(form.user)
flash("You are logged in.", "success")
redirect_url = request.args.get("next") or url_for("user.members")
return redirect(redirect_url)
else:
flash_errors(form)
return render_template("public/home.html", form=form)
sorry, pasted wrong method
No need to add request.form in the form
@nimble epoch so yes, the POST/GET as you wrote
And add a if request.method == “POST”:
