zoukankan      html  css  js  c++  java
  • Flask之请求与响应

    一、请求

    Flask中的请求只需要导入以下内容即可:

    from flask import request

    request对象中有以下部分参数:

    """
    request.data
    request.form
    request.query_string
    request.method
    request.args
    request.values
    request.cookies
    request.headers
    request.path
    request.full_path
    request.script_root
    request.url
    request.base_url
    request.url_root
    request.host_url
    request.host
    request.files
    ...
    """

      如果查看request对象中存在的方法,可以去flask.wrappers.Request类下进行查看,而Request类继承了werkzeug.wrappers.Request,所以你可以去这两个类下查看对应的方法和属性。

    大部分的方法是在下面这几个个类中,查看用法可以看这几个类中对方法的一些说明:

    ##werkzeugwrappers
    equest.py
    
    from .accept import AcceptMixin
    from .auth import AuthorizationMixin
    from .base_request import BaseRequest
    from .common_descriptors import CommonRequestDescriptorsMixin
    from .cors import CORSRequestMixin
    from .etag import ETagRequestMixin
    from .user_agent import UserAgentMixin
    
    
    class Request(
        BaseRequest,
        AcceptMixin,
        ETagRequestMixin,
        UserAgentMixin,
        AuthorizationMixin,
        CORSRequestMixin,
        CommonRequestDescriptorsMixin,
    ):
        """Full featured request object implementing the following mixins:
    
        -   :class:`AcceptMixin` for accept header parsing
        -   :class:`ETagRequestMixin` for etag and cache control handling
        -   :class:`UserAgentMixin` for user agent introspection
        -   :class:`AuthorizationMixin` for http auth handling
        -   :class:`~werkzeug.wrappers.cors.CORSRequestMixin` for Cross
            Origin Resource Sharing headers
        -   :class:`CommonRequestDescriptorsMixin` for common headers
    
        """

    二、响应

    Flask中的响应只需要导入以下内容即可:

    from flask import redirect
    from flask import render_template
    from flask import make_response

    上面的三个方法都可以进行相应。

      其中make_response类的对象是flask.wrappers.Response类型,Response继承的是werkzeug.wrappers.Response类,所以如果看响应中有什么属性和方法可以去werkzeug.wrappers.Response类中查看:

    ##werkzeugwrappers
    esponse.py
    
    class Response(
        BaseResponse,
        ETagResponseMixin,
        WWWAuthenticateMixin,
        CORSResponseMixin,
        ResponseStreamMixin,
        CommonResponseDescriptorsMixin,
    ):
        """Full featured response object implementing the following mixins:
    
        -   :class:`ETagResponseMixin` for etag and cache control handling
        -   :class:`WWWAuthenticateMixin` for HTTP authentication support
        -   :class:`~werkzeug.wrappers.cors.CORSResponseMixin` for Cross
            Origin Resource Sharing headers
        -   :class:`ResponseStreamMixin` to add support for the ``stream``
            property
        -   :class:`CommonResponseDescriptorsMixin` for various HTTP
            descriptors
        """

    例如,在BaseResponse类中存在

    class BaseResponse(object):
            """
               ...
            """
        @property
        def status(self):
            """The HTTP status code as a string."""
            return self._status
        def set_cookie(
            self,
            key,
            value="",
            max_age=None,
            expires=None,
            path="/",
            domain=None,
            secure=False,
            httponly=False,
            samesite=None,
        ):
            """Sets a cookie. The parameters are the same as in the cookie `Morsel`
            object in the Python standard library but it accepts unicode data, too.
    
            A warning is raised if the size of the cookie header exceeds
            :attr:`max_cookie_size`, but the header will still be set.
    
            :param key: the key (name) of the cookie to be set.
            :param value: the value of the cookie.
            :param max_age: should be a number of seconds, or `None` (default) if
                            the cookie should last only as long as the client's
                            browser session.
            :param expires: should be a `datetime` object or UNIX timestamp.
            :param path: limits the cookie to a given path, per default it will
                         span the whole domain.
            :param domain: if you want to set a cross-domain cookie.  For example,
                           ``domain=".example.com"`` will set a cookie that is
                           readable by the domain ``www.example.com``,
                           ``foo.example.com`` etc.  Otherwise, a cookie will only
                           be readable by the domain that set it.
            :param secure: If `True`, the cookie will only be available via HTTPS
            :param httponly: disallow JavaScript to access the cookie.  This is an
                             extension to the cookie standard and probably not
                             supported by all browsers.
            :param samesite: Limits the scope of the cookie such that it will only
                             be attached to requests if those requests are
                             "same-site".
            """
            self.headers.add(
                "Set-Cookie",
                dump_cookie(
                    key,
                    value=value,
                    max_age=max_age,
                    expires=expires,
                    path=path,
                    domain=domain,
                    secure=secure,
                    httponly=httponly,
                    charset=self.charset,
                    max_size=self.max_cookie_size,
                    samesite=samesite,
                ),
            )
    
        def delete_cookie(self, key, path="/", domain=None):
            """Delete a cookie.  Fails silently if key doesn't exist.
    
            :param key: the key (name) of the cookie to be deleted.
            :param path: if the cookie that should be deleted was limited to a
                         path, the path has to be defined here.
            :param domain: if the cookie that should be deleted was limited to a
                           domain, that domain has to be defined here.
            """
            self.set_cookie(key, expires=0, max_age=0, path=path, domain=domain)
    
    ...        
        

    make_response类的对象就可以调用status()、set_cookie()等方法。

    response = make_response(render_template('index.html'))
    response.set_cookie('k1', 'v1')
  • 相关阅读:
    python 的基础 学习 第六天 基础数据类型的操作方法 字典
    python 的基础 学习 第五天 基础数据类型的操作方法
    python 的基础 学习 第四天 基础数据类型
    ASP.NET MVC 入门8、ModelState与数据验证
    ASP.NET MVC 入门7、Hellper与数据的提交与绑定
    ASP.NET MVC 入门6、TempData
    ASP.NET MVC 入门5、View与ViewData
    ASP.NET MVC 入门4、Controller与Action
    ASP.NET MVC 入门3、Routing
    ASP.NET MVC 入门2、项目的目录结构与核心的DLL
  • 原文地址:https://www.cnblogs.com/shenjianping/p/13233174.html
Copyright © 2011-2022 走看看