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")
相关推荐
ss27314 分钟前
AI时代首先数据库-PostgreSQL实战笔记 | 19 PostgreSQL逻辑备份:pg_dump与pg_dumpall
数据库·笔记·postgresql
啵啵啵鱼17 分钟前
九、JDBC 操作 MySQL 数据库
android·数据库·mysql
handonch17 分钟前
MySQL → Kingbase PG模式 高频SQL替换清单
数据库·mysql·postgresql
姜鱼问生20 分钟前
Kuma SQLite 备份坑
数据库·sqlite
水无痕simon24 分钟前
15 MySQL是怎么保证高可用的?
数据库·mysql
漫步人生走在路上29 分钟前
外贸SEO中的品牌词与产品词策略:大卖家和小卖家的不同打法
大数据·javascript·网络·数据库·人工智能·搜索引擎
张小姐的猫29 分钟前
【MySQL】数据类型
android·linux·数据库·c++·mysql·adb·php
泡海椒32 分钟前
JQuick-SQL LIMIT 分页:限制行数与偏移查询
数据库·sql
catino1 小时前
SQL调优
数据库·sql
猫咪很可爱1 小时前
Oracle Data Pump 导入报错 ORA-02375:字符集不一致问题分析与处理
数据库·oracle