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

相关推荐
小徐学编程-zZ3 小时前
量产测试数据
python·压力测试·数据库架构
QQ8057806513 小时前
django基于机器学习的电商评论情感分析系统设计实现
python·机器学习·django
wx09093 小时前
stata实现机器学习的环境配置
python·机器学习·stata
nuowenyadelunwen5 小时前
CS 61A Lab 2 笔记:短路求值、高阶函数与 Lambda 表达式
python·函数式编程·cs61a·berkeley
qq_422828626 小时前
android图形学之SurfaceControl和Surface的关系 五
android·开发语言·python
weixin_444012936 小时前
c++如何将std--vector直接DUMP到二进制文件_指针地址直写【附代码】
jvm·数据库·python
woxihuan1234566 小时前
Go语言中--=运算符详解:位右移赋值操作的原理与应用
jvm·数据库·python
石山代码7 小时前
Python 数据分析三大库:NumPy + Pandas + Matplotlib
python·数据分析·numpy
如竟没有火炬7 小时前
用队列实现栈
开发语言·数据结构·python·算法·leetcode·深度优先
yivifu7 小时前
CustomTkinter的布局管理器介绍及应用
python·gui·customtkinter·pdf去水印