Django 2.2.4和DRF 3.9.4-不支持GET方法JSON body?
这: 为此:Django 2.2.4和DRF 3.9.4-不支持GET方法JSON body?,django,django-rest-framework,Django,Django Rest Framework,这: 为此: curl "http://localhost:8000/v1/post" \ -H 'Content-Type: application/json' \ -H 'Accept-Encoding: gzip' \ -d $'{ "url": "/my-test-url" }' 打印行崩溃 class PostView(APIView): def get(self, request, format=None): print(r
curl "http://localhost:8000/v1/post" \
-H 'Content-Type: application/json' \
-H 'Accept-Encoding: gzip' \
-d $'{
"url": "/my-test-url"
}'
打印行崩溃
class PostView(APIView):
def get(self, request, format=None):
print(request.data['url'])
result = {}
return Response(result)
但是,将GET改为POST:
KeyError: 'url'
我会把它打印出来的
curl -X "POST" "http://localhost:8000/v1/post" \
-H 'Content-Type: application/json' \
-H 'Accept-Encoding: gzip' \
-d $'{
"url": "/my-test-url"
}'
class PostView(APIView):
def post(self, request, format=None):
print(request.data['url'])
result = {}
return Response(result)
这使我相信Django要么不能处理GET
请求正文负载,要么我必须使用URL参数来代替GET
——要么我缺少了一些东西
我做错了什么
GET
请求没有正文,这就是数据
为空的原因
如果您想使用GET
请求传递某些内容,则需要使用querystring参数(例如:http://localhost:8000/v1/post?url=myurl
),然后您可以使用请求.查询参数
而不是请求.数据
(例如:请求.查询参数['url']
)
有关更多详细信息,请参阅文档。您可以尝试以下方法:
curl-X GEThttp://localhost:8000/v1/post -H'内容类型:application/json'-H'接受编码:gzip'-d'{“url”:“/my test url”}”
是的。计算了那么多,但这是Django的决定,而不是HTTP。HTTP规范并不禁止在GET上使用body。像ElasticSearch这样的服务器在GET上使用JSON主体。
/my-test-url
[26/Nov/2019 22:00:42] "POST /v1/post HTTP/1.1" 200 2