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

相关推荐
whcyhhh5 分钟前
头歌实践教学平台:数据科学与大数据技术导论(七上)
大数据·数据库·python
ServBay1 小时前
AI 工程师必备的 9 个 Python 库,从数据验证到模型优化
后端·python·ai编程
AC赳赳老秦2 小时前
企业级合规审计体系:用 OpenClaw 落地采集全链路留痕,自动生成合规审计报告
java·python·django·beautifulsoup·php·deepseek·openclaw
IPdodo_2 小时前
代理 IP 服务商 SLA 怎么验?7 项指标与 Python 探测脚本实战
运维·python·网络协议·网络安全·代理ip
微软技术分享2 小时前
使用Masscan扫描器进行信息搜集
python·masscan·信息搜集
青 春 记 忆2 小时前
零基础入门python23:Flask-Login登录、退出与会话
python·flask·后端开发
微小冷2 小时前
Python图论库NetworkX初步
开发语言·python·图论·graph·networkx·digraph
Data_Journal3 小时前
如何使用 Python 抓取 Google Flights:分步指南
大数据·开发语言·数据库·python·scrapy
你我一见如故3 小时前
仿QQ音乐桌面客户端——测试报告
python·selenium
Kismet_nvi4 小时前
Python 基础核心知识点总结
开发语言·windows·python