Flask{request.script_根|tojson | safe}}未返回值

2024-04-28 22:44:35 发布

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

我下面是许多基本的Flask教程中的一个,其中{{ request.script_root|tojson|safe }}Jinja2模板调用应该返回应用程序的基根(per Flask docshere)。在

我有一个super基本脚本设置:

# app/__init__.py

from flask import Flask

# import blueprints
from .views.index import index_blueprint

# create flask app
app = Flask(__name__)

app.register_blueprint(index_blueprint)

这是我的Blueprint

^{pr2}$

最后,我的index.html模板(位于template文件夹中:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>

    <script type="text/javascript">

        var $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};

    </script>

</head>
<body>

    <p>Flask test.</p>

</body>
</html>

呈现之后,$SCRIPT_ROOT应该包含脚本根,或者至少包含一个非空字符串。但是,生成的填充模板包含一个空字符串:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>

    <script type="text/javascript">

        var $SCRIPT_ROOT = "";

    </script>

</head>
<body>

    <p>Flask test.</p>

</body>
</html>

问题是{{ request.script_root|tojson|safe }}为什么返回空字符串?在


Tags: import模板appflaskindextitlerequesthtml
2条回答

从实数doc

A simple method would be to add a script tag to our page that sets a global variable to the prefix to the root of the application. Something like this:

<script type=text/javascript>
  $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
</script>

对我来说,只添加这个标记而不添加var =

我猜你用的是烧瓶的WSGI。在这种情况下,Flask不知道SCRIPT_NAMEenv变量,因为通常HTTP服务器的工作是设置SCRIPT_NAME(以及PATH_INFO)。在

Flask使用此env var设置script_root属性(来自^{}类的相关函数):

@cached_property
def script_root(self):
    """The root path of the script without the trailing slash."""
    raw_path = wsgi_decoding_dance(self.environ.get('SCRIPT_NAME') or '',
                                   self.charset, self.encoding_errors)
    return raw_path.rstrip('/')

如果要手动设置,可以使用中间件(从this snippet)来实现:

^{pr2}$

在此之后,{{ request.script_root }}将在模板中/myapp。在

相关问题 更多 >