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

相关推荐
Java后端的Ai之路13 小时前
07React_Props验证器
人工智能·python·react.js·架构·fastapi
Eider199813 小时前
为Loop Engineering装刹车
python·vibe coding·agent设计模式·loopengineering
kaixin_啊啊14 小时前
【零基础学AI】第 9 章——安装 Python 和开发工具
人工智能·python
雨滴AI自动化测试14 小时前
想让你的自动化测试接入AI,这一步必须要有。
python
用户76241175670514 小时前
第八章 异常处理及程序调试
python
源图客14 小时前
Python环境安装与PyCharm的第一个项目
开发语言·python·pycharm
朝朝辞暮i14 小时前
VLA 系统学习第 20 课——Diffusion Policy 为什么要先给动作加噪,再学习把噪声去掉?
人工智能·python·深度学习·transformer·vla
郝学胜_神的一滴14 小时前
Numpy数据处理详解 02:玩转高性能数组,告别低效循环
人工智能·python
全栈弄潮儿15 小时前
Python实战第3期:输入输出与字符串操作
python·agent
goehou15 小时前
MCP 传输方式实战:stdio、Streamable HTTP、WebSocket 该选哪个
python·llm·agent·教程·mcp