在Flask中扩展一个蓝图,将其分成几个文件

时间:2019-06-05 14:48:06

标签: python flask

在烧瓶中,我有一个蓝图,该蓝图太长了,我想使用同一条路径/games将其分成几个文件

我尝试扩展该类,但这行不通吗?

# games.py
from flask import Blueprint

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

@bp.route('/')
def index():
    ...

# games_extend.py
from .games import bp

@bp.route('/test')
def test_view():
    return "Hi!"

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

1 个答案:

答案 0 :(得分:1)

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

app.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()

bp / init .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': []})

bp / games_ext.py

from .games import bp

@bp.route('/test')
def test_view():
    return "Hi!"

使用python -m app

启动服务器

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

干杯!