Flask源码:wrappers.py(继承request,response类)

# -*- coding: utf-8 -*-
"""
    flask.wrappers
    ~~~~~~~~~~~~~~
    Implements the WSGI wrappers (request and response).
    继承werkzeug的Request,Response基类,添加一些属性和方法,形成Flask的Request,Response类
"""
from werkzeug.exceptions import BadRequest
from werkzeug.wrappers import Request as RequestBase
from werkzeug.wrappers import Response as ResponseBase
from werkzeug.wrappers.json import JSONMixin as _JSONMixin

from . import json
from .globals import current_app


class JSONMixin(_JSONMixin):
    json_module = json

    def on_json_loading_failed(self, e):
        if current_app and current_app.debug:
            raise BadRequest("Failed to decode JSON object: {0}".format(e))
        raise BadRequest()


class Request(RequestBase, JSONMixin):
    
    url_rule = None    #实例的路由规则
    view_args = None
    routing_exception = None    #路由失败的异常信息
    
    #以下用property方法封装了一些Flask内部调用方法
    @property
    def max_content_length(self):
        """
        默认是None
        """
        if current_app:
            return current_app.config["MAX_CONTENT_LENGTH"]

    @property
    def endpoint(self):
        """
        获取当前视图函数的函数名
        """
        if self.url_rule is not None:
            return self.url_rule.endpoint

    @property
    def blueprint(self):
        """
        获取当前蓝图的名称
        """
        if self.url_rule and "." in self.url_rule.endpoint:
            return self.url_rule.endpoint.rsplit(".", 1)[0]

    def _load_form_data(self):
        """
        重载父类方法,添加调试处理
        """
        RequestBase._load_form_data(self)

        if (
            current_app
            and current_app.debug
            and self.mimetype != "multipart/form-data"
            and not self.files
        ):
            from .debughelpers import attach_enctype_error_multidict

            attach_enctype_error_multidict(self)


class Response(ResponseBase, JSONMixin):
    """
    默认由Flask使用,不需要使用直接使用这个对象,调用make_response方法就可以获取
    重载response 对象只需要继承这个类再设置response_class属性指向即可
    """
    
    #默认的Http响应头Content-Type:text/html; charset=utf-8
    default_mimetype = "text/html"
    
    #get_data()用来获取Http请求的body,封装函数名给子类调用
    def _get_data_for_json(self, cache):
        return self.get_data()

    @property        #也是用property方法的封装config的键值
    def max_cookie_size(self):
        if current_app:
            return current_app.config["MAX_COOKIE_SIZE"]
        return super(Response, self).max_cookie_size

werkzeug.wrappers的Request和ResponseBase

class Request(
    BaseRequest,    #Request基类
    AcceptMixin,
    ETagRequestMixin,
    UserAgentMixin,
    AuthorizationMixin,
    CommonRequestDescriptorsMixin,
):
    """Full featured request object implementing the following mixins:

    - :class:`AcceptMixin` for accept header parsing    #HTTP头解析器
    - :class:`ETagRequestMixin` for etag and cache control handling    #缓存控制
    - :class:`UserAgentMixin` for user agent introspection    #UserAgent相关
    - :class:`AuthorizationMixin` for http auth handling    #认证相关
    - :class:`CommonRequestDescriptorsMixin` for common headers    #
    """


class Response(
    BaseResponse,    #Response基类
    ETagResponseMixin,
    ResponseStreamMixin,
    CommonResponseDescriptorsMixin,
    WWWAuthenticateMixin,
):
    """Full featured response object implementing the following mixins:

    - :class:`ETagResponseMixin` for etag and cache control handling    #缓存控制
    - :class:`ResponseStreamMixin` to add support for the `stream` property    #
    - :class:`CommonResponseDescriptorsMixin` for various HTTP descriptors    #
    - :class:`WWWAuthenticateMixin` for HTTP authentication support    #认证相关
    """

"""
这两个类的doc表明这两个类都是由一些类组合而成,类似建造者模式
"""

base_request.py的BaseRequest基类

class BaseRequest(object):
    """
    最底层的Request类,没有实现任何高级方法    
    """

    charset = "utf-8"    #默认编码    
    encoding_errors = "replace"
    max_content_length = None    #最大内容值    
    ''
    ''
    ''
    ''

    def __init__(self, environ, populate_request=True, shallow=False):
        self.environ = environ
        if populate_request and not shallow:
            self.environ["werkzeug.request"] = self
        self.shallow = shallow
    ''
    ''
    ''
    ''
    #视图函数的request.method
    method = environ_property(
        "REQUEST_METHOD",
        "GET",
        read_only=True,
        load_func=lambda x: x.upper(),
        doc="The request method. (For example ``'GET'`` or ``'POST'``).",
    )
    
    #视图函数的request.cookies
    @cached_property
    def cookies(self):
        return parse_cookie(
            self.environ,
            self.charset,
            self.encoding_errors,
            cls=self.dict_storage_class,
        )

    #视图函数的request.headers
    @cached_property
    def headers(self):
        return EnvironHeaders(self.environ)

    #视图函数的request.path
    @cached_property
    def path(self):
        raw_path = wsgi_decoding_dance(
            self.environ.get("PATH_INFO") or "", self.charset, self.encoding_errors
        )
        return "/" + raw_path.lstrip("/")
    ""
    ""
    ""
    ""
    ""

    """
    Flask的request的很多属性和方法都在这个类实现
    """
发布了23 篇原创文章 · 获赞 0 · 访问量 2018

猜你喜欢

转载自blog.csdn.net/qq_33913982/article/details/104242980