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保护取消

相关推荐
万化冥合1 分钟前
如何批量把 PPT 转成视频?
python·1024程序员节
xiangjiaodalishi14 分钟前
武汉玖叁鹿科技:我们把 GEO 服务做成了可以审计的交付工程
python·1024程序员节
zzu123zsw29 分钟前
为什么 Python 做 Agent 总在并发中崩溃?拆解 Blockcell 在 Rust 下的 Host-Cell 隔离与自愈状态机
开发语言·python·rust·大模型·ai agent
jiangliushi633 分钟前
GPT-6.1 Sol 免费用:Python 读文件报 ‘gbk‘ codec can‘t decode?加一个参数就好
python·编码·1024程序员节
餐赢计餐饮策划设计1 小时前
如何判断国潮养生设计是否适合自己?
python·1024程序员节
爱好曙光1 小时前
SQLite WAL 高并发写入:busy_timeout 与 checkpoint 调优实战
sqlite·性能调优·checkpoint·wal·并发写入
艾灸爱好者1 小时前
艾草精油专业制造商哪3点决定品质高低?
python·1024程序员节
weixin_440401691 小时前
大数据技术-人工智能编程题
大数据·人工智能·python·1024程序员节
“AI国潮设计-小江”2 小时前
AIGC实战:Python+SDXL批量生成英歌舞IP立牌,解锁猪猪蛋糕“反差萌”流量密码(附完整API源码)
开发语言·人工智能·python·prompt·aigc
成信吴彦祖2 小时前
当前专业的无人机RID侦测主站供应商主要有哪些
python·1024程序员节