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

相关推荐
weixin_贾41 分钟前
最新AI-Python机器学习与深度学习技术在植被参数反演中的核心技术应用
python·机器学习·植被参数·遥感反演
张槊哲1 小时前
函数的定义与使用(python)
开发语言·python
船长@Quant1 小时前
文档构建:Sphinx全面使用指南 — 实战篇
python·markdown·sphinx·文档构建
偶尔微微一笑2 小时前
AI网络渗透kali应用(gptshell)
linux·人工智能·python·自然语言处理·编辑器
船长@Quant3 小时前
文档构建:Sphinx全面使用指南 — 基础篇
python·markdown·sphinx·文档构建
喵手3 小时前
从 Java 到 Kotlin:在现有项目中迁移的最佳实践!
java·python·kotlin
liuweidong08023 小时前
【Pandas】pandas DataFrame rsub
开发语言·python·pandas
CH3_CH2_CHO4 小时前
不吃【Numpy】版
开发语言·python·numpy
__淡墨青衫__4 小时前
Django之旅:第七节--模版继承
数据库·django·sqlite
-曾牛4 小时前
企业级AI开发利器:Spring AI框架深度解析与实战
java·人工智能·python·spring·ai·rag·大模型应用