python - 两个 flask 蓝图的 url_prefix 相同

标签 python flask routing

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

/必须呈现 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/

相关文章:

routing - yii2 中的未知类异常的 404 错误

python - Python 中的 Sympy 未给出所需结果

python - 自动化无聊的东西-第5章-国际象棋字典验证器

python - 在Python中导入颜色科学模块时出现"TypeError"

python - 管理 Flask 应用程序对限速 API 的调用

vb.net - 如何告诉浏览器使用特定接口(interface),忽略路由

python 类就像一个列表

python - 使用 uWSGI 在 nginx 下部署的 Flask 在哪里获取我的 Python 打印件?

python - 我不明白让 config.py 隐藏我的 key 有什么意义?

routing - Laravel 4 托管在在线共享服务器上