如何从 Django 中的编码 URL 获取请求参数?
How to get request parameters from an encoded URL in Django?
我正在使用 Django Rest 框架。
API 接收带有编码到 URL 中的 json 对象的 GET 请求。例如:
/endpoint?%7B%0D%0A++%22foo%22%3A%5B%22bar%22%2C%22baz%22%5D%0D%0A%7D
解码后的参数在哪里
{
"foo":["bar","baz"]
}
我在 Django 或 DRF 的文档中找不到任何关于框架如何处理这个问题的内容,因此我通过执行类似:
request.query_params # Should yield a dict -> {foo=[bar,baz]}
如何在 Django Rest Framework 中解码 JSON 编码的 URL?
请注意,我的实际参数要复杂得多。使用 POST 不是因为调用者严重依赖缓存和书签
urllib
应该这样做:
from urllib.parse import unquote
url = "endpoint?%7B%0D%0A++%22foo%22%3A%5B%22bar%22%2C%22baz%22%5D%0D%0A%7D"
url = unquote(url)
print(url)
上面差不多可以,但是可能编码不对,不确定:
endpoint?{
++"foo":["bar","baz"]
}
Django request.GET
对象,以及Django REST添加的request.query_params
别名,只能解析application/x-www-form-urlencoded
query strings, the type encoded by using a HTML form. This format can only encode key-value pairs. There is no standard for encoding JSON into a query string, partly because URLs have a rather limited amount of space.
如果您必须在查询字符串中使用 JSON,那么 prefixed the JSON data with a key name 对您来说会容易得多,因此您至少可以让 Django 处理 URL%为你编码。
例如
/endpoint?json=%7B%0D%0A++%22foo%22%3A%5B%22bar%22%2C%22baz%22%5D%0D%0A%7D
可以通过以下方式访问和解码:
import json
json_string = request.query_params['json']
data = json.loads(json_string)
如果不能加json=
前缀,需要自己解码URL%编码urllib.parse.unquote_plus()
, from the request.META['QUERY_STRING']
value:
from urllib.parse import unquote_plus
import json
json_string = unquote_plus(request.META['QUERY_STRING'])
data = json.loads(json_string)
我正在使用 Django Rest 框架。
API 接收带有编码到 URL 中的 json 对象的 GET 请求。例如:
/endpoint?%7B%0D%0A++%22foo%22%3A%5B%22bar%22%2C%22baz%22%5D%0D%0A%7D
解码后的参数在哪里
{
"foo":["bar","baz"]
}
我在 Django 或 DRF 的文档中找不到任何关于框架如何处理这个问题的内容,因此我通过执行类似:
request.query_params # Should yield a dict -> {foo=[bar,baz]}
如何在 Django Rest Framework 中解码 JSON 编码的 URL?
请注意,我的实际参数要复杂得多。使用 POST 不是因为调用者严重依赖缓存和书签
urllib
应该这样做:
from urllib.parse import unquote
url = "endpoint?%7B%0D%0A++%22foo%22%3A%5B%22bar%22%2C%22baz%22%5D%0D%0A%7D"
url = unquote(url)
print(url)
上面差不多可以,但是可能编码不对,不确定:
endpoint?{
++"foo":["bar","baz"]
}
Django request.GET
对象,以及Django REST添加的request.query_params
别名,只能解析application/x-www-form-urlencoded
query strings, the type encoded by using a HTML form. This format can only encode key-value pairs. There is no standard for encoding JSON into a query string, partly because URLs have a rather limited amount of space.
如果您必须在查询字符串中使用 JSON,那么 prefixed the JSON data with a key name 对您来说会容易得多,因此您至少可以让 Django 处理 URL%为你编码。
例如
/endpoint?json=%7B%0D%0A++%22foo%22%3A%5B%22bar%22%2C%22baz%22%5D%0D%0A%7D
可以通过以下方式访问和解码:
import json
json_string = request.query_params['json']
data = json.loads(json_string)
如果不能加json=
前缀,需要自己解码URL%编码urllib.parse.unquote_plus()
, from the request.META['QUERY_STRING']
value:
from urllib.parse import unquote_plus
import json
json_string = unquote_plus(request.META['QUERY_STRING'])
data = json.loads(json_string)