zoukankan      html  css  js  c++  java
  • 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 客户端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()
    View Code

    该中间就被其他中间件需要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

    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
    View Code

    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)
  • 相关阅读:
    编译安装zabbix3.2
    编译安装PHP的参数 --with-mysql --with-mysqli --with-apxs2默认路径
    MySql中指定符号分割并分行展示
    Linux中vim编辑器常用命令
    Ubuntu中安装配置 JDK与apache
    Ubuntu中python链接本地数据库
    oracle函数笔记(1)
    Oracle的五种约束
    斐波那契数列
    python计算圆面积
  • 原文地址:https://www.cnblogs.com/goldd/p/5508939.html
Copyright © 2011-2022 走看看