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