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

相关推荐
金融小师妹5 小时前
多因子智能推演:油价回落6%与黄金震荡上行的关联解析——AI预测框架
大数据·python·深度学习
BUG研究员_8 小时前
Runnable与LCEL
开发语言·人工智能·python
老马聊技术8 小时前
Pytorch深度学习环境配置与测试
人工智能·pytorch·python
Python私教9 小时前
AI Agent 上生产要不要开写权限?我把执行链拆成 4 道闸门
人工智能·后端·python
天才测试猿9 小时前
软件测试知识总结(基础篇)
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
崔子末9 小时前
某影视库剧集列表以及查询接口逆向
爬虫·python
gogogo出发喽9 小时前
v3 admin
python
问商十三载10 小时前
RAG 检索效果差怎么排查?2026 五层诊断法完整指南
开发语言·人工智能·windows·python·算法
weixin_BYSJ198711 小时前
springboot酒店管理系统--附源码27436
java·spring boot·python·随机森林·贪心算法·eclipse·django