我正在与一个曾经向我发送如下 HTTP 字符串的服务器通信:
/path/to/my/handler/?action-query&id=112&type=vca&info=ch=0&type=event&ev16[sts=begin (...)
因此“info”GET 参数包含“=”和“&”字符。这是相当不正统的,但我们还是为它写了一个解析器。然而,最近他们决定对其中的一部分进行编码,所以现在字符串看起来像这样......
/path/to/my/handler/?action=query&id=112&type=vca&info=ch%3D0%26type%3Devent%26ev46[sts%3Dbegin (...)
这破坏了我们的解析器,它需要一个像第一个那样的字符串。
我能否以某种方式“反编码”字符串,以便我可以使用旧代码(这样它就不会在我们重新编写解析器时被破坏)?
按照下面的回答,我们可以使用 urllib.unquote() 来清理字符串。但是,我们依赖于 request.GET,它是根据第一个字符串设置的。是否可以根据新转换的字符串重建 GET 对象,或者以某种方式强制它重新评估?
最佳答案
我怀疑您想要的是 urllib
模块中的 unquote
函数。
>>> s = '/path/to/my/handler/?action=query&id=112&type=vca&info=ch%3D0%26type%3Devent%26ev46[sts%3Dbegin'
>>> import urllib
>>> urllib.unquote(s)
'/path/to/my/handler/?action=query&id=112&type=vca&info=ch=0&type=event&ev46[sts=begin'
编辑:我对 Django 不是很熟悉,但是 Request and response object section of their docs陈述如下:
QueryDict instances are immutable, unless you create a copy() of them. That means you can't change attributes of request.POST and request.GET directly.
根据我对这些文档的有限阅读,您可以将 unquote()
函数应用于 HttpRequest.body
属性并构建一个新的 QueryDict
结果(如有必要,可能使用它来更新您当前的结果)。
关于python - 反编码 URL 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11215298/