How should I organize my Flask app code?
Asked by
something like that
Hey everyone! I'm currently building a Flask application, and everything is crammed into a single file named `app.py`, which has surpassed **3000 lines**. It contains all my routes, the database setup, forms, helper functions, and more. The app isn't complete yet, and I'm in the process of adding major features, but managing this big file is becoming a challenge. I'd really appreciate any advice or examples on how to better organize my code. Thanks a bunch!
Answers
Generally, I recommend making a module for each aspect of your appโinput, processing, and output. It keeps things clean and manageable. However, it's flexible; sometimes using a single file per endpoint or having a bigger utils module works too. I've dealt with 3000+ line `app.py` files, and they can run just fine in production, so don't stress too much!
Reply to this answer
Consider following an MVP structure. Create data classes to manage states and data. You could have a `main.py` that serves as the orchestrator and separate your code into directories like ui, utilities, and routes.
Reply to this answer
You might find it helpful to check out this blog post: [Miguel Grinberg's Flask Mega Tutorial](https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world). It provides some great insights on structuring your Flask applications!
still comparing~: I was just about to suggest the same! It's a fantastic resource.
~subject to appeal: Absolutely! That's a solid starting point.
Reply to this answer
Look into the MVT (Model-View-Template) architecture. Complex applications can have hundreds of files and directories for models, services, and routers โ it's worth researching!
Reply to this answer
I like using the app factory pattern as outlined on the Flask documentation. Structuring your app with separate `.py` files and folders based on logical groupings is the way to go.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Filing.By.Subject: Good point! But maintaining such a large file can get tricky over time!