官术网_书友最值得收藏!

Blueprints

When you write microservices that have more than a single endpoint, you will end up with a handful of decorated functions--maybe, a few per endpoint. The first logical step to organize your code is to have one module per endpoint, and when you create your app instance, to make sure they get imported so that Flask registers the views.

For example, if your microservice manages a company employees database, you could have one endpoint to interact with all employees, and one with teams. You could organize your application in these three modules:

  • app.py: To contain the Flask app object, and to run the app
  • employees.py: To provide all the views related to employees
  • teams.py: To provide all the views related to teams

From there, employee and teams can be seen as a subset of the app, and might have a few specific utilities and configuration.

Blueprints take that logic a step further by providing a way to group your views into namespaces. You can create a Blueprint object which looks like a Flask app object, and then use it to arrange some views. The initialization process can then register blueprints with app.register_blueprint. That call will make sure that all the views defined in the blueprint are part of the app.

A possible implementation of the employee's blueprint could be as follows:

    from flask import Blueprint, jsonify 

teams = Blueprint('teams', __name__)

_DEVS = ['Tarek', 'Bob']
_OPS = ['Bill']
_TEAMS = {1: _DEVS, 2: _OPS}

@teams.route('/teams')
def get_all():
return jsonify(_TEAMS)

@teams.route('/teams/<int:team_id>')
def get_team(team_id):
return jsonify(_TEAMS[team_id])

The main module (app.py) can then import this file, and register its blueprint with app.register_blueprint(teams).

This mechanism is also interesting when you want to reuse a generic set of views in another application, or several times in the same application.

The Flask-Restless (https://flask-restless.readthedocs.io) extension, for instance, which is a Create, Read, Update, and Delete (CRUD) tool that automatically exposes a database through a REST API by introspecting SQLAlchemy models, generates one blueprint per SQLAlchemy model.

The following is from the Flask-Restless documentation (Person is SQLAlchemy model):

    blueprint = manager.create_api_blueprint(Person, methods=['GET', 
'POST'])
app.register_blueprint(blueprint)
主站蜘蛛池模板: 西宁市| 屏东县| 赣州市| 石河子市| 个旧市| 宜昌市| 任丘市| 溧阳市| 铜川市| 广汉市| 百色市| 阿克苏市| 临夏市| 黔江区| 勃利县| 陈巴尔虎旗| 衢州市| 伊吾县| 五峰| 宁陵县| 平江县| 宣武区| 安溪县| 安化县| 牙克石市| 包头市| 开远市| 五常市| 哈尔滨市| 息烽县| 临泽县| 福泉市| 霍城县| 望都县| 凤庆县| 长白| 麻栗坡县| 东光县| 兴仁县| 岳普湖县| 格尔木市|