Extend a blueprint in Flask, splitting it into several files

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-11 08:43:49

问题


In flask, I have a blueprint that is getting a bit too long and I'd like to split it into several files, using the same route /games

I tried extending the class, but it doesn't work?

# 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!"

Am I doing something wrong or is there a better way?


回答1:


You can make it work using absolute path names (packages), here's how:

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!"

Start your server using: python -m app

Then send Get queries to /games/ and /games/test/ endpoints. Worked for me.

Cheers !



来源:https://stackoverflow.com/questions/56462914/extend-a-blueprint-in-flask-splitting-it-into-several-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!