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

相关推荐
玫幽倩6 小时前
2026第二届湾区杯网络安全大赛决赛(AI专项赛道静态题wp)
pytorch·python·ai·agent·ctf·rag·湾区杯
TechWayfarer6 小时前
IP地址查询之后:如何在请求抵达前识别风险
python·tcp/ip·网络安全
专注于ai算法的踩坑小达人6 小时前
TabFM(Google Tabular Foundation Model)完整部署手册(PyTorch GPU版)
人工智能·python
特创数字科技7 小时前
公文Word一键批量排版工具|批量统一公文标准格式,办公自动化桌面小工具
前端·python
维克兜率天7 小时前
5.3 宏观因子:抬头看天
笔记·python·深度学习·算法·量化
XZ-0700017 小时前
week4-2-坐标轴
python
Delta-delta7 小时前
Ubuntu MATE 24.04 + systemd 部署 LiteLLM + Open WebUI
python
金融大 k7 小时前
A股实时行情 API 接入指南:Python 覆盖行情、复权、基本面与 WebSocket
python·websocket·行情数据·行情 api
生信大杂烩7 小时前
Xenium H&E空间原位可视化——细胞轮廓、基因表达与转录本可视化
python·算法·数据分析
东莞市云毅网络有限公司7 小时前
用标准库做网页正文抽取:从 HTML 到结构化字段的轻量实现
python·sqlite·自动化运维·geo·数据监测