我可以在Flask里建两层以上的端点吗?

2024-04-26 09:37:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道当flask构建大型应用程序时,它已经注册了多个蓝图。你知道吗

烧瓶蓝图开始初始化一个蓝图对象,它同时声明了端点的第一层的名称。你知道吗

例如:

users_bp = Blueprint('users', __name__)

根据表达式,users_bp端点的第一层的名称是users。你知道吗

blueprint对象继续注册它的view函数,它同时声明了第二层端点的名称。你知道吗

@users_bp.route('/login')
    def login():
        # do something

根据表达式,users_bp的第二层端点的名称是login,它来自视图名称。你知道吗

如果我想用endpoint得到相应的url,我应该做:url_for('users.login')。你知道吗

所以这是从flask教程构建大型应用程序的工作流程。对吗?你知道吗


让我们回到正题。是否可以将端点的三层构建为url_for('api. users.login')?你知道吗

如何打包蓝图或烧瓶应用程序来完成我想要的结构?有空吗?你知道吗


Tags: 对象name名称应用程序声明urlflaskfor
1条回答
网友
1楼 · 发布于 2024-04-26 09:37:03

可以在路由装饰器中设置端点,例如:

from flask import Flask, render_template_string

app = Flask(__name__)


@app.route('/', endpoint="this.is.the.home.endpoint")
def index():
    _html="<a href='{{url_for('this.is.another.endpoint')}}'>Go to another endpoint</a>"
    return render_template_string(_html)


@app.route('/another', endpoint="this.is.another.endpoint")
def another():
    _html="<a href='{{url_for('this.is.the.home.endpoint')}}'>Go to the home page</a>"
    return render_template_string(_html)

if __name__ == '__main__':
    app.run()

相关问题 更多 >