将Python Flask-Menu应用程序拆分为多个文件

时间:2014-11-16 21:06:59

标签: python flask

作为此问题的扩展Split Python Flask app into multiple files

我想使用Flask-Menu并在其自己的Python文件中包含每个单独的菜单页。

这是我的主网站main.py文件,其中包含/first菜单项

from flask import Flask, render_template, Blueprint, abort
from flask_wtf import Form
from flask.ext import menu

from wtforms import HiddenField

from second import bp_second

class EmptyForm(Form):
    hidden_field = HiddenField('You cannot see this', description='Nope')

def create_app(configfile=None):
    app = Flask(__name__)
    app.register_blueprint(bp_second)
    menu.Menu(app=app)

    @app.route('/')
    @menu.register_menu(app, '.', 'Home')
    def index():
        form = EmptyForm()
        form.validate_on_submit()
        return render_template('index.html', form=form)

    @app.route('/first')
    @menu.register_menu(app, '.first', 'First', order=0)
    def first():
        form = EmptyForm()
        form.validate_on_submit()
        return render_template('index.html', form=form)

    return app

if __name__ == '__main__':
    create_app().run(debug=True)

我有一个名为second.py的菜单项,其中包含/second菜单项

from flask import Blueprint, render_template
from flask_wtf import Form
from flask.ext import menu

from wtforms import TextField

class TextForm(Form):
    text = TextField(u'text', [validators.Length(min=2, max=5, message="my item")])

bp_second = Blueprint('second', __name__, url_prefix='/second')

@bp_second.route("/second")
@menu.register_menu(bp_second, '.second', 'Second', order=1)
def second():
    form = TickerForm()
    form.validate_on_submit() #to get error messages to the browser
    return render_template('index.html', form=form)

当我点击/second的菜单项时,我收到"GET /meta HTTP/1.1" 404 -消息。 //first菜单项工作

1 个答案:

答案 0 :(得分:1)

我怀疑,你的路线错了。当我读到你的的路线是/秒/秒所以你的菜单条目应该是

@menu.register_menu(bp_second, '.second.second', 'Second', order=1)

您可以查看有关Blueprints Support in Flask-Menu

的Flask-Menu文档