python - 使用蓝图在 Flask 中重复 url_prefix

标签 python flask jinja2

抱歉,我在 stackoverflow 和 google 中进行了搜索,但没有找到有用的信息。 我有一个 flask 应用程序, python 版本2.6 flask 版本0.9

它的应用程序层次结构就像

  application/
     __init__.py
     app.py
     hello/
       __init__.py
       view.py
       templates/
         hello.html

两个文件init.py都是空的

app.py
-----------------------
from flask import Flask
from flup.server.fcgi import WSGIServer
from hello.view import hello

app = Flask(__name__)
app.debug = True 

app.register_blueprint(hello, url_prefix='/hello')

if __name__ == '__main__':
    WSGIServer(app, bindAddress='/tmp/app.sock').run()

view.py
-----------------------
import os
from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound

hello = Blueprint('hello', __name__, template_folder='templates')

@hello.route('/')
def get_index():
    try:
        return render_template('hello.html')
    except TemplateNotFound:
        abort(404)

hello.html
-----------------------
<!DOCTYPE html>
<html>
    <head>
        {% block head %}
        <meta charset="utf-8">
        {% endblock %}
    </head>
    <body>
        <div>
            {% block body %}
            <h1><a href="{{ url_for('hello.get_index') }}">Click Me</a></h1>
        {% endblock %}
        </div>
    </body>
</html>

当我输入localhost:8080/hello时,它工作正常,但如果我单击html中的链接,则会出现错误。我发现它的 url 值为 href="/hello/hello/" (应该是 /hello/ 对吗?)。 我知道 hello.get_index 映射到 /hello/,但不知道第一个 hello/ 来自。任何提示表示赞赏。

最佳答案

您是否尝试在注册蓝图时删除 url_prefix 参数?例如,如果您将以下内容更改为:

app.register_blueprint(hello, url_prefix='/hello')

app.register_blueprint(hello)

关于python - 使用蓝图在 Flask 中重复 url_prefix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11663244/

相关文章:

python - pandas dataframe上的for-if循环语句操作问题

python - 多个 Django 模板加载器

python - 如何设置 django 1.8 以使用 jinja2?

python - 在 Python 中 issubclass() 意外地提示 "Protocols with non-method members"

以列表作为值的 Python 字典到 Pandas 数据框

python - 为什么 `pip install hwrt --upgrade`会升级到随机版本(有时也会降级)?

reactjs - Vite + React + Flask 不代理前端到后端

javascript - onclick 加载 {% include 'test.html' %}

Python Flask,使用重新加载器重新启动 : What does that mean

ansible - 有条件地连接 jinja2 列表