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=20request.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 UserAnonymousUser 当前登录用户(需配合 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")
相关推荐
员大头硬花生3 小时前
七、InnoDB引擎-架构-后台线程
java·数据库·mysql
Ryan ZX3 小时前
etcd 高可用分布式键值存储
数据库·分布式·etcd
研究司马懿3 小时前
【ETCD】ETCD——confd配置管理
数据库·golang·自动化·运维开发·etcd·argocd·gitops
..Cherry..3 小时前
Etcd详解(raft算法保证强一致性)
数据库·算法·etcd
Tadas-Gao3 小时前
MySQL存储架构解析:从数据无序到索引艺术的演进
数据库·分布式·mysql·微服务·云原生·架构
懒羊羊不懒@4 小时前
【MySQL | 基础】通用语法及SQL分类
数据库·oracle
llxxyy卢5 小时前
基于时间的 SQL 盲注-延时判断和基于布尔的 SQL 盲注
数据库·sql·oracle
Yeats_Liao6 小时前
时序数据库系列(六):物联网监控系统实战
数据库·后端·物联网·时序数据库
珊珊而川6 小时前
MAC-SQL:黄金标准错误
数据库·sql
一 乐7 小时前
智慧党建|党务学习|基于SprinBoot+vue的智慧党建学习平台(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·学习