/r/flask
Flask is a Python micro-framework for web development. Flask is easy to get started with and a great way to build websites and web applications.
Use [Ask Flask] or [AF] if you have a very specific problem and need help with code.
Use [Extension-name] if you are discussing a certain extension to Flask.
Also check out /r/python or /r/django
/r/flask
I am looking to start hosting a web application of mine on an official web domain and need a little help. Right now, I have a full stack web application in JavaScript and Flask with a MySQL server. Currently, I run the website through ngrok with a free fake domain they create, but I am looking to buy a domain and run my app through that .com domain. I also have a Docker environment set up to run my app from an old computer of mine while I develop on my current laptop. What exactly would I need to run this website? I am thinking of buying the domain from porkbun or namecheap and then using GitHub and netlify to send my app code to the correct domain. Should I be using something with docker instead to deploy the app given I have a database/MySQL driven app? Should I use ngrok? Any help explaining what services and service providers I need to put in place between domain hosting and my Flask/JS app would be appreciated.
Which of the two ways is correct?
SECRET_KEY = os.environ.get('SECRET_KEY') or 'myKey'
or
SECRET_KEY = os.environ.get('SECRET_KEY') or os.urandom(24)
I was hoping someone could help me, I am new to flask. I am trying to implement a webrtc stream for a one way CCTV/rtsp monitoring system. I chose flask because I am using computer vision for security and also training and/or deploying AI models was the goal for this project. I just can’t find a project anywhere or get any type of AI to help me properly configure it all to work for one way, server to client streaming. I am also a newb to programming, just a hobbyist. Right now my repo is private because I have personal info in some of my code that could cause vulnerabilities, that I do not want to share. But I was wondering if anybody out there has a public repo that was good for one way WebRTC streaming and that actually functions. I’m not trying to video and voice chat, just view a security camera’s stream. I had it working with HTTP but it was absolutely horrible frame quality. It was like slow motion and you had to refresh the page. So I want to try WebRTC so freaking bad lol. I guess I could ditch flask for something else but I know Python the most and a little bit of node on the side… Help!
Hi everyone,
I’m new to Flask and want to work on some beginner-friendly projects that can help me improve my skills while staying manageable for a learner.
I’d appreciate any suggestions for projects that:
Cover basic Flask features like routing, templates, and forms.
Are practical or fun to build and learn from.
Can be expanded with additional features as I progress.
Thanks a lot for your ideas and guidance!💗
Thanks to the holidays I've managed to find the time to get heads down with learning a few new things and I'm sharing this latest example of converting the Flask blog tutorial project into a single page application with HTMX.
This was more challenging than I thought it would be, mostly because my templates became increasingly more difficult to read as time passed. This example could be cleaned up more with the use of macros, but I thought it would be best to keep most of the original code intact to compare this with the source example better.
My biggest takeaway from this project was the concept of out-of-band swaps for updating other parts of the HTML outside of the original target.
HTMX is a great tool and I'm happy to see it getting more traction.
Hi,
I'm recently building a hobby project backend which uses domain driven design and clean/hexagonal architecture. I'm pretty new to domain driven design, so I'm reading about it and trying to implement it. I'm using google and perplexity to get understand the concepts, clear my doubts and get different perspectives when trying to make a choice between multiple implementations. Now, I'm looking for a open-source project that makes heavy use of DDD implementing things like event sourcing, etc so I can get a better understanding of the implementation. Does anyone know any good github repos which implements Domain driven design which I can use as reference?
So I've created a flask app and I've hosted it through python anywhere. I want to learn how to create and intranet. Any resource or guidance on how I can make a web app that can only be accessed on a specific network? I know this may not be a flask specific question but that my background.
Since Google AppEngine is already a container and I will need to install OS dependencies like Microsoft Visual C++ 14.0 for python-Levenshtein-wheels on Windows (if I want to develop in windows). I don't see any advantage on "dockerize" my project. Am'I missing something?
Edit: Just to clarify "When installing the "python-Levenshtein-wheel" package in Python, you might need to install C++ build tools because the package often includes a compiled C++ component that needs to be built during installation, and your system needs the necessary compilers and build tools to compile this component from source code." Extra build is neccesary while enabling this dependency so is harder to create a truly portable docker image. You will need some different OS dependencies in linux to enable this dependency.
Hi, my workflow would be such that flask-assets would detect any changes in my less files and automatically restart the flask server and rebuild the assets. Relatively easy frontend development.
I loaded up an older project and reinstalled dependencies to current versions and noticed this funtionaliy changing. While the static files do update on a restart of the development server, the server does not detect changes to less file. Any suggestions on what would be causing this? Running flask 3.1 and flask assets 2.1
Im doing a learning project trying to set up a flask app with https on my home network and make it available online. Im using a asus router and set up ddns with a asus provided domain name and port forwarding. This part works with http.
How would i go about making this work with https. In the asus router settings for ddns i have generated key and cert.pem from letscencrypt (for the domain i guess?) But how can i configure the flask app to use this?
What I want to do is add a LaTeX button when using flask CKeditor in a form. Then I want to get the ckeditor value in the column from a database and display the jinja db column in the html file so the LaTeX typed equations display.
I also require the LaTeX extension to be free. I think https://www.mathjax.org/, would be good for the LaTeX button. But other free LaTeX can also work if anyone has any suggestion.
Here is what I tried.
I am trying to render {{post.content}}
in html when using flask ckeditor with flask wtf but the problem is I am getting a character like  
. Below is a better example of what I am talking about . <p>zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz</p> <p> </p> <p>zzzzzzzzzzzzzzzzzzzzzzzzzzzz</p>
.
How do I fix this so it displays in html using jinja like it is in flask ckeditor form? I just wanted to add the extra character like   is caused by the flask ckeditor form.
(Also I may have mistyped one of the variable names because I changed some of the variable names to simplify this example. Also I just want to reiterate this works I just getting extra characters.)
Here is the code.
models.py
class Post(UserMixin, db.Model)
# Here is the column in the class in models.py
content: Mapped[Optional[str]] = mapped_column(Text(), unique=True)
forms.py
class CreateContentForm(FlaskForm):
# todo change to create_text
create_content = CKEditorField('content', validators=[DataRequired('content is required')])
submit = SubmitField('Submit')
routes.py
@postroute.route("/create_post_content", methods = ['GET', 'POST'])
@login_required
def create_post_content():
form = CreateContentForm()
if form.validate_on_submit():
content_form = form.create_content.data
post_db = db.session.execute(db.select(Post).filter_by(contnet=content_form)).scalar_one_or_none()
add_post_content = Post(content=text_form)
db.session.add(add_post_content)
db.session.commit()
flash('You have created new content for the post successfully.')
# redirect somewhere
return render_template('create_post_content.html', title='create post content', form=form)
post.html
{% extends "layout.html" %}
<!-- get the error message from wtf forms -->
{% from "_formhelpers.html" import render_field %}
{% block title %} {{title}} {% endblock title %}
{% block content %}
<!--
get the error message from ( "\_formhelpers.html" import render\_field)
and make the error message from wtf forms show up on the screen. %}
\-->
<!-- I am not using bootstrap becauase it screws up ckeditor -->
<form action="" method="post" novalidate>
<!-- Make the secret key work -->
{{ form.csrf_token }}
{{ render_field(form.create_content) }}
<input type="submit" value="Submit">
</form>
{{ ckeditor.load() }}
{{ ckeditor.config(name='create_content') }}
{% endblock content %}
_formshelpers.html
<!--creates function that show the functions name and the error in flask wtf forms -->
{% macro render_field(field) %}
<dt>{{ field.label }}
<dd>{{ field(**kwargs)|safe }}
{% if field.errors %}
<ul class=errors>
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</dd>
{% endmacro %}
layout.html
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<!-- CSS -->
<link href="{{ url_for('static', filename='css/style.css') }}" rel="stylesheet">
{% if title %}
<title> flashblog {{+ title}} </title>
<!-- The title will say home -->
{% else %}
{{ 'home' }}
{% endif %}
</head>
<body>
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<!-- include the navbar which contains the searchform -->
{% include 'navbar.html' %}
{% block content %}
{% endblock content %}
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
</body>
</html>
Here is the full error.
I am using vsc and windows 11 and powershell in vsc to run the code. Also this is just a development server.
Here are the docs for flask session https://flask-session.readthedocs.io/en/latest/ .
Hello, I wanted to make a simple image hosting application. I created some endpoints and tried to verify it using Postman to send some requests. The register and login endpoints are working, but the upload endpoint, which requires user to be already logged in doesnt work (as if this particular info is never stored). In the header the Cookie Key seems to be the same in the Header but I still get 401 error. Here is my code:
# Login
@app.route('/login', methods=['POST'])
def login():
data = request.json
user_data = users.find_one({'email': data.get('email')})
if user_data and bcrypt.check_password_hash(user_data['password'], data.get('password')):
user = User(user_data)
login_user(user)
return jsonify({'message': 'Logged in successfully'})
return jsonify({'message': 'Invalid credentials'}), 401
# Upload
@app.route('/upload', methods=['POST'])
@login_required
def upload():
if 'file' not in request.files:
return jsonify({'message': 'No file provided'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'message': 'No file selected'}), 400
if not allowed_file(file.filename):
return jsonify({'message': 'File type not allowed'}), 400
filename = generate_unique_filename(file.filename)
bucket_name = 'XXXXX'
folder_name = 'XXXXX'
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(f'{folder_name}/{filename}')
generation_match_precondition = 0
blob.upload_from_file(file)
url = blob.public_url
# Save the file metadata in MongoDB
image_data = {
'filename': filename,
'user_id': current_user.id,
'url': url,
'timestamp': datetime.now()
}
images.insert_one(image_data)
return jsonify({'message': 'File uploaded successfully', 'url': url})
I create a variable and store it in flask session(server side), now I open another tab and change the variable, now it reflects in both the tabs. How should I deal with separating data accross multiple tabs?
The playlist is broken into six parts:
This tutorial truly is end-to-end. If you enjoy the content, you can help me a ton by doing any or all of the following:
Any questions or requests, just leave a comment.
I am trying to make a registration page, for my website. The data is coming from the javascript frontend to the backend successfully (evident by browser logs.) and by print statements, but the incoming data is failing to commit to the database.
Background, App is made with "Role Based Access" in mind with models User, Roles and UserRoles (association table)
Influencer
and Sponsor
inherit from User and their primary keys and foreign keys are same. i.e (influencer_id and sponsor_id) respectively.
Here creation of instance of User first is necessary so that its (user_id
) could be used to populate the primary keys of Influencer and Sponsor.
@app.route('/register', methods=['POST'])
def register():
data = request.get_json()
username = data.get('username')
email = data.get('email')
password = data.get('password')
role = data.get('role')
socialm =data.get('social_media')
handle = data.get('handle')
country = data.get('country')
followers = data.get('followerCount')
new_user = User(
email=email,
password=hash_password(password),
roles=[datastore.find_or_create_role(name=role)],
active=True,
type=role,
username=username
)
try:
db.session.add(new_user)
db.session.flush()
if (role == 'influencer'):
fname = data.get("fname")
lname = data.get("lname")
age = data.get("age")
gender = data.get("gender")
newinf = Influencer(
influencer_id = new_user.user_id,
inf_firstName=fname,
inf_lastName=lname,
inf_age=age,
inf_gender=gender,
inf_followerCount=followers,
inf_country = country,
inf_socialMedia=socialm,
inf_handle=handle,
)
db.session.add(newinf)
else:
spname = data.get("spname")
newsp = Sponsor(
sponsor_name = spname,
sponsor_followerCount=followers,
sponsor_country = country,
sponsor_socialMedia=socialm,
sponsor_handle=handle
)
db.session.add(newsp)
db.session.commit() #Suspected failing point
return jsonify({"message" : "user created", "redirect_url": url_for('login')}), 200
except Exception as e :
db.session.rollback()
print(f"Error during registration: {e}")
return jsonify({"message" : "error creating user"}), 400
Error:
* Detected change in '/path/to/project/file/routes.py', reloading
* Restarting with stat
Starting Local Development
Data creation in progress..
Starting Local Development
Data creation in progress..
* Debugger is active!
* Debugger PIN: 730-880-975
Username: randominfluencer, Email: ri@abc.com, Password: 123, Role: influencer ###frontend data
New User: ri@abc.com, randominfluencer, $2b$12$KpW/yS1VPdEfwlpDxlp9a.kvdlZsk3Z826DkCXZIkIHmyCy/5VWiC ###frontend data
New User: ri@abc.com, randominfluencer, $2b$12$KpW/yS1VPdEfwlpDxlp9a.kvdlZsk3Z826DkCXZIkIHmyCy/5VWiC, None
/path/to/project/file/routes.py:132: SAWarning: Flushing object <User at 0x7f8e3a77f6e0> with incompatible polymorphic identity 'influencer'; the object may not refresh and/or load correctly (this warning may be suppressed after 10 occurrences)
db.session.commit()
Error during registration: (sqlite3.IntegrityError) NOT NULL constraint failed: User.email
[SQL: INSERT INTO "User" (username, email, password, active, confirmed_at, fs_uniquifier, type) VALUES (?, ?, ?, ?, ?, ?, ?)]
[parameters: (None, None, None, 1, '2024-11-24 14:34:23.744976', 'f917a93a-c42e-4ba5-8650-ba5be03f5835', 'influencer')]
(Background on this error at: https://sqlalche.me/e/20/gkpj)
127.0.0.1 - - [24/Nov/2024 14:34:28] "POST /register HTTP/1.1" 400 -
Hi,
I am trying to implement Autogen agents with a Flask App. The new version of autogen-agentchat library allows a rich architecture for multiagent systems.
The following is an example from the documentation (Swarm Chat) that starts an agent chat, where at some point a user input is needed. The chat stops at that point. Then whenever the user input is obtained the chat is resumed.
import asyncio
from autogen_ext.models import OpenAIChatCompletionClient
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import Swarm
from autogen_agentchat.task import HandoffTermination, Console, MaxMessageTermination
from autogen_agentchat.messages import HandoffMessage
async def main() -> None:
model_client = OpenAIChatCompletionClient(model="gpt-4o" api_key=os.environ.get("OPENAI_API_KEY))
agent = AssistantAgent(
"Alice",
model_client=model_client,
handoffs=["user"],
system_message="You are Alice and you only answer questions about yourself, ask the user for help if needed.",
)
termination = HandoffTermination(target="user") | MaxMessageTermination(3)
team = Swarm([agent], termination_condition=termination)
# Start the conversation.
await Console(team.run_stream(task="What is bob's birthday?"))
# Resume with user feedback.
await Console(
team.run_stream(
task=HandoffMessage(source="user", target="Alice", content="Bob's birthday is on 1st January.")
)
)
asyncio.run(main())
I want to implement this in a Flask App. So there will be an endpoint that receives user messages. Then:
If the message is the first one (i.e. no message before) the app will run the part with team.run_stream(task="What is bob's birthday?")
and return some message to the user as the response
For subsequent requests the app will run the second part and resume the chat: team.run_stream(task=HandoffMessage(source="user", target="Alice", content="Bob's birthday is on 1st January."))
Any suggestions about how to create such a Flask App?
@app.route('/register', methods=['GET' , 'POST'])
def register():
from auth_operations import register_user
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
confirm_password = request.form['confirm_password']
I made it because we needed to share files in university computers & WhatsApp login was taking too long.... So needed a faster approach that does not require login..
Link: Internet Clipboard.
(UPDATE: THANK YOU! AFTER HOURS I FIGURED IT OUT)
Hey guys,
So I'm new to the whole web app thing, but I've been following this tutorial on how the basics work: https://www.youtube.com/watch?v=dam0GPOAvVI
Here's the github for the code he's also used:
https://github.com/techwithtim/Flask-Web-App-Tutorial/tree/main
Basically, I feel like I've done GREAT so far, following along well. This is what I have managed to produce so far with working pages, routes, re-directs etc:
BUT... I've hit a complete and utter stop when it comes to putting this ^ data into the SQ Database.
This is the code I have for this area and all my other files copy the same names, as well as my html files:
u/auth.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
email = request.form.get('email')
username = request.form.get('username')
password1 = request.form.get('password1')
password2 = request.form.get('password2')
if len(email) < 4:
flash("Email must be at least 4 characters", category="error")
elif len(username) < 2:
flash("Name must be at least 1 character", category="error")
elif password1 != password2:
flash("Passwords don/'t match", category="error")
elif len(password1) < 7:
flash("Password must be at least 7 characters", category="error")
else:
new_user = User(email=email, username=username, password=generate_password_hash(password1, method='scrypt'))
db.session.add(new_user)
db.session.commit()
flash('Account created!', category='success')
return redirect(url_for('views.home'))
return render_template("register.html")
Unfortunately I am getting this error message no matter WHAT I do...
WHICH, keeps bringing me back to this part of my code:
What am I doing wrong? I've even tried changing all the wording and same thing happens no matter what it's called. I'm at my wits end. I'm only 2-3 months into coding and mostly self taught on the web app and applications end, so I don't have anyone else to ask.
I'm having real trouble trying to figure out how to deploy a flask app with a multimodal HuggingFace ml model on AWS Elastic Beanstalk (with a GPU instance). All the youtube tutorials out there are significantly lacking, just showing how to deploy some 'hello world' flask app. Any one know of any decent tutorials or tips on how to actually accomplish this? My two biggest challenges are 1) Figuring out what I need for the .ebextentions for loading the model 2) loading the model during deploying and not when someone visits the website for the first time, as they will have to sit for about 5 minutes while the model loads from huggingface.
This is all there is written about request.form in the flask docs,
"*property form: ImmutableMultiDict[str, str]* The form parameters. By default an ImmutableMultiDict
is returned from this function. This can be changed by setting parameter_storage_class
to a different type. This might be necessary if the order of the form data is important.
Please keep in mind that file uploads will not end up here, but instead in the files
attribute."
How am i supposed to know that i have to use `request.form['username']` where 'username' is the the name attribute of the input element from the html, to get the data? also they do mention it in the quickstart a bit but still leaves out the part what that 'username' part is.
I am a complete nub on this stuff, but i started to give docs more reads these days to actually understand and know what is going.
I genuinely want to know how do you guys figure out these kind of stuff when the docs just assumes you know what you are doing as if you were not looking through docs to not learn?
after clicking approve, function should run which is
now this function confirm_order_route is not printing any statements and in this i have a called a subfunction confirm_order
now this function is deleting booked_order ( record in table in models.py) but not adding data to table confirmed_order , idk why it is not working , not showing any error , it is deleting but not inserting
below i am sharing my tables (models.py)
professional model and bookedorder model
please help!
Hi there, fellows, I have the feeling i am wasting a lot of time reading the documentation of the flask-sqlalchemy flask-sqlalchemy....#define-models without doing real progress.
I seek here some advices to reach my goal faster: load a pandas dataframe into a nice class like ExcelData() I can already load an excel and display it via route and template, but i now want to save it into a DB via a class. My skills seems to be bloked at this step.
Any hints? Link? Template, Tuto? Indian YouTuber?
Hi guys I'm trying to figure out the best way to solve my issue, whether it be threads, or asyncio, or something other than flask.
Heres my route handler:
route_handler():
def stream_response():
def process(connection):
do_something()
processing_thread = CancellableThreadWithDBConnection(target=process)
processing_thread.start()
while not processing_done:
try:
yield json.dumps("")
time.sleep(1)
except GeneratorExit:
processing_thread.raise_exception() # Terminate the thread
return
processing_thread.join()
return Response(stream_with_context(stream_response()))
I need to run a long running task (process) and simultaneously yield "" every second back to the client to see if the client closed the connection. If it did, then i need to stop everything (with my code right now that means killing the processing thread from the main thread). To do that I had to extend the Threading class to make a CancellableThread class.
I would much rather just have some sort of event loop or something and keep this on a single thread to avoid needing to kill threads from other threads since that is bad practice.
For context, the process() function is very long running and very cpu intensive, it can take several minutes. Because of this an event loop may not help since process() may just totally block the thread and yield json.dumps() wouldnt even run?
Any help is appreciated, thanks guys.
I'm encountering an error when running my Flask application. The error occurs when I try to log in, and it seems related to the AssignmentReminder
model's foreign key referencing the User
model. Here's the error traceback:
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'assignment_reminder.teacher_id' could not find table 'user' with which to generate a foreign key to target column 'id'
Here are the models involved:
User Model:
class User(db.Model, UserMixin):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(150), nullable=False, unique=True)
email = db.Column(db.String(120), unique=True, nullable=False)
password_hash = db.Column(db.String(128), nullable=False)
role = db.Column(db.String(20), nullable=False) # e.g., 'student', 'teacher', etc.
def __repr__(self):
return f"User('{self.username}', '{self.email}', '{self.role}')"
AssignmentReminder Model:
class AssignmentReminder(db.Model):
__tablename__ = 'assignment_reminder'
id = db.Column(db.Integer, primary_key=True)
teacher_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) # Foreign key
assignment_details = db.Column(db.String(255), nullable=False)
title = db.Column(db.String(100), nullable=False)
description = db.Column(db.Text, nullable=False)
due_date = db.Column(db.DateTime, nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
# Relationship
teacher = db.relationship("User", backref="assignments")
__tablename__
in the User
model is set to 'user'
.user
exists.teacher_id
column uses db.ForeignKey('user.id')
instead of referencing the class name (User.id
).user
the table is created before assignment_reminder
during database initialization.Why is SQLAlchemy unable to find the user
table, even though the table name matches the foreign key reference? How can I resolve this error?
I'm using Flask-Migrate for database migrations. The User
model is bound to the main database and the AssignmentReminder
model references this table.
python
flask
sqlalchemy
flask-sqlalchemy
database
I am working on a B2C startup and need to design the backend for a website and mobile apps supporting a chat application. The platform will incorporate AI/ML models to analyze chats and user inputs, alongside a notification system for users. My initial idea is to separate the backend and AI services. Should I use Python for both the backend(with flask or django) and AI components, or would it be better to leverage Nest.js for the backend, while using Python for AI?
Hi guys my flask route is streaming and “yield”s data every 1 second to check if the client connection has been closed. Meanwhile I want the actual route handler logic to run.
Right now I create a separate thread in the route handler to run the actual logic then just have a while loop with yield “” in the main thread.
But this just seems so hacky since I have to terminate the child thread from the main thread if the client closed the connection and yield “” threw a generator exit error.
I saw that flask has an event loop and just wanted to check with you all and see if anyone has had experience with it. Obviously it’s a much better solution if it works. Thanks!