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

相关推荐
北斗落凡尘9 小时前
LangGraph 入门实战(10)--时光回溯
python·langchain
今天AI了吗9 小时前
Agent & AI 名词大扫盲
数据库·人工智能·python·sql·rust
张张123y9 小时前
Hermes Agent 是什么?它能做什么,以及如何部署到飞书
人工智能·python·飞书
SamChan909 小时前
用Playwright端到端测试PDF翻译功能:Web自动化测试实战
前端·python·ai·pdf·wpf
袁袁袁袁满10 小时前
Python爬虫实战:利用巨量IP获取跨境电商数据
爬虫·python·网络爬虫·爬虫实战·跨境电商·电商爬虫
jufeng130710 小时前
【系列:TDengine 工业物联网实战:从零搭起可运行系统 · 第 4 篇】
python·时序数据库·tdengine·asyncio
努力搬砖的咸鱼10 小时前
意图理解:让Agent从需求描述自动生成Pytest测试策略
人工智能·python·ai·单元测试·pytest·agent
2601_9563198810 小时前
2026年下半年,量化学习要把交易认知和技术实现接起来
人工智能·python
EW Frontier10 小时前
【雷达信号处理】5 个阵元追平 16 个阵元:稀疏阵列 STAP 的实测报告【附python+matlab代码】
python·matlab·信号处理·雷达·mimo·稀疏阵列·stap
卷无止境10 小时前
FastAPI的测试事件在测什么?
后端·python·fastapi