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_96229867几秒前
正则表达式引擎 哪些
java·python·perl·pcre·正则表达式引擎
gf132111122 分钟前
【python_回复邮件】
android·java·python
天空属于哈夫克329 分钟前
企业微信API:企业微信机器人如何开发?
python·机器人·企业微信
Patrick在香港31 分钟前
把 Claude 塞进 pandas 管道:7 条脏地址实测,5 条自动清洗、2 条被闸门拦下
python·pandas·etl·claude·数据清洗
二进制漫游记32 分钟前
PostgreSQL超详细入门教程:Windows安装+Python异步连接+完整增删改查实战
python·postgresql
2601_9620776034 分钟前
从零搭建Python接口自动化测试框架:pytest+requests实战指南
python·pytest·接口自动化·requests·框架搭建
stolentime1 小时前
OpenClaw 2.0 新手快速上手与实战指南
爬虫·python·ai·网络爬虫
启观川1 小时前
Python基础-第 16 章 综合案例:客户信息管理系统
开发语言·笔记·python·正则表达式
用户3721574261351 小时前
如何使用 Python 给 PDF 添加附件:文档附件与附件注释
python
λqaq71 小时前
Redis 数据库基础:安装、5 大核心数据类型与常用命令
linux·数据库·redis·python·缓存