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 客户端IP
  • REMOTE_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 (like process_request, you can use process_view instead).

应用代码设置的属性

Django本身不设置这些属性,可以被服务端设置的属性

HttpRequest.current_app
Django 1.8后新属性

The url template tag will use its value as the current_app argument to reverse().

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 to None to revert any changes made by previous middleware and return to using theROOT_URLCONF.

Changed in Django 1.9:

Setting urlconf=None raised ImproperlyConfigured in older versions.

被中间件设置的属性

Django项目中要求包含这些中间件,如果请求中看不到这些属性, 查看下这些中间件列表 MIDDLEWARE_CLASSES.

HttpRequest.session

来自 SessionMiddleware中间件:一个可读写类似字典对象的当前会话

HttpRequest.site

来自 CurrentSiteMiddleware中间件: An instance of Site or RequestSite as returned byget_current_site() representing the current site.

HttpRequest.user

来是 AuthenticationMiddleware中间件: An instance of AUTH_USER_MODEL representing the currently logged-in user. If the user isn’t currently logged in, user will be set to an instance of AnonymousUser. You can tell them apart with is_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 or CsrfViewMiddleware.

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(keydefault=RAISE_ERRORsalt=''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 the default 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, the max_age argument will be checked against the signed timestamp attached to the cookie value to ensure the cookie is not older than max_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)
False

See 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对象的更多相关文章

  1. [R]django的HTTPREQUEST对象

    django的HTTPREQUEST对象 via Django使用request和response对象 当请求一张页面时,Django把请求的metadata数据包装成一个HttpRequest对象, ...

  2. django的HTTPREQUEST对象

    Django使用request和response对象 当请求一张页面时,Django把请求的metadata数据包装成一个HttpRequest对象,然后Django加载合适的view方法,把这个Ht ...

  3. Django的httprequest对象和httpresponse对象

    请求一张页面时,Django把请求的metadata数据包装成一个HttpRequest对象,然后Django加载合适的view方法,把这个HttpRequest 对象作为第一个参数传给view方法. ...

  4. $Django 虚拟环境,2.0、1.0路由层区别,Httprequest对象,视图层(fbv,cbv),文件上传

    1 虚拟环境:解决问题同一台机器上可以运行不同版本的django,  1 用pychanrm创建--->files-->newproject--->选择虚拟环境  2 setting ...

  5. django HttpRequest对象

    概述: 服务器接收http请求后,会根据报文创建HttpRequest对象 视图的第一个参数就是HttpRequest对象 django创建的,之后调用视图时传递给视图 属性 path:请求的完整路径 ...

  6. Django 10 GET和POST(HttpRequest对象,GET和POST请求,文件上传,HttpResponse对象的cookie)

    Django 10 GET和POST(HttpRequest对象,GET和POST请求,文件上传,HttpResponse对象的cookie) 一.HttpRequest对象 #HttpRequest ...

  7. Django框架之第四篇(视图层)--HttpRequest对象、HttpResponse对象、JsonResponse、CBV和FBV、文件上传

    视图层 一.视图函数 一个视图函数,简称视图,是一个简单的python函数,它接收web请求并且会返回web响应.响应可以是一张网页的html,一个重定向,或者是一张图片...任何东西都可以.无论是什 ...

  8. django.http.request中HttpRequest对象的一些属性与方法

    HttpRequest对象的属性 属性 描述 path 表示提交请求页面完整地址的字符串,不包括域名,如 "/music/bands/the_beatles/". method 表 ...

  9. Django框架(九):视图(二) HttpRequest对象、HttpResponse对象

    1. HttpRequest对象 服务器接收到http协议的请求后,会根据报文创建HttpRequest对象,这个对象不需要我们创建,直接使用服务器构造好的对象就可以.视图的第一个参数必须是HttpR ...

随机推荐

  1. printf--动态指定输出格式长度

    char a1[] = {'A', 'B', 'C'}; char a2[] = "world"; printf(, a1, , a2); printf("[%.*s][ ...

  2. maven+springmvc+easyui+fastjson+pagehelper

    1.maven配置 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www ...

  3. Python学习笔记(五)Python的切片和迭代

    切片 Python提供了切片操作符,可以对list.tuple.字符串进行截取操作. list中的切片应用 语法如下: >>> L = ['Michael', 'Sarah', 'T ...

  4. 如何实现button像a标签一样跳转页面

    这个实现起来很简单,如下: <a href="{% url 'cms:add' %}"> <button class="btn btn-default& ...

  5. SQL Server 内存开销分析

    第一步: 每一类资源用了多少内存. select          clerks.type,         sum(clerks.virtual_memory_reserved_kb) as Res ...

  6. Oracle EBS-SQL (PO-14):检查供应商信息sql

    select pvs.org_id, pvs.vendor_id, pvs.vendor_site_id, hou.name                                 经营组织, ...

  7. 让Maven正确处理javac警告

    [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.1:compile (default ...

  8. Android 获取系统内置Intent

    1,掉web浏览器 Uri myBlogUri = Uri.parse("http://www.yzmanga.com"); returnIt = new Intent(Inten ...

  9. Sonar入门(二): Maven集成Sonar

    Sonar对maven提供了简单可配的支持,要做的事情很简单——在maven/conf下settings.xml <profiles></profiles>标签之间添加如下内容 ...

  10. Python学习笔记10-Python MysqlHelper ,MySql 辅助类

    自己写了一个MySql辅助类,有需要的拿走: #--encoding:utf-8-- # import MySQLdb class MySQLHelper: myVersion=0.1 def __i ...