Python 如何在 jinja2/flask 中获取当前 URL(request.url 不起作用)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26276580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:19:02  来源:igfitidea点击:

How to get current URL in jinja2/flask (request.url not working)

pythonflaskjinja2

提问by alias51

Is there a way to print the current URL in Jinja2/Flask?

有没有办法在 Jinja2/Flask 中打印当前 URL?

E.g. if the current URL is http://www.domain.com/example/1/2

例如,如果当前 URL 是 http://www.domain.com/example/1/2

{{ request.path }}works and prints /example/1/2, but how to I get the full URL with http:// as well?

{{ request.path }}工作和打印/example/1/2,但如何使用 http:// 获取完整 URL?

From the docs (here){{ request.url }}should work, but it doesn't yield anything.

从文档(这里){{ request.url }}应该可以工作,但它不会产生任何结果。

Thanks

谢谢

UPDATE

更新

Here are the render/context args from views.py:

以下是来自 views.py 的渲染/上下文参数:

class EventDetailView(EventObjectMixin, FormView):
    template_name = 'gig/public/about.html'
    context_object_name = 'event'
    form_class = EventPurchaseTicketForm

    def get_context_data(self, **kwargs):
        context = super(EventDetailView, self).get_context_data(**kwargs)

    ...

        return context

采纳答案by hugoxia

You can use {{ url_for(request.endpoint) }}, it works.

你可以使用{{ url_for(request.endpoint) }},它的工作原理。

回答by gcerar

Find where you have similar code to this, usually found in controller.pyor __ init__.pyor views.py:

找到与此类似的代码,通常在controller.py__ init__.pyviews.py 中找到

from flask import render_template
...

@app.route('/example/<arg1>/<arg2>')
def some_view_function(arg1, arg2):
    ...

    return render_template('path/to/your/template.html')

With render_template()are request and other variables available to you.

您可以使用render_template()请求和其他变量。

回答by Dull Bananas

The flask.requestobject provides different ways to get the URL. See the documentationfor info.

flask.request对象提供了获取 URL 的不同方法。有关信息,请参阅文档