Django HttpRequest 对象的常用属性

以下是 request 对象中你经常能用到的其他核心属性:

属性 类型 说明 示例
request.path str 请求的完整路径(含脚本前缀) /dashboard/
request.path_info str 请求路径(去除了脚本前缀) /dashboard/
request.get_full_path() str 路径 + 查询字符串 /dashboard/?page=2
request.get_raw_uri() str 完整请求 URI(含协议、host、路径等) https://example.com/dashboard/?q=test
request.method str 请求方法 'GET', 'POST', 'PUT', 'DELETE'
request.GET QueryDict GET 参数(URL 查询参数) ?name=Tom&age=20 → request.GET['name']
request.POST QueryDict POST 表单数据 提交表单时使用
request.FILES MultiValueDict 上传的文件数据 配合 enctype="multipart/form-data" 使用
request.COOKIES dict 客户端 Cookie request.COOKIES.get('sessionid')
request.session SessionStore 当前用户的 session 对象 request.session['user_id'] = 123
request.user User 或 AnonymousUser 当前登录用户(需配合 Django auth) request.user.is_authenticated
request.META dict HTTP 请求头和其他元数据 request.META['HTTP_USER_AGENT'], request.META['REMOTE_ADDR'](IP)
request.scheme str 协议类型 'http' 或 'https'
request.content_type str 请求体的 MIME 类型 'application/json'
request.content_length int or None 请求体长度 用于验证上传大小
request.body bytes 原始请求体数据(用于非表单如 JSON) json.loads(request.body)

举个例子说明这些属性的用法

复制代码
def my_view(request):
    print("路径:", request.path_info)           # /my/page/
    print("完整路径:", request.get_full_path()) # /my/page/?q=test
    print("方法:", request.method)              # GET 或 POST
    print("GET参数:", request.GET.dict())       # {'q': 'test'}
    print("用户IP:", request.META.get('REMOTE_ADDR'))
    print("User-Agent:", request.META.get('HTTP_USER_AGENT'))
    print("是否HTTPS:", request.scheme == 'https')
    print("当前用户:", request.user.username)
    print("Session中的app:", request.session.get("app"))
    
    if request.method == "POST":
        print("POST数据:", request.POST.dict())
        print("上传文件:", request.FILES.get("avatar"))

    return HttpResponse("OK")
相关推荐
龙腾AI白云13 小时前
AI检索增强生成(RAG):解决大模型幻觉的核心落地技术
数据库·人工智能·机器学习·知识图谱
一 乐14 小时前
动漫书销售商城|基于springboot + vue动漫书销售商城(源码+数据库+文档)
java·数据库·vue.js·spring boot·毕业设计
zzj_26261014 小时前
MySQL常用操作
数据库·mysql
其实防守也摸鱼14 小时前
Fastjson 反序列化漏洞(JNDI注入)
android·数据库·安全·oracle·自动化·fastjson·反序列化
haerapi14 小时前
把 PostgreSQL 复制巡检做成可审计闭环:确定性采集、阈值判定与受控模型归纳
数据库·postgresql
微学AI15 小时前
不让每一步都调用最贵模型:用蓝耘智能路由改造自主式研究 Agent
数据库·人工智能·蓝耘
yjb.gz15 小时前
Oracle19 RAC查看集群状态及磁盘空间情况(巡检)
数据库
钝挫力PROGRAMER16 小时前
开发踩坑记:MyBatis selectKey、空 SQL
数据库·sql·mybatis
JosieBook16 小时前
【数据库】MySQL 实战精通系列 · 第6篇:InnoDB 存储引擎、日志与崩溃恢复
数据库·mysql
杨云龙UP16 小时前
TDengine 3.4.2.8 Community 三节点三副本生产集群部署实战(DNode/MNode/taosAdapter/Explorer)
大数据·linux·运维·数据库·tdengine·时序库