Home >Backend Development >Python Tutorial >How to use Flask blueprint in python (with code)

How to use Flask blueprint in python (with code)

不言
不言forward
2018-11-15 15:07:044749browse

The content of this article is about how to use Flask blueprint in python (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Blueprint

We have learned some basic usage of Flask through code before. Now a problem arises. We have more and more functions to do. Is routing Should it be placed in the run file? For example, we have defined some routes in different files. If we want to access them, do we need to open many different services?

Blueprints are provided in Flask, specifically used for modularization of Flask.

Flask uses the concept of blueprints to make application components and support common patterns within or across applications. Blueprints can greatly simplify how large applications work and provide a central means for Flask extensions to register actions on the application. The Blueprint object works similarly to the Flask application object, but it is not actually an application. Rather, it is a blueprint for how to structure or extend an application.

In short, blueprints can make our program more modular. Routes for different functions can be placed under different modules, and finally concentrated into the startup class.

First, create a new flask project file and create a file structure as shown below:

How to use Flask blueprint in python (with code)

Main running file

from app.movie.view import movie as movie_bp
from app.tag.view import tag as tag_bp
from flask import Flask


if __name__ == '__main__':
    app = Flask(__name__)
    app.register_blueprint(tag_bp,url_prefix='/tag')
    app.register_blueprint(movie_bp,url_prefix='/movie')
    app.run(port=9099)

Module One: Tag

All routing and view functions are still written in a separate file, named here view.py

from flask import Blueprint


tag = Blueprint('tag',__name__)
@tag.route('/')
def index():
    return 'ok'

@tag.route('/add/')
def add():
    return 'tag add'

Module Two: Movie

All routing and view functions are still written in a separate file, named here view.py

from flask import Blueprint


movie = Blueprint('movie',__name__)
@movie.route('/')
def index():
    return 'ok'

@movie.route('/add/')
def add():
    return 'movie add'

Running results

How to use Flask blueprint in python (with code)

How to use Flask blueprint in python (with code)

The above is the detailed content of How to use Flask blueprint in python (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete