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

相关推荐
甄心爱学习13 小时前
【leetcode】判断平衡二叉树
python·算法·leetcode
深蓝电商API13 小时前
滑块验证码破解思路与常见绕过方法
爬虫·python
Ulyanov13 小时前
Pymunk物理引擎深度解析:从入门到实战的2D物理模拟全攻略
python·游戏开发·pygame·物理引擎·pymunk
sensen_kiss13 小时前
INT303 Coursework1 爬取影视网站数据(如何爬虫网站数据)
爬虫·python·学习
玄同76513 小时前
我的 Trae Skill 实践|使用 UV 工具一键搭建 Python 项目开发环境
开发语言·人工智能·python·langchain·uv·trae·vibe coding
Yorlen_Zhang13 小时前
Python Tkinter Text 控件完全指南:从基础编辑器到富文本应用
开发语言·python·c#
HAPPY酷14 小时前
C++ 和 Python 的“容器”对决:从万金油到核武器
开发语言·c++·python
gpfyyds66615 小时前
Python代码练习
开发语言·python
aiguangyuan16 小时前
使用LSTM进行情感分类:原理与实现剖析
人工智能·python·nlp
小小张说故事16 小时前
BeautifulSoup:Python网页解析的优雅利器
后端·爬虫·python