Folder structure and file organisation for python flask

Two methods to create flask application

Case 1: a module:

/application.py
/templates
    /hello.html

Case 2: a package:

/application
    /__init__.py
    /templates
        /hello.html

For larger applications it’s a good idea to use a package instead of a module.

How to convert module into package

To convert that into a larger one, just create a new folder yourapplication inside the existing one and move everything below it. Then rename yourapplication.py to __init__.py. (Make sure to delete all .pyc files first, otherwise things would most likely break)

 

Now we can restructure the application a bit into multiple modules. The only thing you have to remember is the following quick checklist:

  1. the Flask application object creation has to be in the __init__.py file. That way each module can import it safely and the __name__ variable will resolve to the correct package.
  2. all the view functions (the ones with a route() decorator on top) have to be imported in the __init__.py file. Not the object itself, but the module it is in.

Here is sample folder structure

 


.
└── myproject
├── myapp1
│   ├── __init__.py
│   ├── static
│   ├── templates
│   │   ├── aboutus.html
│   │   ├── base_bkp.html
│   │   ├── base.html
│   │   ├── contactus.html
│   │   └── index.html
│   └── views.py
└── setup.py

Using Blueprint

In above example we have used very simple structure. Now let us look at creating multiple views and grouping them together using blueprint

A Blueprint is a way to organize a group of related views and other code. Rather than registering views and other code directly with an application, they are registered with a blueprint. Then the blueprint is registered with the application when it is available in the factory function.

here is sample code for simple flask package with two blueprints


import os

from flask import Flask


def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    # app.config.from_mapping(
    #     SECRET_KEY='dev',
    #     DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    # )

    from . import auth
    app.register_blueprint(auth.bp)

    from . import blog
    app.register_blueprint(blog.bp)

    # import myapp1.views

    # a simple page that says hello
    @app.route('/')
    def hello():
        return 'Hello, World!'

    return app

auth.py


import functools

from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from werkzeug.security import check_password_hash, generate_password_hash


bp = Blueprint('auth', __name__, url_prefix='/auth')

@bp.route('/')
def auth_home():
	return "this is auth base page"

@bp.route('/aboutus')
def aboutus():
	return render_template('aboutus.html', name="techtrekking.net")

@bp.route('/contactus')
def contactus():
	return render_template('contactus.html')

blog.py


import functools
from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from werkzeug.security import check_password_hash, generate_password_hash
bp = Blueprint('blog', __name__, url_prefix='/blog')
@bp.route('/')
def auth_home():
    return "this is blog base page"
@bp.route('/aboutus')
def aboutus():
    return render_template('aboutus.html', name="techtrekking.net")
@bp.route('/contactus')
def contactus():
    return render_template('contactus.html')

By using blueprint, you can segregate urls based on their functions. This is very usefull method to segregate the different sections of the website.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.