简体   繁体   English

使用python-requests发布数据

[英]post data using python-requests

I'm trying to post the following data. 我正在尝试发布以下数据。 But I'm getting an error. 但是我遇到了错误。 Can you please take look? 你能看看吗? Thanks a lot. 非常感谢。

I'm posting the same data using Postman. 我正在使用邮递员发布相同的数据。 And it works. 而且有效。

def _build_post_data(bike_instance):
    """
    data = {
        "apikey": "XXX",
        "data": {
            "created_at": "date_XX",
            "Price": "Decimal_XX"
        }
    }
    """
    data = {}
    raw_data = serializers.serialize('python', [bike_instance])
    actual_data = [d['fields'] for d in raw_data]
    data.update(
        {
            "apikey": XXX,
            "data": actual_data[0]
        }
    )
    return data

Posting data 发布数据

bike = Bike.objects.get(pk=XXX)

data = _build_post_data(bike)

dump_data = json.dumps(data, cls=DjangoJSONEncoder)

requests.post(url, data=dump_data)

error 错误

u'{"error":{"message":"422 Unprocessable Entity","errors":[["The data field is required."],["The apikey field is required."]],"status_code":422}}'

data and apikey already in the dict. dataapikey已经在字典中。 then why I'm getting an error? 那为什么我会出错? Any idea? 任何想法?

Postman works 邮递员的作品

在此处输入图片说明

With Postman you are sending a multipart/form-data request, with requests you only send JSON (the value of the data field in Postman), and are not including the apikey field. 使用Postman,您将发送multipart/form-data请求,使用requests您将仅发送JSON (Postman中data字段的值),并且不包括apikey字段。

Use a dictionary with the JSON data as one of the values, and pass that in as the files argument. 使用带有JSON数据作为值之一的字典,并将其作为files参数传递。 It probably also works as the data argument (sent as application/x-www-urlencoded ): 它也可能用作data参数(发送为application/x-www-urlencoded ):

form_structure = {'apikey': 'XXXX', 'data': dump_data}
requests.post(url, files=form_structure)
# probably works too: requests.post(url, data=form_structure)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM