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

相关推荐
用户83562907805119 分钟前
Python 操作 Word 文档节与页面设置
后端·python
西西弗Sisyphus23 分钟前
Python 闭包的经典坑
python·闭包
西西弗Sisyphus27 分钟前
Python 在dataclasses 里,field() 能给可变、不可变数据分别设置安全的默认值
python·field·dataclasses
西西弗Sisyphus44 分钟前
Python @dataclass 有 `__post_init__` 和 无 `__post_init__` 的对比
python·dataclass·__post_init__
独隅1 小时前
PyCharm 开启硬换行的方法
ide·python·pycharm
weixin_408099671 小时前
python请求文字识别ocr api
开发语言·人工智能·后端·python·ocr·api·ocr文字识别
我会好好吃饭歌1 小时前
医疗单据隐私脱敏开源项目:OCR + Vision LLM + 四点定位打码,适配弯曲、旋转、复杂拍摄场景
图像处理·python·开源项目·paddleocr·医疗ai·隐私脱敏
惊鸿若梦一书生1 小时前
《Python 高阶教程》003|变量背后不是盒子:名字、对象与引用的本质
java·jvm·python
qq_380619161 小时前
SQL中如何实现特定范围内数据的批量删除_范围分区与分区删除
jvm·数据库·python
Hommy882 小时前
【开源剪映小助手】云渲染环境搭建
python·开源·github·剪映小助手