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

相关推荐
2601_967980112 小时前
Python闭包(Closure)详解
python·作用域·装饰器·函数式编程·闭包
AI创界者2 小时前
ComfyUI 进阶实战:MiniMax-H3 视频人物脸部替换工作流全解析(对比 Face 5.5 实测与避坑指南)
人工智能·python·aigc
承渊政道3 小时前
【Python编程快速上手—让繁琐工作自动化】(模式匹配与正则表达式:从找到一个号码到批量提取信息)
python·正则表达式·pycharm·自动化·模式匹配
JonaHu3 小时前
AceDataCloud Coding Plan 多模型编程:从 Chat Completions 迁移到 Responses API 与工具调用
python·大模型·api·ai编程·acedatacloud
鲸渔3 小时前
【AI Agent系列课程23-Python 基础23】测试入门:为函数写第一个 pytest 用例
开发语言·python·pytest·ai编程
fengkai45454 小时前
Python运维实战
运维·开发语言·python·ssh·sftp·paramiko
用户45428451062814 小时前
一张 3000×2000 的 PSD 为什么 86MB:从体积构成到上传墙
python
用户298698530145 小时前
使用 Python 提取 Word 文档中的文本与图片
后端·python·api
用户0332126663676 小时前
使用 Python 在 PDF 中创建表单域
python
羲云网络15 小时前
GPT Image 2.6 海报改横竖版:文字安全区、排版分离与交付验收
图像处理·人工智能·python·aigc