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

相关推荐
外收内放6 分钟前
数据分析(数据读取与写入)
python·学习·数据分析
zh路西法16 分钟前
【离策略强化学习】DDPG、TD3 与 SAC:核心公式推导与源码解析
python·强化学习·ddpg·td3·sb3·off-policy·sac
秋秋小事18 分钟前
python 数据契约层FastAPI+Pydantic(一)
python
AIFQuant18 分钟前
Python港股实时行情API接入:恒生股票数据获取与AH股溢价监控实战
开发语言·数据库·python·金融·实时数据api
朝阳资本论25 分钟前
小马智行杀入伦敦牵手Uber,中国Robotaxi出海怎么打?
python
外收内放28 分钟前
Python基础语法练习题(70)
开发语言·python
老唐77729 分钟前
Agent 开发入门教程:从零搭建一个 Python AI Agent
人工智能·python·深度学习·langchain·大模型·agent·智能体
宿州派大星3 小时前
Python实战:PyQt5 + OpenCV + Dlib 打造AI桌面应用
人工智能·python·qt
承渊政道4 小时前
【从零开始大模型开发与微调:基于PyTorch与ChatGLM】(开源大模型ChatGLM高级定制化应用实战)
人工智能·pytorch·python·llm·模型微调·glm
Smoothcloud润云11 小时前
PyTorch大模型权重加载与启动耗时优化实战:定位磁盘、内存与显存瓶颈
人工智能·pytorch·python·深度学习·gpu算力