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

相关推荐
MediaTea3 分钟前
Python 库手册:wave WAV 音频读写工具
开发语言·python·音视频
写代码的【黑咖啡】3 分钟前
python的小型实践项目
开发语言·python
zyxczyf12311 分钟前
软件工程test
python
阿水实证通18 分钟前
DoubleML+FLAML实现双重机器学习超参数的自动调优(python实现路径)
人工智能·python·机器学习·实证分析
攻城狮之路人甲28 分钟前
用pycharm写的程序,点击.py无法运行闪退
ide·python·pycharm
syt_biancheng36 分钟前
大规模考试系统性能优化与风险评估
python·功能测试·selenium·性能优化·postman
热爱生活的五柒1 小时前
在有真实标签 (Ground Truth) 的情况下,常用的指标有哪些?聚类指标有哪些?
python·指标
superman超哥1 小时前
仓颉语言智能指针深度实战:突破 GC 与所有权的边界
c语言·开发语言·c++·python·仓颉
Elaine3361 小时前
【基于 Scikit-learn 本地数据集的垂直领域词云生成】
python·机器学习·nlp·scikit-learn·词云
3824278271 小时前
python:mysql数据库
数据库·python·mysql