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 小时前
深入Python内存管理与垃圾回收:从引用计数到分代回收的实战解析
python·性能优化·内存管理·垃圾回收·引用计数
m0_547486661 小时前
《Python数据分析与挖掘》全套PPT课件
python·数据挖掘·数据分析
㱘郳1 小时前
飞机大战Pygame存档
python·pygame
阿童木写作2 小时前
跨马翻译:一站式图片视频智能处理,提升跨境电商工作效率
人工智能·python·音视频
Python图像识别-12 小时前
基于yolov8的钢铁缺陷检测系统-2027毕业版(UI界面+Python项目源码+模型+标注好的数据集)
开发语言·python·yolo
aqi002 小时前
15天学会AI应用开发(十五)使用LangChain封装AI执行链
人工智能·python·大模型·ai编程·ai应用
kisbad3 小时前
Day 012|Embedding 和向量数据库:知识库检索到底在检什么
数据库·python·embedding·agent
va学弟3 小时前
LeetCode 热题 100 题解(1):哈希
python·算法·leetcode·哈希算法
言乐63 小时前
Python实现基本搜索引擎
java·linux·开发语言·python·搜索引擎