Blueprint - Flask blueprints

Blueprint - Flask blueprints

Introduction

Blueprints are needed to split a project into subprojects. Usually it is more convenient to put some functionality into separate .py files; the classic import as in ordinary Python code is not recommended

Creating and registering a blueprint without url_prefix

Suppose that in your project project there is a folder app and in it you already have a working __init__.py file

Create a file blog.py in the same directory and write the minimum code.

touch app/blog.py
vi app/blog.py

from flask import ( Blueprint, flash, g, redirect, render_template, request, url_for ) bp = Blueprint('blog', __name__) @bp.route('/') def index(): return render_template('blog/index.html')

Note that the url is handled with @bp.route and not @app.route as in an application without blueprints

This blueprint needs to be registered. Make changes in __init__.py it is assumed that the application is started through a factory

vi app/__init__.py

from . import blog app.register_blueprint(blog.bp) app.add_url_rule('/', endpoint='index')

In the folder templates create a subfolder blog and put a template file there

mkdir app/templates/blog
touch app/templates/blog/index.html

When the blog.py blueprint was created, only two arguments were passed - the name of the blueprint and __name__

bp = Blueprint('blog', __name__)

When this blueprint is registered in __init__.py endpoint was specified as index

from . import blog app.register_blueprint(blog.bp) app.add_url_rule('/', endpoint='index')

In this case the blueprint will have no url_prefix defined

Thus blog becomes the root

The second option is to set a prefix; we will look at it in the next paragraph

url_prefix

Create a file auth.py with the minimum code

from flask import ( Blueprint, flash, g, redirect, render_template, request, url_for ) bp = Blueprint('auth', __name__, url_prefix='/auth')

Pay attention to the line

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

When creating the blueprint auth three arguments are passed: the name of the blueprint, __name__ and url_prefix='/auth'

When registering this blueprint, there is no need to call add_url_rule additionally

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

Template

In the folder templates create a subfolder auth and put a template file there

mkdir app/templates/blog
touch app/templates/auth/login.html

↓ Articles about Flask ↓
Python
Flask
Running Flask on hosting
Running Flask on a Linux server
The first Flask project
Jinja templates
Flask FAQ
Web Forms
Errors

Article author: Andrei Olegovich