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

相关推荐
hongyucai20 小时前
详解rlinf强化学习四步曲
人工智能·python·算法·架构
c_lb728820 小时前
2026年下半年AI量化工具,阶段不同重点也不同
人工智能·python
Xpower 1720 小时前
详细解释 Codex 最近一次功能更新,以及 GPT-5.6 Sol、Terra、Luna 的能力、价格、使用方式和适用场景。
人工智能·python·gpt·学习
许彰午20 小时前
87_Python Django模型与数据库
数据库·python·django
程序员小远20 小时前
性能测试之性能调优
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·性能测试
金銀銅鐵21 小时前
[Python] 借助图形化界面探索模n运算的规律
python·数学
Hesionberger21 小时前
快速求解完全平方数的最少数量
开发语言·数据结构·python·算法·leetcode·c#
xywww1681 天前
大模型 API 选型实战:GPT、Gemini、Claude 接入时该看哪些指标?
运维·服务器·人工智能·python·gpt·langchain
夜雪一千1 天前
Python enumerate() 函数完整详解:遍历同时获取索引,告别手动计数
服务器·windows·python
能有时光1 天前
PyTorch KernelAgent 源码解读 ---(4)--- ExtractorAgent
人工智能·pytorch·python