urllib.request 发送 http post 时如何修复 'This QueryDict instance is immutable'

how to fix 'This QueryDict instance is immutable' when send http post by urllib.request

我正在通过 urllib.request 写一个发件人,但在服务器中收到 "This QueryDict instance is immutable"。

当我在服务器代码(django tastypie)中添加 "bundle.request.POST._mutable = True" 时,它已修复。

但我想知道如何通过发件人解决。

python:v3.6 发件人:urllib.request 服务器:django tastypie

发件人:

   cookie = http.cookiejar.MozillaCookieJar()
   handler = urllib.request.HTTPCookieProcessor(cookie)
   opener = urllib.request.build_opener(handler)
   request = urllib.request.Request(url, 
                  data=data,headers=headers,method=method)
   rep = opener.open(request)

服务器错误:

File "/python3.6/site-packages/tastypie/resources.py", line 1408, in post_list
    updated_bundle = self.obj_create(bundle, **self.remove_api_resource_names(kwargs))
  File "/python3.6/site-packages/tastypie/resources.py", line 2244, in obj_create
    bundle = self.full_hydrate(bundle)
  File "/python3.6/site-packages/tastypie/resources.py", line 943, in full_hydrate
    bundle = self.hydrate(bundle)
  File "/home/ma/*/api.py", line 115, in hydrate
    bundle.data["create_by"] = user
  File "/python3.6/site-packages/django/http/request.py", line 421, in __setitem__
    self._assert_mutable()
  File "/python3.6/site-packages/django/http/request.py", line 418, in _assert_mutable
    raise AttributeError("This QueryDict instance is immutable")

我找到一个原因,application/x-www-form-urlencoded -> application/json。

对于那些在从 TestCases 发送有效载荷时在请求中获得 Querydict 类型,但在从前端(例如 React)传递数据时获得 Dict 类型的人 -您可以通过将有效负载作为 JSON 传递来避免处理 Querydict,因此,您的 request.data 将是 'dict'.

类型

例子

payload = {
            "name": "Dict example"
        }

response = self.client.post(ENDPOINT, json.dumps(chat_payload),content_type="application/json"

)

这样,您可以像普通字典一样访问request.data["name"],使操作更简单。