两个Flask蓝图的url前缀相同

2024-03-28 18:58:13 发布

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

我想实现简单的站点布局:

/必须呈现home.html

/one/two/three必须相应地呈现one.htmltwo.htmlthree.html

到目前为止,我想出了以下代码:

main_page = Blueprint('main', __name__)
category_page = Blueprint('category', __name__)


@main_page.route("/")
def home():
    return render_template('home.html')


@category_page.route('/<category>')
def show(category):
    return render_template('{}.html'.format(category))

app = Flask(__name__)
app.register_blueprint(main_page, url_prefix='/')
app.register_blueprint(category_page, url_prefix='/categories')

这样我就可以将categories路由到/categories/<category>。如何将它们路由到/<category>,同时保持home.html链接到{}?感谢你的帮助

我尝试了两种方法:

  1. 为两个蓝图设置url_prefix='/'=>;第二个蓝图不起作用。

  2. 不要使用main_page蓝图,只需使用app.route('/')来呈现{}。当与category_pageblueprint混合时,这个也不起作用


Tags: nameappurlhomeprefixmainhtmlpage
1条回答
网友
1楼 · 发布于 2024-03-28 18:58:13

可以将变量移动到registing语句内的url_prefix参数:

@main_page.route("/")
def home():
    return render_template('home.html')
app.register_blueprint(main_page, url_prefix='/')

@category_page.route('/')
def show(category):
    return render_template('{}.html'.format(category))        
app.register_blueprint(category_page, url_prefix='/<category>')

(这取决于整个模式的复杂性,但最好将带有变量的注册语句保持在每个函数附近,以处理多个视图。)

相关问题 更多 >