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

相关推荐
爱昏羔13 小时前
上篇:从PDF到向量库 — 物流行业RAG系统的知识库构建全解析
python·langchain·pdf·agent·rag
麻雀飞吧13 小时前
最新量化实现难点,规则和流程要先有形状
人工智能·python
用户03321266636713 小时前
使用 Python 在 Word 文档中添加或删除文本框
python
LadenKiller14 小时前
近期AI量化辅助,工具重点要跟学习阶段变化
人工智能·python
phltxy14 小时前
LangChain_Agent中间件实战
人工智能·python·深度学习·语言模型·中间件·langchain
axinawang14 小时前
第14课:查找、统计、分割字符串
python
倒流时光三十年15 小时前
第一阶段 02 · Mapping 与数据类型(text vs keyword 是重点)
后端·python·django
小大宇15 小时前
python蓝图、拦截器、异常处理、redis队列、线程池、控制台及日志文件输出
python
喝茶与编码15 小时前
真实业务场景:高并发 Upsert 死锁频发?InnoDB 锁机制与重试机制深度解析
数据库·python
倒流时光三十年15 小时前
第一阶段 05 · Java 客户端查询类详解(Query / SearchCriteria / Response 与复杂拼接)
java·开发语言·python