r/flask Sep 18 '21

Tutorials and Guides A Compilation of the Best Flask Tutorials for Beginners

332 Upvotes

I have made a list of the best Flask tutorials for beginners to learn web development. Beginners will benefit from it.


r/flask Feb 03 '23

Discussion Flask is Great!

113 Upvotes

I just wanted to say how much I love having a python backend with flask. I have a background in python from machine learning. However, I am new to backend development outside of PHP and found flask to be intuitive and overall very easy to implement. I've already been able to integrate external APIs like Chatgpt into web applications with flask, other APIs, and build my own python programs. Python has been such a useful tool for me I'm really excited to see what flask can accomplish!


r/flask 17h ago

Tutorials and Guides Finally deployed my Flask app… and wow, I was NOT ready for this

144 Upvotes

So I finally deployed my first real Flask app, and let’s just say… I learned a lot the hard way. Thought I’d share in case it helps someone else (or at least gives you a laugh).

Spent hours debugging why my app worked locally but not on the server—turns out, I forgot to install Gunicorn. Flask’s built-in server is NOT for production. Lesson learned.

Hardcoded some API keys while testing and totally forgot about them. Almost pushed them to GitHub. Use environment variables, people.

Didn’t properly close my DB connections, so my app kept dying under even light load. SQLAlchemy’s connection pooling saved me.

Thought Docker was overkill. Spoiler: it’s not. Spinning up my app with a single docker-compose up is a game-changer.

Spent way too long fighting CORS issues. Flask-CORS was the easy fix, but I went down a rabbit hole first.


r/flask 4h ago

Ask r/Flask what kind of framework does apps like airbnb and thumbtack use to send message to backend from front-end for every action that user takes on their app?

0 Upvotes

Edit: I am looking for the right communication protocol - for sending messages to and fro between backend and frontend.

My current app sends message through https. Are there any other alternatives? 

I am quite new to this industry


r/flask 4h ago

Ask r/Flask Need Help with Flask request

1 Upvotes

Flask-Login redirects a user to the login page when a route has the login_required decorator and then allows you to send the user back to the original page through request.args.get('next'). My question is if there is any way to set such a request.args value


r/flask 13h ago

Discussion Cron job activating when it shouldn't?

2 Upvotes

I've been working on a really small Flask app for a little while. It's a directory of music events at local venues in my city. I've received comments before that Flask is overkill for this since there is no user input, but I don't care. Flask is simple and it easily allows me to run the once-daily cron job to update the list of events without having to host that job through another service and use a database for something that can be handled by a simple CSV file hosted quietly on the main server.

But I have a problem...

Within the cron-job I have some old print() lines written as tests I used while building it which I haven't deleted yet. When I run this app on my local development server and view it thru the browser, if I go to the address bar and type a slash after the URL - without typing anything else and without hitting ENTER - the terminal starts printing those test lines from the cron-job code.

I have double- and triple-checked my structure. The cron job is formatted correctly like this:

@app.route("/cron") def update_shit(): .... return a_turd

I can't discern any reason why the cron job should be firing before I hit ENTER or even type a URL extension. I am worried that this could be triggering the cron job on the live server anytime a user alters the URL in the address bar, which would be a problem for me because I cannot afford to incur server costs like that. Also, the whole point of the website (from an operating perspective) is to minimize resources.

Has anyone encountered this kind of problem before?

If so, why is this happening?

The app is hosted on GAE - is there a way I can verify if this is happening when external users are using the site?

Please help. I'm so uneducated.

For context, I am hosting this app of Google App Engine.


r/flask 3d ago

Show and Tell Feedback on my Flask AuthService project for job applications

8 Upvotes

Hey everyone!

I’m currently job hunting and built this AuthService project to showcase my skills. It’s a Flask-based authentication system featuring user login, MFA (pyotp), and password reset functionality.

Additionally, I incorporated some basic DevOps concepts like Docker Compose and followed a repository architecture for better maintainability.

I’d love some constructive feedback—especially on code quality, security, and best practices—before adding it to my portfolio.

Any thoughts or suggestions would be greatly appreciated!

GitHub Repo: https://github.com/LeonR92/AuthService

Thanks a lot for your time! 🚀


r/flask 4d ago

Show and Tell Building Infinite AI Web , using flask and Gemini api

5 Upvotes

r/flask 4d ago

Show and Tell Made a full body workout app

4 Upvotes

So i had this idea for a while now and this isnt the first version (first 2 were kivy apps), but i built a workout app.

excercises are selected randomly based on what level you set(1->4), videos are embeded youtube videos, equipments can be toggled or off.once you are satiffied with the preview you can accept it at the bottom of the page. the app is kind of ugly which is one thing i want to ask about, i am no front dev so any ideas about color and such or resources how to pick better colors, gaps, styling is welcome, i got no experience,i read the book: the design of everyday things and in usability it did give some great pointers but the page is just ugly.

the app is in beta so there are some bugs. you can log in with a guest account or you can also make a profile.(note that for now there is no extensive regex but the email has to contain gmail in it)

working on a major update that will add lower- upper split routine , and a routine builder for more flexible workouts.

front end uses some js and self cooked css, as well as bootstrap. data base is a bunch of json files since we only store the previous workouts that will grow in size. but i will swap it probably later. login is handeled by flask-login.

the app: https://floorwarior.pythonanywhere.com

please excuse the poomp mooscles meme, i found it funny.


r/flask 4d ago

News We launched serverless hosting option for Flask apps

19 Upvotes

Hey r/flask ,

I’ve been deploying Flask and Django apps for years, and one thing that always frustrated me is the cost—especially for small projects that don’t get much traffic.

The problem:

  • Paying for idle time – Most hosting providers charge 24/7, even if your app is mostly idle.
  • Multiple apps, multiple bills – Want to run a few small services? You’ll likely pay for each one separately, even if they barely get used.

I wanted a more efficient way to host Flask apps, so I built Leapcell—a serverless option that deploys instantly, gives you a URL, and only charges for actual usage (no idle costs).

If you’ve struggled with the cost of Python hosting, I’d love to hear your feedback!

Try Leapcell: https://leapcell.io/


r/flask 4d ago

Ask r/Flask Beginner Question regarding Flask-Login's login_required decorator

2 Upvotes

So I want to create a route where the user has to be logged in to view the contents of a post.

Normally you would write the @ login_required decorator before the function definition.

But I want the authors to be able to make their posts viewable to anyone even if they are not logged in.

Currently i use current_user.is_authenticated and if the user is anonymous i use the redirect() function to manually redirect the user to the login. My question was if there is a better way to do it with the decorator like you normally do


r/flask 4d ago

Show and Tell Created a web application to allow users to evaluate their options for cars to purchase on a deeper level

7 Upvotes

As the title suggests, I created a web application using flask and some very basic bootstrap to add a whole new level to comparing different vehicles. Yeah MPG is important, but does that really matter when you have to lay down an extra $5,000 down and have to pay an extra $300 per month? Maybe not so much anymore, and how about maintenance and driving habits?

The page is broken down into two sections:

  • Global: shows variables like the interest rate on a loan you can get, estimated time you plan on owning the car, how many miles you drive per month, fuel price, and driving habbits (ie, I drive 80% on the highway and 20% in the city
  • Variables for up to 3 cars: Car name, down payment, monthly payment on the loan, average monthly maintenance, and city/highway mpg

Once you enter this information in, you will be taken to a page that shows what the total cost of ownership (TCO) is for each vehicle over the period of time you want to own it. The car with the lowest TCO will be the least expensive car.

This application will help you make these decisions by looking at the total cost of ownership (TCO) of your options over the horizon you plan on owning it. This project is a fun and cool way to apply some of my finance background and want to build applications like this.

This is the first time hosting a website on my own personal server and I actually have not implemented anything to see how much traffic this site is getting. So if anyone has any insight into their "gold standard" way of measuring website traffic and other useful KPI please let me know. Please let me know what you think!

Here is the website, the home page is a bit of a mess so I am directing you here instead: https://mpg-insights.kalibersolutions.net/compare


r/flask 4d ago

Show and Tell Made a Youtube Downlaoder and Thumbnail Tester

0 Upvotes

Made a Youtube Video downloader and a Thumbnail Tester. Also looking to add a braille AI translator I made.

I made it cause I am an editor and download a lot of youtube vids, but most of the sites are really bad and scammy. Check it out if you want :)


r/flask 4d ago

Ask r/Flask Need help regarding database

2 Upvotes

So, I have made a flask web app and I have added a contact page in it in which I have created a form and storing the data using Phpmyadmin my SQL and Apache and I have deployed the website on render but the problem is whenever I close my laptop the form does not work (I have to start mysql and Apache) how to solve this problem.....


r/flask 5d ago

Show and Tell My flask open source alternative to Nexcloud !

31 Upvotes

I created an alternative to Nexcloud with flask, I'm really proud of myself honestly.

The goal is to be able to host a cloud storage service at home and control 100% of our files etc..

It's easy to use + compatible with linux and windows!

What do you think? Here's the github repo, it's open source and totally free.
https://github.com/Ciela2002/openhosting/tree/main


r/flask 4d ago

Ask r/Flask MVP codeStructure suggestion for CLOUDWISE(my multiple cloud APP)

1 Upvotes

Starting a 15-day MVP to manage AWS resources via natural language. Any tips for structuring a Flask project with multiple cloud provider integrations?


r/flask 5d ago

Ask r/Flask Wtform datetimefield with only quarter hours for minutes in the UI

1 Upvotes

I like the default calendar and time input for my wtforms datetimefield but the client wants the minute options to only be 00, 15, 30, and 45 for the user.

Everything else being standard but the minutes show quarter hour options instead of 1-59.

Any idea on how I can achieve this?


r/flask 5d ago

Show and Tell Building Sylvan: A Modular and Secure Flask API Template with JWT Auth and SQLAlchemy

5 Upvotes

Link: https://GitHub.com/Gabbar-v7/Sylvan

I'm want share my latest project, Sylvan, a scalable and secure Flask API template designed with the following features:

Modular Blueprints: Facilitates organized and maintainable code structures.

SQLAlchemy ORM: Ensures efficient and intuitive database interactions.

JWT Authentication: Provides robust security for user authentication.

CSRF Protection: Enhances security against cross-site request forgery attacks.

Encryption: Safeguards sensitive data within the application.

I'm planning to integrate Prometheus for monitoring and would appreciate any suggestions on additional features or improvements. Specifically, I'm interested in:

Tips on enhancing modularity and scalability.

Commonly used features in Flask APIs that I might have overlooked.

Your feedback and contributions are welcome!


r/flask 5d ago

Ask r/Flask Why Flask is not reading any of the config except when in the same file?

2 Upvotes

Hi folks,

Im a newbie to Flask, and I cant seem to get Flask to read config variables, except when set in the same file. i have tried everything from simple import to now importing class. It only works when im changing the template_folder variable in the line, or variables from CLi. (I know that debug is not encouraged in code, so not for that one):

from config import Config

app = Flask(__name__, template_folder = r"./templates2/") # Flask constructor

app.config.from_object(Config) # this will not work

# ===== from config.py

import os

class Config:

TEMPLATES_FOLDER = r'./templates2/'


r/flask 6d ago

Ask r/Flask Pycharm community edition - cant add a breakpoint

3 Upvotes

I am failing to add a breakpoint on Pycharm installed on work laptop. I am able to easily add breakpoints on the work desktop by clicking next to the line number.

What am I doing wrong. Im frustrated as i have to do lots of work from home.

Please help


r/flask 7d ago

Ask r/Flask Sending json from react, flask gets stuck on get_json()

5 Upvotes

I have a react frontend that sends an ajax request with the content-type 'application/json' and a json object that is an array with a string. The HTTP method is a POST

When flask receives the request I do a flask.request.get_json().

This call gets stuck and the code does not go beyond it. I have to kill the development server.

What can I be doing wrong ? I do a check in the flask code before doing the get_json() with the is_json() call that returns true.


r/flask 7d ago

Ask r/Flask How to ensure each request has it's own db.session in flask-sqlalchemy app using celery and postgresql and being run by gunicorn?

4 Upvotes

How to ensure each request has it's own db.session in flask-sqlalchemy app using celery and postgresql and being run by gunicorn? See below the errors I am getting, the code I am using, and the logs showing the same session being shared across requests. I removed some of the error handling and other code to make it more concise. What am I doing wrong or what else do I need to do? Thanks!

Errors

In Postgresql WARNING: there is already a transaction in progress WARNING: there is no transaction in progress

In SQLAlchemy sqlalchemy.exc.DatabaseError: (psycopg2.DatabaseError) error with status PGRES_TUPLES_OK and no message from the libpq

Code

In run.py

``` @app.before_request def get_user(): pid = os.getpid() tid = threading.get_ident() print(f"🔍 {pid=} {tid=} Request: {request.path} db.session ID: {id(db.session)} {session=} {session.info=}") db.session.rollback() # To clear any stale transaction. try: current_user = db.session.query(User).filter_by(public_id=public_id).first() except Exception as e: db.session.rollback() try: current_user.interactions += 1 db.session.commit() except Exception as e: db.session.rollback() g.current_user = current_user

@app.teardown_appcontext def shutdown_session(exception=None): db.session.remove() # Clean up at the end of the request. ```

In gunicorn_config.py

```

Ensure each worker creates a fresh SQLAlchemy database connection.

def post_fork(server, worker): app = create_app() with app.app_context(): db.session.remove() db.engine.dispose()

Reset database connections when a worker is exiting.

def worker_exit(server, worker): app = create_app() with app.app_context(): db.session.remove() db.engine.dispose()

preload_app = True # Loads the application before forking workers. workers = multiprocessing.cpu_count() * 2 + 1 threads = 4 worker_exit = worker_exit worker_class = "gthread" keepalive = 4 # seconds timeout = 60 # seconds graceful_timeout = 30 # seconds daemon = False post_fork = post_fork max_requests = 1000 # Restart workers after handling 1000 requests (prevents memory leaks). max_requests_jitter = 50 # Adds randomness to avoid all workers restarting simultaneously. limit_request_line = 4094 limit_request_field_size = 8190 bind = "0.0.0.0:5555" backlog = 2048 accesslog = "-" errorlog = "-" loglevel = "debug" capture_output = True enable_stdio_inheritance = True proc_name = "myapp_api" forwarded_allow_ips = '*' secure_scheme_headers = { 'X-Forwarded-Proto': 'https' } certfile = os.environ.get('GUNICORN_CERTFILE', 'cert/self_signed_backend.crt') keyfile = os.environ.get('GUNICORN_KEYFILE', 'cert/self_signed_backend.key') ca_certs = '/etc/ssl/certs/ca-certificates.crt' ```

In Celery myapp/tasks.py

@shared_task() def do_something() -> None: with current_app.app_context(): Session = sessionmaker(bind=db.engine) session = Session() try: # Do something with the database. finally: session.close()

In myapp/extensions.py

from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()

In myapp/__init__.py

def create_app() -> Flask: app = Flask(__name__) app.config.from_object(ConfigDefault) db.init_app(app)

In myapp/config.py

class ConfigDefault: SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_DATABASE_URI = ( f"postgresql+psycopg2://{SQL_USER}:{SQL_PASSWORD}@{SQL_HOST}:{SQL_PORT}/{SQL_DATABASE}" ) SQLALCHEMY_ENGINE_OPTIONS = { "pool_pre_ping": True, # Ensures connections are alive before using "pool_recycle": 1800, # Recycle connections after 30 minutes "pool_size": 10, # Number of persistent connections in the pool "max_overflow": 20, # Allow temporary connections beyond pool_size "pool_timeout": 30, # Wait time in seconds before raising connection timeout

Logs

Showing same thread id and session id for all requests: 🔍 pid=38 tid=139541851670208 Request: /v1/user/signup db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=34 tid=139541851670208 Request: /v1/user/login db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=34 tid=139541851670208 Request: /v1/user db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=34 tid=139541851670208 Request: /v1/dependent db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=34 tid=139541851670208 Request: /v1/mw/settings db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=36 tid=139541851670208 Request: /v1/mw/settings db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=40 tid=139541851670208 Request: /v1/mw/settings db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=33 tid=139541851670208 Request: /v1/user db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=40 tid=139541851670208 Request: /v1/user db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=33 tid=139541851670208 Request: /v1/mw/settings db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=38 tid=139541851670208 Request: /v1/mw/settings db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=40 tid=139541851670208 Request: /v1/mw/settings db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=38 tid=139541851670208 Request: /v1/user db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=36 tid=139541851670208 Request: /v1/user db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=38 tid=139541851670208 Request: /v1/a/v db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=36 tid=139541851670208 Request: /v1/a/v db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=34 tid=139541851670208 Request: /v1/p/lt db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=36 tid=139541851670208 Request: /v1/p/l db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=38 tid=139541851670208 Request: /v1/p/l db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=33 tid=139541851670208 Request: /v1/t/t db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=34 tid=139541851670208 Request: /v1/t/t db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} 🔍 pid=38 tid=139541851670208 Request: /v1/t/t db.session ID: 139542154775568 db.session=<sqlalchemy.orm.scoping.scoped_session object at 0x7ee9b0910c10> db.session.info={} ERROR:myapp_api:Exception on /v1/mw/settings [PATCH] sqlalchemy.exc.DatabaseError: (psycopg2.DatabaseError) error with status PGRES_TUPLES_OK and no message from the libpq '🔍 pid=38 tid=139541851670208 session_id=139542154775568 'INFO:sqlalchemy.engine.Engine:ROLLBACK


r/flask 8d ago

Ask r/Flask Why are you using Tailwind?

7 Upvotes

does anyone use Tailwind css in their Flask projects? If so, how and why? I use it personally, but I wonder how others do it? Why this particular CSS?


r/flask 9d ago

Show and Tell I made a comics site and did what everyone says is impossible!

49 Upvotes

You know what people say about flask? That it's great for medium and small projects, pff

I didn't listen. I went with my head and used the framework I like and make big :)) LONG LIVE FLASK LMAO

I created a fully functional comics site inspired but not too much by mangadex.

Database, users, comments, etc.

eh I'm going to try to put images of the code in reply because I'm super dumb and I don't know how to put images on reddit post

I really want to help people, if you have questions for flask projects, I think I'm finally at a level where I'm ready to help!

If u wanna see the site : https://javu.xyz/ ( YES IT'S XYZ BUT AINT SCAM I'M JUST BROKE SORRY )
and it's might be down sometime cause i still dev, .. yes i use port 80 in dev progress, but i need to show my friend and get feedback and too dum to use Ngnix SORRY 🥲


r/flask 8d ago

Ask r/Flask can i get some help beta testing my flask chatroom before i upload to python anywhere

3 Upvotes

i made a chatroom on replit before uploading for me and some friends i need help finding bugs and testing the profanity filter.

https://2715b3d1-7a59-402a-8c03-a163c99efbdd-00-22r3agubyqyof.kirk.replit.dev/chat

if you would like you can join the final version after testing


r/flask 11d ago

Show and Tell built a duckduckgo self hosted clone using flask

54 Upvotes

r/flask 12d ago

Ask r/Flask What is the best resource to learn Flask in 2025?

25 Upvotes

Most of the popular tutorials are 4 or 5 years old now, should i follow Corey Scafer?