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

相关推荐
果汁华8 小时前
CLI 命令行与 Python 框架实战
git·python·github
Maiko Star8 小时前
FastAPI 进阶三部曲:中间件、依赖注入与 ORM 实战
python·中间件·fastapi
MrDJun8 小时前
长期稳定跑网页监控:TLS 指纹、代理选路与请求节流的工程实践
运维·爬虫·python·网络协议·网站监控
m沐沐8 小时前
【计算机视觉】OpenCV 物体跟踪——原理、算法与CSRT跟踪器实战
人工智能·python·深度学习·opencv·算法·计算机视觉·人脸识别
大数据魔法师9 小时前
AI Agent - OpenAI从零开始完整学习教程(零基础入门+实战落地)
python
卷无止境9 小时前
Python的魔术方法:那些藏在双下划线背后的魔法
后端·python
米码收割机9 小时前
【Python】Django恒达科技门户网站(源码+文档)【独一无二】
数据库·python·科技
卷无止境9 小时前
别再被"乱码"吓到了:Python文件操作的门道
后端·python
STLearner10 小时前
ICML 2026 | LLM×Graph论文总结[2]【Graph4LLM,Graph4Agent,智能体记忆(Memory)
大数据·人工智能·python·深度学习·学习·机器学习·数据挖掘
郭老二19 小时前
【Python】基本语法:装饰器语法糖@
python