在Flask中扩展一个蓝图,将其分成几个文件 [英] Extend a blueprint in Flask, splitting it into several files

查看:60
本文介绍了在Flask中扩展一个蓝图,将其分成几个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在烧瓶中,我有一个蓝图,该蓝图太长了,我想使用同一路径/games

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?

推荐答案

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

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

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

来自__future__的

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

来自.games的

from .games import bp

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

使用以下代码启动服务器: python -m app

Start your server using: python -m app

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

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

干杯!

这篇关于在Flask中扩展一个蓝图,将其分成几个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆