Django 常用注解

@require_http_methods(["POST"])

  • @require_http_methods(["POST"]) 是 Django 提供的装饰器,确保该视图函数只能处理指定的 HTTP 方法(如 POST 请求)。
  • 如果客户端使用其他的 HTTP 方法(如 GET, PUT, DELETE),Django 会自动返回 HTTP 405 (Method Not Allowed) 错误。
  • 它的作用是简化对 HTTP 方法的限制,而不用手动在视图里检查 request.method

没有**@require_http_methods注解,需要方法内部自己if request.method == 'POST':**

复制代码
import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt  # 如果你没有启用 CSRF token 可以加上这个装饰器, 但要注意安全性
def add_car(request):
    if request.method == 'POST':
        try:
            # 读取并解析 JSON 请求体
            data = json.loads(request.body.decode('utf-8'))
            
            # 从 JSON 数据中获取参数
            car_name = data.get('name')
            car_model = data.get('model')
            
            # 在这里可以处理接收到的数据,例如保存到数据库
            # Car.objects.create(name=car_name, model=car_model)

            return JsonResponse({'status': 'success', 'message': 'Car added successfully'})
        except json.JSONDecodeError:
            return JsonResponse({'status': 'error', 'message': 'Invalid JSON'}, status=400)
    else:
        return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=405)

@csrf_exempt:

禁用视图的 CSRF 保护,不注释全局csrf中间件,使用此注解即可完成单个请求的csrf保护取消

相关推荐
sg_knight5 分钟前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
好运的阿财13 分钟前
process 工具与子agent管理机制详解
网络·人工智能·python·程序人生·ai编程
张張40823 分钟前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_4235339927 分钟前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python
Ricky111zzz1 小时前
leetcode学python记录1
python·算法·leetcode·职场和发展
小白学大数据1 小时前
Selenium+Python 爬虫:动态加载头条问答爬取
爬虫·python·selenium
Hui Baby1 小时前
springboot读取配置文件
后端·python·flask
阿Y加油吧1 小时前
回溯法经典难题:N 皇后问题 深度解析 + 二分查找入门(搜索插入位置)
开发语言·python
leo_messi941 小时前
2026版商城项目(三)-- ES+认证服务
后端·python·django
搜佛说2 小时前
比SQLite更快,比InfluxDB更轻:sfsDb的降维打击
jvm·数据库·物联网·架构·sqlite·边缘计算·iot