python - 使用 Python requests 模块发出的 PUT 请求没有数据

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

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

我的 ARC 请求如下所示: enter image description here

对于我的测试 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)

最佳答案

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={})

关于python - 使用 Python requests 模块发出的 PUT 请求没有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35256384/

相关文章:

c++ - Python 将输入重定向到子进程

jquery - 在网页上显示youtube json供稿

javascript - ExtJS网格过滤器: how can I load 'list' filter options from external json?

angularjs - 从 token 创建 Django session

python - 洪水填充算法在 python 中崩溃

python - 如何在Python中平滑概率分布图?

java - Camel Rest DSL 响应编码

python - Django Auth,登录问题

python - 结合 django 管理器

python - Saltstack master 找不到执行模块,说不可用