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

相关推荐
1941s17 小时前
Google Agent Development Kit (ADK) 指南 第六章:记忆与状态管理
人工智能·python·agent·adk·google agent
no_work17 小时前
万能图像处理小助手1.1_傅里叶变化_椒盐噪声_直方图均衡等图片批量处理
图像处理·人工智能·python
2401_8846621017 小时前
CSDN年度技术趋势预测文章大纲
python
叶子20242217 小时前
在压力面前保持本色
python
wefly201717 小时前
告别本地环境!m3u8live.cn一键实现 M3U8 链接预览与调试
前端·后端·python·音视频·m3u8·前端开发工具
yaoxin52112317 小时前
358. Java IO API - 使用 relativize() 创建路径之间的相对关系
java·linux·python
biubiuibiu18 小时前
探秘新飞机:从包装到起飞的全程指南
数据库·python
racerun18 小时前
跳转链接批量解析工具 python
开发语言·python
q_354888515318 小时前
计算机毕业设计:Python当当网图书大数据分析平台 Django框架 爬虫 Pandas 可视化 大数据 大模型 书籍(建议收藏)✅
大数据·爬虫·python·机器学习·数据分析·django·课程设计
知智前沿18 小时前
什么是 RAG?通俗易懂讲解 + 核心流程梳理
人工智能·python