我尝试将使用python运行的服务通过http PATCH
请求发送到使用Django API Rest Framework requests的另一个正在运行Django的数据。
SomeAccount
的字段appUserId
现在为-1
。
以下是 some_sender.py 谁知道app_user_id
(=77
,例如。)
auth = ('someusrname', 'somepwd')
data = {"appUserId": app_user_id}
url = 'myapi:8000/someaccounts/1'
r = requests.patch(url, data=data, auth=auth)
print r.status_code
#> 200
当我在GET /someaccounts/1
检查项目的值时,它仍然有appUserId=-1
。
在调试时,在Django中我得到了请求,但没有任何数据 - 它只是一个空的字典。
以下是我在Django中的表现:
mysite的/ MyApp的/ urls.py :
from django.conf.urls import include, url
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'someaccount', views.SomeAccountViewSet)
# ...
urlpatterns = [
url(r'^', include(router.urls)),
# ...
]
mysite的/ MyApp的/ models.py :
from django.db import models
# ...
class SomeAccount(models.Model):
"""
Some account can include all the data related to some user's account.
"""
# ...
appUserId = models.BigIntegerField(blank=True, null=True)
mysite的/ MyApp的/ views.py :
class SomeAccountViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows some accounts to be viewed or edited.
"""
queryset = SomeAccount.objects.all()
serializer_class = SomeAccountSerializer
mysite的/ MyApp的/ serializers.py :
from models import SomeAccount
# ...
class SomeAccountSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField()
class Meta:
model = SomeAccount
fields = ('url', 'id', 'appUserId')
depth = 3
partial = True
def update(self, someAccount, account_data):
if 'appUserId' in account_data:
someAccount.appUserId = account_data.pop('appUserId')
someAccount.save()
return someAccount
在SomeAccountSerializer
调试传入请求时,我得到以下值:
account_data: {}
initial_data: <QueryDict: {}>
someAccount: {'appUserId': -1, 'id': 1}
我尝试通过Postman Google Chrome插件发送相同的值,但它确实有效。
我还尝试设置content-type
标题:
application/x-www-form-urlencoded
:
requests.patch(
url, data=data, auth=auth,
headers={'content-type': 'application/x-www-form-urlencoded'}
)
application/form-data
:
requests.patch(
url, data=data, auth=auth,
headers={'content-type': 'application/form-data'}
)
application/json
:
requests.patch(
url, json=json.dumps(data), auth=auth,
headers={'content-type': 'application/json'}
)
没有成功。
编辑: python-requests正在发送请求。问题可能在于Django如何处理它。
答案 0 :(得分:1)
就遇到了同样的问题。网址末尾缺少斜杠。当Django使用斜杠重定向到URL时,它似乎掉落了PATCH的有效载荷。
答案 1 :(得分:0)
您应检查网络流量以确定问题出现的位置。如果我使用
import requests
app_user_id = 7
auth = ('someusrname', 'somepwd')
data = {'appUserId': app_user_id}
url = 'http://localhost:8000/someaccounts/1'
r = requests.put(url, data=data, auth=auth)
print r.status_code
用netcat打开一个本地套接字(nc -l 8000)我得到的是数据格式编码:
PUT /someaccounts/1 HTTP/1.1
Host: localhost:8000
Content-Length: 11
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.8.1
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Authorization: Basic c29tZXVzcm5hbWU6c29tZXB3ZA==
appUserId=7