Django使用Json进行呼叫. Common_Unsupported_Media_Type [英] Django calls with Json. Common_Unsupported_Media_Type

查看:320
本文介绍了Django使用Json进行呼叫. Common_Unsupported_Media_Type的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用request.post在python/django中进行RESTful api调用

I'm trying to make a RESTful api call in python/django with requests.post

我可以使request.get(url = url,auth = auth)正常工作.该公司在相同api系列中的类似调用

I can get requests.get(url=url, auth=auth) to work. Similar call in the same api family for this company

我正在尝试:

data = {'start': 13388, 'end': 133885, 'name': 'marcus0.5'}
r = requests.post(url=url, auth=auth, headers={'Accept': 'application/json'}, data=data)

,我收到以下错误消息:

and I get the following error:

>>> r.text
     u'{"status":"error","errorCode":"COMMON_UNSUPPORTED_MEDIA_TYPE","incidentId":"czEtbXNyZXBvcnRzMDQuc3RhZ2V4dHJhbmV0LmFrYW1haS5jb20jMTM3NTgxMzc3MTk4NQ==","errorMessage":"The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.. Content type \'application/x-www-form-urlencoded;charset=UTF-8\' not supported."}'

我认为它与json有关,但是我不确定该怎么办,也不确定如何修复它.有什么想法吗?

I think it has something to do with the json, but I'm not sure what and I'm not sure how to fix it. Any ideas?

其他信息[不确定是否适用]:

Extra info [not sure if it applies]:

我导入了

import requests, django

我知道身份验证是正确的,并使用get方法对其进行了测试

I know the the auth is correct and I tested it with the get method

推荐答案

您要将请求的Content-Type参数设置为'application/json',而不是Accept参数.

You want to set the Content-Type parameter of your request to 'application/json', not the Accept parameter.

来自 w3.org :

接受请求标头"字段可用于指定响应可接受的某些媒体类型.

The Accept request-header field can be used to specify certain media types which are acceptable for the response.

尝试以下方法:

import json

data = {'start': 13388, 'end': 133885, 'name': 'marcus0.5'}
r = requests.post(url=url, auth=auth, data=json.dumps(data),
                  headers={'content-type': 'application/json'})

关于何时将数据作为dict或json编码的字符串(即json.dumps的结果)发送时,也有一些困惑(对我来说也是如此). 此处上有一篇很好的文章,解释了该问题.有关简短摘要,请在API需要表单编码的数据时发送dict,而在需要JSON编码的数据时发送json编码的字符串.

There is a little bit of confusion (for me as well) about when to send data as a dict or a json encoded string (ie. the result of json.dumps). There is an excellent post here that explains the problem. For a brief summary send a dict when the API requires form-encoded data, and a json encoded string when it requires json-encoded data.

这篇关于Django使用Json进行呼叫. Common_Unsupported_Media_Type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆