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

相关推荐
Nautiluss2 分钟前
一起玩XVF3800麦克风阵列(十)
linux·人工智能·python·音频·语音识别·实时音视频·dsp开发
BoBoZz195 分钟前
MultiBlockDataSet 复合感知与非复合感知
python·vtk·图形渲染·图形处理
兔子小灰灰1 小时前
jetson安装pytorch
人工智能·pytorch·python
Swizard2 小时前
拒绝“裸奔”上线:FastAPI + Pytest 自动化测试实战指南
python
Ven%3 小时前
从单轮问答到连贯对话:RAG多轮对话技术详解
人工智能·python·深度学习·神经网络·算法
谈笑也风生3 小时前
经典算法题型之复数乘法(二)
开发语言·python·算法
先知后行。3 小时前
python的类
开发语言·python
dyxal4 小时前
Python包导入终极指南:子文件如何成功调用父目录模块
开发语言·python
nnerddboy4 小时前
解决传统特征波段选择的不可解释性:2. SHAP和LIME
python·机器学习
电商API&Tina4 小时前
【电商API接口】关于电商数据采集相关行业
java·python·oracle·django·sqlite·json·php