gpt4 book ai didi

python - 两个 flask 蓝图的 url_prefix 相同

转载 作者:太空狗 更新时间:2023-10-30 02:38:28 25 4
gpt4 key购买 nike

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

/必须呈现 home.html

/one , /two , /three必须呈现 one.html , two.html , three.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('/')呈现 home.html .当与 category_page 混合时,这个也不起作用蓝图

最佳答案

您可以将变量移动到注册语句中的 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>')

(这取决于整个模式的复杂程度,但最好让带有变量的注册语句靠近每个函数以处理多个 View 。)

关于python - 两个 flask 蓝图的 url_prefix 相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46870909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com