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. AlertDialog与DialogFragment

    1.AlertDialog 作用:简单的弹出框实现 创建方法: AlertDialog alert = new AlertDialog.Builder(); 使用: new AlertDialog.B ...

  2. deepin添加新的打开方式软件

    在/usr/share/applications文件夹中,你可以先打开一个其他的软件比如geany,然后根据geany的配置配置你所需要的新软件

  3. 自学nodejs系列

    好久没有搞nodejs了.nodejs也是更新的很快!!当初翻译的文档

  4. YUI的模块化开发

    随着互联网应用越来越重,js代码越来越庞大,如何有效的去组织自己的代码,变得非常重要.我们应该学会去控制自己的代码,而不是到最后一堆bug完全不知道从哪冒出来.前端的模块化开发可以帮助我们有效的去管理 ...

  5. 如何重载浏览器 onload 事件后加载的资源文件

    http://www.oschina.net/translate/reloading-post-onload-resources?lang=eng 怎么在webview中加载本地jquery.mi.j ...

  6. Tip.It诞生记

    灵光一闪 之所以想做 Tip.It,完全是受自己初到北京时找房子各种痛苦的启发,当时为了跳过中介租房子,去58同城,豆瓣等各种网站去看房子,比如说下图就是一个典型的58同城的租房页面. 可以看到电话号 ...

  7. 解决GitHub未配置SSH key提示错误信息

    git push -u origin master Permission denied (publickey). fatal: Could not read from remote repositor ...

  8. 开发SCM系统笔记001

    使用EasyUI分页问题: 1.在分页界面没有显示声明分页属性名称,系统如何获取? EasyUI会向后台发送page\rows两个参数. 2.在配置sql参数时,parametertype与param ...

  9. [Django实战] 第3篇 - 用户认证(初始配置)

    当大家打开一个网站时,第一步做什么?大部分一定是先登录吧,所以我们就从用户认证开始. 打开用户认证 Django本身已经提供了用户认证模块,使用它可以大大简化用户认证模块的开发,默认情况下,用户认证模 ...

  10. poj2387-Til the Cows Come Home dijkstra获得水的问题

    Til the Cows Come Home Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 29539   Accepted ...