103

I have just created a flask application and so far I have a router for my "Hello world!" template.

I would like to add a little (a lot) more functionality, but I wonder how I should structure the app directory.

What's the most common way of structuring a Flask app? For instance, should I create a routes.py for all my routes? Where does the SQLAlchemy stuff go? Should models be in models.py?

simanacci
  • 2,197
  • 3
  • 26
  • 35
kasperhj
  • 10,052
  • 21
  • 63
  • 106

12 Answers12

51

You should check out the Larger Applications page in the Patterns section of the Flask docs: http://flask.pocoo.org/docs/patterns/packages/. It seems to be the model that most people follow when their application calls for a package instead of a module.

I believe views.py is what you are calling routes.py. After that, models would go in models.py, forms would go in forms.py, etc.

dirn
  • 19,454
  • 5
  • 69
  • 74
  • 7
    I don't get that, why do we have just one file for all the models? What about the 'one class per file' practice? What if some models are quite big? Should we move some of the logic into other modules? And still, if I wanted my models to be in separate files, should I just create a module 'models'? Thanks! – simon Jul 11 '16 at 18:07
  • 1
    @lime, how to structure project when there are more models?, i can you help me please. – julian salas Jul 29 '16 at 18:06
  • 1
    @lime I'm not a fan of "one class per file." I find longer, repetitive import paths to be cumbersome. You also end up with a lot of extra imports to accommodate everything being separate, unless you import everything into an `__init__.py`, which can be hard to maintain. That said, you're free to structure your project however you'd like. I was merely offering a convention many people follow. – dirn Jul 29 '16 at 19:03
  • @dirn yeah, I guess there is no common structure. Different frameworks suggest various structures. Even Django say in the docs that the default structure is just a suggestion. – simon Aug 01 '16 at 07:32
  • 3
    I think one class per file is great when the project grows, but if you only have 2-3 why bother. You can always split them when you need to. My guideline is when it fits my 19" screen its fine soon asI need to scroll, I split ... – Kimmo Hintikka Nov 11 '16 at 17:22
  • Is it good practice to make your app installable? It will cause truble when you want to move your app to docker container. – marcin Feb 03 '22 at 13:42
46

An example of a FlaskApp directory:

    /yourapp  
        /run.py  
        /config.py  
        /app  
            /__init__.py
            /views.py  
            /models.py  
            /static/  
                /main.css
            /templates/  
                /base.html  
        /requirements.txt  
        /yourappenv

run.py - contains the actual python code that will import the app and start the development server.
config.py - stores configurations for your app.
__init__.py - initializes your application creating a Flask app instance.
views.py - this is where routes are defined.
models.py - this is where you define models for your application.
static - contains static files i.e. CSS, Javascript, images
templates - this is where you store your html templates i.e. index.html, layout.html
requirements.txt - this is where you store your package dependancies, you can use pip
yourappenv - your virtual environment for development

simanacci
  • 2,197
  • 3
  • 26
  • 35
  • For `requirement.txt` and `venv`. – Kishor Pawar Sep 28 '16 at 07:47
  • dumb question, but are the 2nd and 3rd "/yourapp" supposed to be named the same? I'm a little confused on why there's 3 levels named "/yourapp" – Source Matters Dec 20 '19 at 23:44
  • 1
    @SourceMatters The first `/yourapp` wasn't really necessary, third one is `/app`. – simanacci Dec 21 '19 at 06:08
  • 1
    thanks! that helps. i'm having trouble getting mine to run with blueprints (for use of a url_prefix). i'm not sure how to structure the code properly. works fine when running in debug in vscode, but running as gunicorn, it doesn't run. – Source Matters Dec 21 '19 at 17:43
  • Try [here](https://lepture.com/en/2018/structure-of-a-flask-project) and the official documentation. – simanacci Dec 22 '19 at 06:32
  • for quick testing: `mkdir -p yourapp/{run.py,config.py,requirements.txt} && \ mkdir -p yourapp/app/{__init__.py,views.py,models.py} && \ mkdir -p yourapp/app/static/{main.css,} && \ mkdir -p yourapp/app/templates/{base.html,}` – user9074332 May 15 '20 at 14:27
29

I would say if you split the application use divisional rather than functional structure. I advocate this because you are more likely to work on 1 of these divisional components at any one time.

This type of structure lends itself well on marketplace or SaaS apps where different user groups use a different type of views. API only flask app I might use functional splitting.

Here are examples from Flask Blueprints. Blueprints are essentially documented advice how to split Flask application for more manageable pieces. More on this at : http://exploreflask.com/en/latest/blueprints.html

Here is an example of divisional splitting. See how each feature is grouped together.

yourapp/
    __init__.py
    admin/
        __init__.py
        views.py
        static/
        templates/
    home/
        __init__.py
        views.py
        static/
        templates/
    control_panel/
        __init__.py
        views.py
        static/
        templates/
    models.py

Here is the functional example >

yourapp/
    __init__.py
    static/
    templates/
        home/
        control_panel/
        admin/
    views/
        __init__.py
        home.py
        control_panel.py
        admin.py
    models.py
Kimmo Hintikka
  • 13,472
  • 7
  • 34
  • 63
12

I think flask is micro framework and now you must decide how create files and folders.

i use this way :

this is near Django structure

i suggest you see some project to give you what you want

Mohammad Efazati
  • 4,812
  • 2
  • 35
  • 50
11

Anyone looking for a simple beginner-friendly structure for the flask project may find this helpful:

   |__movies 
     |__run.py 
     |__app     
        ├── templates
        │   └── index.html
        │   └── signup.html
        └── __init__.py
        └── routes.py

Here 'movies' is the name given for the main application. It contains 'run.py' and a folder called 'app'. 'app' folder contains all necessary flask files such as 'templates' folder, '__init __.py', and 'routes.py'.

Contents of:

run.py:

from app import app

__init.py__:

from flask import Flask

app = Flask(__name__)

from app import routes


app.run(debug=True)

routes.py:

from app import app

@app.route('/')
@app.route('/index')
def index():
    return "Hello, World!"
Nuhman
  • 1,172
  • 15
  • 22
9

Beauty of flask lies in its flexibility. You can build django like project-structure easily. Django popularized abstraction of features in apps and making them reusable but it can be a overkill for many projects.

But with flask you can go either way. Write reusable apps or write simple apps. Check these cookiecutter skeletons -

  1. minimal skeleton
    myproject
    ├── config.py
    ├── instance
    │   └── config.py
    ├── myproject
    │   ├── commands.py
    │   ├── controllers.py
    │   ├── extensions.py
    │   ├── forms.py
    │   ├── __init__.py
    │   ├── models.py
    │   ├── routes.py
    │   └── ui
    │       ├── static
    │       │   ├── css
    │       │   │   └── styles.css
    │       │   └── js
    │       │       └── custom.js
    │       └── templates
    │           └── index.html
    ├── README.md
    ├── requirements.txt
    └── wsgi.py
  1. django like skeleton
    myproject
    ├── config.py
    ├── development.py
    ├── instance
    │   └── config.py
    ├── myproject
    │   ├── auth
    │   │   ├── controllers.py
    │   │   ├── forms.py
    │   │   ├── __init__.py
    │   │   ├── models.py
    │   │   └── routes.py
    │   ├── helpers
    │   │   ├── controllers.py
    │   │   ├── __init__.py
    │   │   └── models.py
    │   ├── __init__.py
    │   └── ui
    │       └── templates
    │           ├── 404.html
    │           ├── 500.html
    │           └── base.html
    ├── README.md
    ├── requirements.txt
    ├── tests
    │   ├── auth
    │   │   ├── __init__.py
    │   │   └── test_controllers.py
    │   └── __init__.py
    └── wsgi.py

This is an excellent article on this.

27px
  • 430
  • 5
  • 16
userx
  • 806
  • 1
  • 11
  • 23
  • Do you have a github example of this in practice? I'm still trying to figure what to put into `__init__.py` vs `wsgi.py`, for example. – krubo Jun 24 '19 at 17:56
  • @krubo content is already added in cookiecutter-minimal-skeleton (1st example link) . just create project using it. You will get everything ready. check README for more info. – userx Jun 25 '19 at 14:36
5

You could get inspired by the cookiecutter templates here to jumpstart your app development

Community
  • 1
  • 1
Shankar ARUL
  • 12,642
  • 11
  • 68
  • 69
3

Here is the basic file structure for flask I use regularly.

yourapp/
static/
    js
    css
    img

templates/
    home.html
    index.html

app.py

static folder contains all the static files of the website. The templates folder contains all the HTML pages. and app.py contains your python views.

1

I decided to nest the source code folder under src/.

my_flask_app (project folder)
├── app.py
├── setup.py
├── src/
│   ├── my_flask_app/ (source code folder)
│   │   ├── config.py
│   │   ├── errors.py
│   │   ├── forms.py
│   │   ├── __init__.py
│   │   ├── models.py
│   │   ├── routes.py
│   │   ├── static/
│   │   └── templates/
│   └── my_flask_app.egg-info/
|
└── tests/ (test folder)

Because of this, I added package_dir={'': 'src'} in setup.py.

panc
  • 817
  • 2
  • 14
  • 30
0

good idea is to goole for sceletons/template projects on github

for example you can look at this

Ryabchenko Alexander
  • 10,057
  • 7
  • 56
  • 88
0

In flask we can maintain the mvc structure like as separate all thinks for example 1 Templets folder contains all html files 2 Static folder contains all css and boostrap related files 3 User defined db folder for db connection and crud operations 4 User defined Model folder for accessing/ binding the data from Templets/front- end to db/back-end connectivity and after the main activity file
for reference flask file structure link as follow https://flask.palletsprojects.com/en/1.1.x/tutorial/layout/

-1

For larger projects here's what my directory structure looks like

app_name(root folder)
│  .env
│  .gitignore
│  .gitattributes
│  README.MD
│  pyproject.toml
│
└── app(source code)
│   │   __init__.py
│   │   __main__.py
│   │   db.py
│   │   auth.py
│   │   forms.py
│   │   utils.py
│   │   config.py
│   │
│   └─── routes
│          __init__.py
│          views.py
│          api.py
│          auth.py
│
└─ resources
│   |─── static
│   │       css
│   │       js        
│   │       images
│   │
│   └─── templates
│           base
|           components
│
└─ tests
└─ venv
└─ docs