首页 > 其他分享 >when get data from request.POST or request.body

when get data from request.POST or request.body

时间:2024-09-05 17:47:54浏览次数:7  
标签:body Use form get request POST data

In Django, you can retrieve data from a request using either request.POST or request.body, depending on the content type of the request and how the data is being sent. Here’s a detailed explanation of when to use each:

1. Using request.POST

  • When to Use: Use request.POST when your form is submitted via a standard HTML form submission (using application/x-www-form-urlencoded or multipart/form-data content types).
  • How to Access: Data is accessed as a dictionary-like object.
  • def item_update(request, pk):
        if request.method == 'POST':
            name = request.POST.get('name')
            description = request.POST.get('description')
            # Process the data as needed

    2. Using request.body

    • When to Use: Use request.body when your request is sending JSON data (typically with the application/json content type) or when you are not using a standard form submission.
    • How to Access: You need to parse the raw body of the request because it will be a byte string. Use json.loads() to convert it to a Python dictionary.
      • import json
        from django.http import JsonResponse
        
        def item_update(request, pk):
            if request.method == 'POST':
                try:
                    data = json.loads(request.body)  # Parse the JSON data
                    name = data.get('name')
                    description = data.get('description')
                    # Process the data as needed
                    return JsonResponse({'success': True})
                except json.JSONDecodeError:
                    return JsonResponse({'error': 'Invalid JSON'}, status=400)

         

        Summary of Differences

        Featurerequest.POSTrequest.body
        Use Case Standard form submissions JSON data or raw body content
        Access Method Directly as a dictionary-like object Requires parsing with json.loads()
        Content-Type application/x-www-form-urlencoded or multipart/form-data application/json

        Conclusion

        • Use request.POST for traditional form submissions.
        • Use request.body when dealing with JSON or other raw data formats.
        • Ensure to handle errors (like JSON decoding errors) when using request.body.

标签:body,Use,form,get,request,POST,data
From: https://www.cnblogs.com/lxgbky/p/18398940

相关文章

  • MyRequestsHelper
    importrequestsimporttimeclassStateCodeError(Exception):"""状态码异常"""passclassContentError(Exception):"""内容异常"""passclassRequestHelper:"""未使用代理......
  • 【工具推荐】TomcatWeakPassChecker v2.2(最新版本) - Tomcat 漏洞一键漏洞利用getshe
    工具介绍:一键tomcat漏洞批量弱口令检测、后台部署war包getshell,该脚本用于检查ApacheTomcat管理页面的弱密码,并尝试通过上传自定义WAR包部署GodzillaWebshell。如果成功,将记录成功登录的信息以及获取到的Webshell地址。下载地址链接:https://pan.quark.cn/s/2062b75c4312环......
  • unittest+request+htmltestrunner为什么强于pytest+request+allure?
    关于接口自动化框架python的实现方案,主流的就unittest/pytest+request+htmltestrunner/allure。而unittest库相比于pytest在网上被各个博主喷的体无完肤,没有mark标记共功能,没有用例重跑机制、测试报告不如allure好看功能不如allure强大等等。但是我们深度思考后能否给自己提个......
  • gadget驱动框架(二)
    usb_composite_driver的创建于注册源码:drivers/usb/legacy/serial.c//创建usb_composite_driverstaticstructusb_composite_drivergserial_driver={.name="g_serial",.dev=&device_desc,.strings=dev_strings,.max_s......
  • How to use Node.js to get all files full paths that nested in folders All In On
    HowtouseNode.jstogetallfilesfullpathsthatnestedinfoldersAllInOne如何使用Node.js获取文件夹中嵌套的所有文件的完整路径demosESM//❌//importfsfrom'node:fs/promises';//✅import*asfsfrom'node:fs/promises';//import*asfsf......
  • 深入理解Widget有状态和无状态
    参考https://www.jb51.net/article/263730.htm无状态StatelessWidgetclassLessComponentextendsStatelessWidget{constLessComponent({Key?key}):super(key:key);@overrideWidgetbuild(BuildContextcontext){returnContainer();}}有状态......
  • 【git】fork远程仓库,fork仓库同步和提交pull request
    一、fork远程仓库,将会在你的GitHub账号中创建一个副本1.找到你想要的github仓库,点击Fork按钮 2.选择相应的Owner和想要clone的上游原始仓库的reponame,点击Createfork 3.fork创建成功(大概几秒钟就好了) 二、fork仓库同步上游仓库1.将上游仓库添加位远程仓库,并命......
  • gadget驱动框架(一)
    之前在linux移植udc驱动的时候,没有深入的理解整个gadget驱动框架,现在重新再屡屡gadget驱动,以便后期再次学习。本系列的文章以虚拟串口进行分析,相关源码均是基于linux4.19.123。gadget驱动框架gadget源码主要在:drivers/usb/gadget,以虚拟串口为例,对源文件做简单说明:drivers/usb/g......
  • 记一次代码审计之nbcio-boot从信息泄露到Getshell
    《Java代码审计》http://mp.weixin.qq.com/s?__biz=MzkwNjY1Mzc0Nw==&mid=2247484219&idx=1&sn=73564e316a4c9794019f15dd6b3ba9f6&chksm=c0e47a67f793f371e9f6a4fbc06e7929cb1480b7320fae34c32563307df3a28aca49d1a4addd&scene=21#wechat_redirect一、项目简介NBCI......
  • 在Android中发送网络请求(post和get的区别)
    get//将参数附加到URLStringurlWithParams=HttpConfig.GET_USER_NAME+"?qrCodeContent="+msg;//构建请求Requestrequest=newRequest.Builder().url(urlWithParams).addHeader("Authorization&q......