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 小时前
Mac 通过 Miniconda 安装 Python
python·macos·conda·miniconda
就改了7 小时前
Java8 日期处理(详细版)
java·python·算法
威联通安全存储10 小时前
TS-h1887XU-RP在汽车发动机热试与NVH在线质检网中的部署
python·汽车
qq_3164110311 小时前
腹腔镜模拟手术训练数字化管理平台构建
人工智能·python·深度学习·机器学习
卷无止境11 小时前
PageIndex:把RAG的检索逻辑从"找相似"改成了"讲道理"
后端·python
卷无止境11 小时前
什么是VoxCPM2?一场TTS架构的彻底重构
后端·python
kisloy13 小时前
【爬虫入门第5讲】Python爬虫文本解析详解
开发语言·爬虫·python
神经蛙199613 小时前
🌍 别再硬编码中文了!Python Web 项目国际化(i18n)完全指南
后端·python
颜酱13 小时前
14 | 验证并修正 LLM 生成的 SQL
人工智能·python
颜酱14 小时前
13 | 使用 LangChain 生成 SQL
人工智能·python·langchain