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 分钟前
深入理解 Flask 实现原理
后端·python·flask
FriendshipT17 分钟前
Ultralytics:解读SPPF模块
人工智能·pytorch·python·深度学习·目标检测
AOwhisky36 分钟前
Python 基础语法(上篇 + 下篇)——综合自测题
linux·windows·python
埃博拉酱1 小时前
Pip/Conda 混用导致的 CRT 版本冲突问题:[WinError 1114] 动态链接库(DLL)初始化例程失败
windows·python
刘小八1 小时前
LangGraph 人机交互实战:Interrupt、人工审批与工作流恢复
人工智能·python·人机交互
YMWM_1 小时前
python-venv虚拟环境
linux·开发语言·python
Tbisnic2 小时前
23.大模型开发:深度学习----CNN 卷积神经网络 与 RNN 循环神经网络
人工智能·python·rnn·深度学习·cnn·ai大模型
CoderYanger2 小时前
视频切割脚本(Python版)
linux·开发语言·windows·后端·python·程序人生·职场和发展
迷途呀2 小时前
新闻头条后端:新闻缓存模块
前端·redis·python·缓存·fastapi
想会飞的蒲公英2 小时前
逻辑回归为什么叫回归,却用来做分类
人工智能·python·分类·回归·逻辑回归