简体   繁体   English

从请求正文django访问数据

[英]access data from request body django

I am using django v2.2.4 and need to access request body data. 我正在使用django v2.2.4 ,需要访问请求正文数据。

Here's my code: 这是我的代码:

@api_view(['POST'])
@renderer_classes((JSONRenderer,))
def index(request):
    if request.method == 'POST':
        results= []
        data = JSONParser().parse(request)
        serializer = ScrapeSerializer(data=data)

        if serializer.is_valid():           
            url = request.data.url
            #url = request.POST.get('url')

But I get this error: 但是我得到这个错误:

RawPostDataException at /scrape/
You cannot access body after reading from request's data stream

Here's the request body: 这是请求正文:

{
    "url": "xyz.com"
}

How can I access the request body? 如何访问请求正文?

I have found this SO post that related to this issue, Exception: You cannot access body after reading from request's data stream 我发现与此问题相关的SO帖子, 例外:从请求的数据流中读取后无法访问正文

Anyway use request.data instead of request.body in DRF 无论如何在DRF中使用request.data而不是request.body

@api_view(['POST'])
@renderer_classes((JSONRenderer,))
def index(request):
    if request.method == 'POST':
        results = []
        serializer = ScrapeSerializer(data=request.data)

        if serializer.is_valid():
            url = request.data["url"]

The request.data returns the parsed content of the request body and it will be dict like object , hence the dot operation ( request.data.url ) won't works here. request.data返回请求正文的解析内容,它将像对象一样dict ,因此点操作( request.data.url在这里不起作用。

要访问POST请求的请求正文,您可以通过url = request.POST.get("url")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 django.http.request.RawPostDataException:从请求的数据 stream 读取后,您无法访问正文 - django.http.request.RawPostDataException: You cannot access body after reading from request's data stream 使用DRF和django-revproxy时出现“异常:从请求的数据流读取后无法访问正文” - Getting “Exception: You cannot access body after reading from request's data stream” while working with DRF and django-revproxy 如何在单元测试 django 中从请求正文传递数据 - How to pass data from request body in unit test django 慢慢访问Django的request.body - Slow access to Django's request.body request.body中的Django json数据但为空 - Django json data in request.body but empty 如何访问存储从 postman 发送到 Django 服务器的文件数组的发布请求正文的字段? - How to access a field of the body of a post request that stores an array of files sent from postman to a Django server? 只有 Django request.body 包含数据(不是 request.POST) - Only Django request.body contains data (not request.POST) DRF 中的 request.data 与 Django 中的 request.body - request.data in DRF vs request.body in Django 为什么出现Django HttpRequest(POST)来将request.data设置为request.body中“ data”键的值? - Why does a Django HttpRequest (POST) appear to set request.data to the value of the “data” key from request.body? RawPostDataException:从请求的数据流读取后无法访问正文 - RawPostDataException: You cannot access body after reading from request's data stream
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM