django之HttpRequest对象
- class
HttpRequest
[source]
属性
所有的属性都是只读的,除非另有说明
HttpRequest.
scheme
-
字符串(http/https)表示http还是https请求
HttpRequest.
body
-
原始的http请求正文
也可以像文件一样读他,看
HttpRequest.read()
.
HttpRequest.
path
-
完整的请求路径,不包括域
例:
"/music/bands/the_beatles/"
HttpRequest.
path_info
-
在某些情况下,路径被分割成脚本前缀和路径,这样可以使部署和测试更方便
例如脚本前缀为"/minfo"
, 路径为"/minfo/music/bands/the_beatles/"
path_info为"/music/bands/the_beatles/"
HttpRequest.
method
-
字符串(GET/POST)表示GET还是POST请求
if request.method == 'GET':
do_something()
elif request.method == 'POST':
do_something_else()常用方法
HttpRequest.
encoding
-
一个字符串,用于解码的当前编码的表单提交的数据(或没有,就使用thedefault_charset)。在访问表单数据时,可以使用此属性来更改所用的编码。如果你知道表格数据不是default_charset编码。随后的任何属性的访问(如阅读从GET或POST)将使用新的encodingvalue。
HttpRequest.
GET
-
GET请求对象,详细查看
QueryDict
HttpRequest.
POST
-
POST请求对象,详细查看
QueryDict
注意:
POST不包含文件上传
,请看FILES
.
HttpRequest.
COOKIES
-
客户端cookies信息,字典类型
HttpRequest.
FILES
-
一个包含所有文件对象的字典. key是
<inputtype="file" name="" />中name的值,没一个value是一个上传的文件对象,请查看
UploadedFile
.参看 Managing files 获取更多信息
如果要上传文件需要在
<form>
标签中添加enctype="multipart/form-data",不然收到的是一个空值
HttpRequest.
META
-
请求头信息
例:
CONTENT_LENGTH
请求体当作一个字符串的总长度。CONTENT_TYPE
请求体的MIME类型。HTTP_ACCEPT 可以接受的内容类型的响应。
HTTP_ACCEPT_ENCODING
接受编码的响应。HTTP_ACCEPT_LANGUAGE
接受语言的反应。HTTP_HOST 客户端请求时用的服务端地址
HTTP_REFERER 参考页面
HTTP_USER_AGENT
客户端的标志信息QUERY_STRING
一对一的查询字符串REMOTE_ADDR
客户端IPREMOTE_HOST
客户端主机名REMOTE_USER
客服端的身份信息REQUEST_METHOD
请求方式SERVER_NAME
服务器主机名SERVER_PORT 服务端开放的端口
HttpRequest.
resolver_match
-
An instance of
ResolverMatch
representing the resolved url. This attribute is only set after url resolving took place, which means it’s available in all views but not in middleware methods which are executed before url resolving takes place (likeprocess_request
, you can useprocess_view
instead).
应用代码设置的属性
Django本身不设置这些属性,可以被服务端设置的属性
HttpRequest.
current_app
-
Django 1.8后新属性
The
url
template tag will use its value as thecurrent_app
argument toreverse()
.
HttpRequest.
urlconf
-
This will be used as the root URLconf for the current request, overriding the
ROOT_URLCONF
setting. See How Django processes a request for details.urlconf
can be set toNone
to revert any changes made by previous middleware and return to using theROOT_URLCONF
.Changed in Django 1.9:Setting
urlconf=None
raisedImproperlyConfigured
in older versions.
被中间件设置的属性
Django项目中要求包含这些中间件,如果请求中看不到这些属性, 查看下这些中间件列表 MIDDLEWARE_CLASSES
.
HttpRequest.
session
-
来自
SessionMiddleware中间件
:一个可读写类似字典对象的当前会话
HttpRequest.
site
-
来自
CurrentSiteMiddleware中间件
: An instance ofSite
orRequestSite
as returned byget_current_site()
representing the current site.
HttpRequest.
user
-
来是
AuthenticationMiddleware中间件
: An instance ofAUTH_USER_MODEL
representing the currently logged-in user. If the user isn’t currently logged in,user
will be set to an instance ofAnonymousUser
. You can tell them apart withis_authenticated()
, like so:if request.user.is_authenticated():
... # Do something for logged-in users.
else:
... # Do something for anonymous users.
方法
HttpRequest.
get_host
()[source]-
返回从HTTP_X_FORWARDED_HOST
(ifUSE_X_FORWARDED_HOST
is enabled)和HTTP_HOST
headers获取的主机名和端口信息像PEP 3333的格式例:
"127.0.0.1:8000"
注意:
get_host()
获取失败,说明后面有很多代理. 一个解决方案是使用中间件来重写代理头文件,如下面的例子:class MultipleProxyMiddleware(object):
FORWARDED_FOR_FIELDS = [
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED_HOST',
'HTTP_X_FORWARDED_SERVER',
] def process_request(self, request):
"""
Rewrites the proxy headers so that only the most
recent proxy is used.
"""
for field in self.FORWARDED_FOR_FIELDS:
if field in request.META:
if ',' in request.META[field]:
parts = request.META[field].split(',')
request.META[field] = parts[-1].strip()该中间就被其他中间件需要get_host()获取值的中间就依赖
– 例如,CommonMiddleware
orCsrfViewMiddleware
.
HttpRequest.
get_port
()[source]-
Django 1.9新的
返回包含HTTP_X_FORWARDED_PORT
(ifUSE_X_FORWARDED_PORT
is enabled) 和SERVER_PORT
META
的值
HttpRequest.
get_full_path
()[source]-
返回包含路径和查询字符串的路径
例:
"/music/bands/the_beatles/?print=true"
HttpRequest.
build_absolute_uri
(location)[source]-
返回一个绝对的url地址
例如:
"https://example.com/music/bands/the_beatles/?print=true"
注意:
如果混合了http和https是获取不准确的,除非全部重定向到https
HttpRequest.
get_signed_cookie
(key, default=RAISE_ERROR, salt='', max_age=None)[source]¶-
Returns a cookie value for a signed cookie, or raises a
django.core.signing.BadSignature
exception if the signature is no longer valid. If you provide thedefault
argument the exception will be suppressed and that default value will be returned instead.The optional
salt
argument can be used to provide extra protection against brute force attacks on your secret key. If supplied, themax_age
argument will be checked against the signed timestamp attached to the cookie value to ensure the cookie is not older thanmax_age
seconds.For example:
>>> request.get_signed_cookie('name')
'Tony'
>>> request.get_signed_cookie('name', salt='name-salt')
'Tony' # assuming cookie was set using the same salt
>>> request.get_signed_cookie('non-existing-cookie')
...
KeyError: 'non-existing-cookie'
>>> request.get_signed_cookie('non-existing-cookie', False)
False
>>> request.get_signed_cookie('cookie-that-was-tampered-with')
...
BadSignature: ...
>>> request.get_signed_cookie('name', max_age=60)
...
SignatureExpired: Signature age 1677.3839159 > 60 seconds
>>> request.get_signed_cookie('name', False, max_age=60)
FalseSee cryptographic signing for more information.
HttpRequest.
is_secure
()[source]-
返回是否是https请求
HttpRequest.
is_ajax
()[source]-
返回是否是异步请求
HttpRequest.
read
(size=None)[source]
HttpRequest.
readline
()[source]
HttpRequest.
readlines
()[source]
HttpRequest.
xreadlines
()[source]
HttpRequest.
__iter__
()-
再处理XML是,如果数据量过大,使用可迭代的传入请求数据,而不是完整的读取
使用这个标准的接口, 把数据传入ElementTree:
import xml.etree.ElementTree as ET
for element in ET.iterparse(request):
process(element)
最新文章
- C# 破解 Reflector8.5
- 《Learning Highcharts》中文翻译
- [poj2349]Arctic Network(最小生成树+贪心)
- Objective-C的 KVC和KVO
- [Ljava.lang.String和java.lang.String区别
- fflua更新-增加对引用的支持
- iOS录音加播放.
- Android LayoutParams
- P2P直播、点播技术学习经验
- jquery 数组和字典
- Javascript 优化
- Zen Coding in Visual Studio 2012
- 在CentOS上安装第三方软件库EPEL
- hdu2410(水)
- 服务器 隐藏php版本,nginx版本号等
- Django admin修改密码
- Spark SQL / Catalyst 内部原理 与 RBO
- Head First Servlets &; JSP 学习笔记 第四章 —— 作为Servlet
- 阿里云服务器(windows)配置项目域名
- comet4j推送 405/500 JSON转换异常
热门文章
- [Effective Modern C++] Item 4. Know how to view deduced types - 知道如何看待推断出的类型
- javascript中base64和Gzip的使用
- iOS Dev (21) 用 AVPlayer 播放一个本地音频文件
- fzu 1753 Another Easy Problem
- 进程外Session和进程内Session存储
- GO的GDB调试
- 组队练习赛(Regionals 2012, North America - East Central NA)
- Python网络资源 + Python Manual
- linux命令之mount
- PHP - Mysql数据库备份类