在 Flask 中扩展蓝图,将其拆分为多个文件

Chr*_*cht 5 python flask

在烧瓶中,我有一个有点太长的蓝图,我想使用相同的路线将其分成几个文件/games

我尝试延长课程时间,但不起作用?

# games.py
from flask import Blueprint

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

@bp.route('/')
def index():
    ...
Run Code Online (Sandbox Code Playgroud)

# games_extend.py
from .games import bp

@bp.route('/test')
def test_view():
    return "Hi!"
Run Code Online (Sandbox Code Playgroud)

我做错了什么还是有更好的方法?

小智 4

您可以使用绝对路径名(包)使其工作,具体方法如下:

应用程序.py

from __future__ import absolute_import
from flask import Flask
from werkzeug.utils import import_string

api_blueprints = [
    'games',
    'games_ext'
]

def create_app():
    """ Create flask application. """
    app = Flask(__name__)

    # Register blueprints
    for bp_name in api_blueprints:
        print('Registering bp: %s' % bp_name)
        bp = import_string('bp.%s:bp' % (bp_name))
        app.register_blueprint(bp)

    return app

if __name__ == '__main__':
    """ Main entrypoint. """
    app = create_app()
    print('Created app.')
    app.run()
Run Code Online (Sandbox Code Playgroud)

bp/初始化.py

bp/games.py

from __future__ import absolute_import
from flask import Blueprint, jsonify

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

@bp.route('/')
def index():
    return jsonify({'games': []})
Run Code Online (Sandbox Code Playgroud)

bp/games_ext.py

from .games import bp

@bp.route('/test')
def test_view():
    return "Hi!"
Run Code Online (Sandbox Code Playgroud)

使用以下命令启动您的服务器:python -m app

然后将 Get 查询发送到 /games/ 和 /games/test/ 端点。为我工作。

干杯!