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
ResolverMatchrepresenting 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_viewinstead).
应用代码设置的属性
Django本身不设置这些属性,可以被服务端设置的属性
HttpRequest.current_app-
Django 1.8后新属性
The
urltemplate tag will use its value as thecurrent_appargument toreverse().
HttpRequest.urlconf-
This will be used as the root URLconf for the current request, overriding the
ROOT_URLCONFsetting. See How Django processes a request for details.urlconfcan be set toNoneto revert any changes made by previous middleware and return to using theROOT_URLCONF.Changed in Django 1.9:Setting
urlconf=NoneraisedImproperlyConfiguredin older versions.
被中间件设置的属性
Django项目中要求包含这些中间件,如果请求中看不到这些属性, 查看下这些中间件列表 MIDDLEWARE_CLASSES.
HttpRequest.session-
来自
SessionMiddleware中间件:一个可读写类似字典对象的当前会话
HttpRequest.site-
来自
CurrentSiteMiddleware中间件: An instance ofSiteorRequestSiteas returned byget_current_site()representing the current site.
HttpRequest.user-
来是
AuthenticationMiddleware中间件: An instance ofAUTH_USER_MODELrepresenting the currently logged-in user. If the user isn’t currently logged in,userwill 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_HOSTis enabled)和HTTP_HOSTheaders获取的主机名和端口信息像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()获取值的中间就依赖– 例如,CommonMiddlewareorCsrfViewMiddleware.
HttpRequest.get_port()[source]-
Django 1.9新的
返回包含HTTP_X_FORWARDED_PORT(ifUSE_X_FORWARDED_PORTis enabled) 和SERVER_PORTMETA的值
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.BadSignatureexception if the signature is no longer valid. If you provide thedefaultargument the exception will be suppressed and that default value will be returned instead.The optional
saltargument can be used to provide extra protection against brute force attacks on your secret key. If supplied, themax_ageargument will be checked against the signed timestamp attached to the cookie value to ensure the cookie is not older thanmax_ageseconds.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)
django之HttpRequest对象的更多相关文章
- [R]django的HTTPREQUEST对象
django的HTTPREQUEST对象 via Django使用request和response对象 当请求一张页面时,Django把请求的metadata数据包装成一个HttpRequest对象, ...
- django的HTTPREQUEST对象
Django使用request和response对象 当请求一张页面时,Django把请求的metadata数据包装成一个HttpRequest对象,然后Django加载合适的view方法,把这个Ht ...
- Django的httprequest对象和httpresponse对象
请求一张页面时,Django把请求的metadata数据包装成一个HttpRequest对象,然后Django加载合适的view方法,把这个HttpRequest 对象作为第一个参数传给view方法. ...
- $Django 虚拟环境,2.0、1.0路由层区别,Httprequest对象,视图层(fbv,cbv),文件上传
1 虚拟环境:解决问题同一台机器上可以运行不同版本的django, 1 用pychanrm创建--->files-->newproject--->选择虚拟环境 2 setting ...
- django HttpRequest对象
概述: 服务器接收http请求后,会根据报文创建HttpRequest对象 视图的第一个参数就是HttpRequest对象 django创建的,之后调用视图时传递给视图 属性 path:请求的完整路径 ...
- Django 10 GET和POST(HttpRequest对象,GET和POST请求,文件上传,HttpResponse对象的cookie)
Django 10 GET和POST(HttpRequest对象,GET和POST请求,文件上传,HttpResponse对象的cookie) 一.HttpRequest对象 #HttpRequest ...
- Django框架之第四篇(视图层)--HttpRequest对象、HttpResponse对象、JsonResponse、CBV和FBV、文件上传
视图层 一.视图函数 一个视图函数,简称视图,是一个简单的python函数,它接收web请求并且会返回web响应.响应可以是一张网页的html,一个重定向,或者是一张图片...任何东西都可以.无论是什 ...
- django.http.request中HttpRequest对象的一些属性与方法
HttpRequest对象的属性 属性 描述 path 表示提交请求页面完整地址的字符串,不包括域名,如 "/music/bands/the_beatles/". method 表 ...
- Django框架(九):视图(二) HttpRequest对象、HttpResponse对象
1. HttpRequest对象 服务器接收到http协议的请求后,会根据报文创建HttpRequest对象,这个对象不需要我们创建,直接使用服务器构造好的对象就可以.视图的第一个参数必须是HttpR ...
随机推荐
- printf--动态指定输出格式长度
char a1[] = {'A', 'B', 'C'}; char a2[] = "world"; printf(, a1, , a2); printf("[%.*s][ ...
- maven+springmvc+easyui+fastjson+pagehelper
1.maven配置 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www ...
- Python学习笔记(五)Python的切片和迭代
切片 Python提供了切片操作符,可以对list.tuple.字符串进行截取操作. list中的切片应用 语法如下: >>> L = ['Michael', 'Sarah', 'T ...
- 如何实现button像a标签一样跳转页面
这个实现起来很简单,如下: <a href="{% url 'cms:add' %}"> <button class="btn btn-default& ...
- SQL Server 内存开销分析
第一步: 每一类资源用了多少内存. select clerks.type, sum(clerks.virtual_memory_reserved_kb) as Res ...
- Oracle EBS-SQL (PO-14):检查供应商信息sql
select pvs.org_id, pvs.vendor_id, pvs.vendor_site_id, hou.name 经营组织, ...
- 让Maven正确处理javac警告
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.1:compile (default ...
- Android 获取系统内置Intent
1,掉web浏览器 Uri myBlogUri = Uri.parse("http://www.yzmanga.com"); returnIt = new Intent(Inten ...
- Sonar入门(二): Maven集成Sonar
Sonar对maven提供了简单可配的支持,要做的事情很简单——在maven/conf下settings.xml <profiles></profiles>标签之间添加如下内容 ...
- Python学习笔记10-Python MysqlHelper ,MySql 辅助类
自己写了一个MySql辅助类,有需要的拿走: #--encoding:utf-8-- # import MySQLdb class MySQLHelper: myVersion=0.1 def __i ...