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

相关推荐
高洁017 小时前
多源数据融合:把零散信号拼成一致图景
人工智能·python·机器学习·transformer·迁移学习
郝学胜-神的一滴8 小时前
Effective Python 条款41:试Mix‑In组合式开发
开发语言·pytorch·python·pycharm·numpy
吃我一窝jio8 小时前
Python与Redis集合深度解析
开发语言·redis·笔记·python
龙腾AI白云10 小时前
多源数据融合:把零散信号拼成一致图景
大数据·人工智能·python·机器学习·知识图谱
艾派森10 小时前
深度学习实战-基于VGG19的健康和白化珊瑚图像分类识别模型
人工智能·python·深度学习·分类
鲸渔10 小时前
【AI Agent系列课程26-Python 基础26】复盘:Python 接口开发知识清单
开发语言·python·ai编程
2401_8685347811 小时前
55 个热门网络面试问题及答案
网络·python
aifannihao11 小时前
ON CONFLICT 冲突后返回空:sqlite3 实测 get-or-create
数据库·python·postgresql·sqlite3·标准库
用户03321266636711 小时前
使用 Python 合并 Excel 工作簿
python
__underline__11 小时前
冷门Python知识点008篇:__int__、__index__与__float__,Python数值转换的真实回退顺序?
后端·python