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

相关推荐
sukioe6 小时前
一张图、两把锁:AI 物流履约平台的确定性边界设计
人工智能·python·ai·langchain
2601_962203516 小时前
【SpringBoot3】面向切面 AspectJ AOP 使用详解
开发语言·前端·python
程序员大雄学编程6 小时前
微积分43. 无穷积分入门:从概念到Python实战可视化
开发语言·python·学习·微积分
测试老哥7 小时前
Postman获取token并设置token依赖步骤
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
郝学胜-神的一滴7 小时前
C++11 工程级应用 06:自己造一个类似Python的Range迭代器
开发语言·c++·windows·python·程序人生·microsoft
满怀冰雪7 小时前
23-PaddleClas 数据集、配置文件与训练参数详解
人工智能·python·深度学习·paddlepaddle
笔触狂放7 小时前
第3章 抓取静态网页数据
爬虫·python
海兰7 小时前
【 Python 量化交易】开篇
开发语言·python·信息可视化·量化交易
pt10438 小时前
网络自动化Python课程:Netconf与Restconf及Cisco自动化配置实验
网络·python·自动化
slacker-kian8 小时前
[笔记]-什么是相似性搜索?
python·ai·向量·相似性搜索·点积·l2 距离·余弦相似度和距离