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")
相关推荐
JIngJaneIL9 分钟前
社区互助|社区交易|基于springboot+vue的社区互助交易系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·社区互助
晚风吹人醒.16 分钟前
缓存中间件Redis安装及功能演示、企业案例
linux·数据库·redis·ubuntu·缓存·中间件
Y***985134 分钟前
DVWA靶场通关——SQL Injection篇
数据库·sql
Yawesh_best36 分钟前
告别系统壁垒!WSL+cpolar 让跨平台开发效率翻倍
运维·服务器·数据库·笔记·web安全
蒋士峰DBA修行之路38 分钟前
实验二十八 SQL PATCH调优
数据库·sql·gaussdb
I***t7161 小时前
一条sql 在MySQL中是如何执行的
数据库·sql·mysql
一 乐1 小时前
应急知识学习|基于springboot+vue的应急知识学习系统(源码+数据库+文档)
数据库·vue.js·spring boot
微学AI2 小时前
内网穿透的应用-突破局域网束缚,MongoDB 远程访问使用cpolar原来可以这么简单
数据库·mongodb
大锦终4 小时前
【MySQL】内置函数
数据库·mysql
猿小喵4 小时前
索引优化-MySQL性能优化
数据库·mysql·性能优化