【问题标题】:PUT request made with Python requests module has no data使用 Python requests 模块发出的 PUT 请求没有数据
【发布时间】:2016-05-17 07:59:26
【问题描述】:

我正在开发一个 Python REST api,对于服务器端,我使用 Django 和 django-rest-framework。我设法在 chrome 中使用 AdvancedRestClient 成功测试了我的 api,但我无法让它与 python 请求一起工作。

我的 ARC 请求如下所示:

对于我的测试 Python 请求,我编写了以下代码:

import requests
import json

payload = {"TimeStamp": "2016-02-07T13:38:16Z", "DateInserted": "2016-02-07T13:38:18Z", "Value": 17.145, "Sensor": 1}
url = "http://127.0.0.1:8000/api/Readings"
headers = {"Content-Type": "application/json", "Authorization": "966271f8-94a3-4232-95f7-953f3b7989f3"}
r = requests.put(url, data=json.dumps(payload), headers=headers)

我尝试了许多不同的方法,例如使用 json= 而不是 data=,但是当我的请求到达我的服务器端时,它们似乎总是没有数据内容。我搜索了网络,但找不到任何使用 POST 处理请求的可行示例,所以我希望有人能与我分享一些第一手经验。

更新: 以下代码现在适用于 django-rest-framework。

payload = {"TimeStamp": "2016-02-07T13:38:16Z", "DateInserted": "2016-02-07T13:38:18Z", "Value": 12.123, "Sensor": 1}
url = "http://127.0.0.1:8000/api/Readings/"
headers = {"Content-Type": "application/json", "Authorization": "966271f8-94a3-4232-95f7-953f3b7989f3"}
r = requests.put(url, data=json.dumps(payload), headers=headers)

【问题讨论】:

  • 您的请求在我看来是正确的。尝试使用http://httpbin.org/put 查看您实际发送的内容。
  • 可以在token前加Token吗? "令牌'966271f8-94a3-4232-95f7-953f3b7989f3'"
  • 请将print json.dumps(json.loads(r.text), indent=4)print r.status_code 添加到您的snipplet 并报告结果。 (同时在Authorization 标头中添加Token 。)
  • 我正在使用我自己的自定义授权,因此不需要令牌。我设法让它工作,请参阅下面的评论。

标签: python json django django-rest-framework python-requests


【解决方案1】:

默认情况下,DRF 有一个尾随空格。代替 http://127.0.0.1:8000/api/Readings 应该是 http://127.0.0.1:8000/api/Readings/ 。我建议将Readings设为小写,因为很容易忘记它是大写的


我使用的 API 测试的一般结构是这样的:

from django.core.urlresolvers import reverse

from rest_framework.test import APITestCase, APIClient

class TestReadings(APITestCase):

    def setUp(self):
        self.client = APIClient()

    def test_put(self):

        url = reverse('readings', kwargs={}) # 'readings' here is the named url
        request = self.client.post(url, data={})

【讨论】:

  • 我设法让它工作。为了做到这一点,我不得不改变两件事。当我将 / 添加到读数时,我开始看到数据通过,但格式不正确。所以我必须改变的第二件事是放 data= 而不是 json=。谢谢大家的帮助。
猜你喜欢
  • 2013-03-12
  • 1970-01-01
  • 2023-03-29
  • 2018-07-04
  • 2012-10-20
  • 1970-01-01
  • 1970-01-01
  • 2017-12-25
  • 2014-08-03
相关资源
最近更新 更多