我看到 Flask 在 Request 中提供了一些 parsed fields,但是 url 是在删除转义之后的。在 Flask 进行取消转义之前,有什么方法可以访问 url 吗?
例如,当 REST 客户端请求“http://www.example.com/my_url%20is%20here?arg1=2&?arg2=3”时,Flask 会向我提供“http”的 request.base_url ://www.example.com/my_url 在这里”,其中 %20 被空格替换。我可以自己引用这个来获取某人回复时的原始 URL,但最好我想访问客户端发送的原始 URL,而不是派生它。
这些字段不是 URL,甚至不是 URI,它们是 IRI。使用
iri_to_uri
:
from werkzeug.urls import iri_to_uri
iri_to_uri(request.url)
"""
...
Note that the string returned might contain unicode characters as the
representation is an IRI not an URI. If you need an ASCII only
representation you can use the :func:`~werkzeug.urls.iri_to_uri`
function:
>>> from werkzeug.urls import iri_to_uri
>>> iri_to_uri(get_current_url(env))
'http://localhost/script/?param=foo'
...
"""
flask 和 werkzeug 的好处之一是您始终可以在源代码中跟踪事情。
Flask3 具有
url
属性 (https://flask.palletsprojects.com/en/3.0.x/api/#flask.Request.url)from flask import request
...
@app.route(...)
def myhandler(...):
print(request.url)
你的意思是%XX逃逸了?
from urllib.parse import quote
quote(url)