flask源码笔记:三,app.py模块(3)——Flask的初始化之请求和响应

来源:互联网 发布:arcgis数据视图做表格 编辑:程序博客网 时间:2024/05/16 12:00
初始化工作包含了属性设定和__init__函数
源代码:
    #: The class that is used for request objects.  See :class:`~flask.Request`
    #: for more information.
    request_class = Request


    #: The class that is used for response objects.  See
    #: :class:`~flask.Response` for more information.
    response_class = Response


从flask/wrappers.py中获取类Request,Response
源代码:
class Request(RequestBase):
    """The request object used by default in Flask.  Remembers the
    matched endpoint and view arguments.


    It is what ends up as :class:`~flask.request`.  If you want to replace
    the request object used you can subclass this and set
    :attr:`~flask.Flask.request_class` to your subclass.


    The request object is a :class:`~werkzeug.wrappers.Request` subclass and
    provides all of the attributes Werkzeug defines plus a few Flask
    specific ones.
    """
#揭示了RequestBase基类的来源:werkzeug.wrappers.Request


    #: the internal URL rule that matched the request.  This can be
    #: useful to inspect which methods are allowed for the URL from
    #: a before/after handler (``request.url_rule.methods``) etc.
    #:
    #: .. versionadded:: 0.6
    url_rule = None
#URL路由规则初始化


    #: a dict of view arguments that matched the request.  If an exception
    #: happened when matching, this will be `None`.
    view_args = None
#当请求匹配到视图函数时的传入到视图函数的参数


    #: if matching the URL failed, this is the exception that will be
    #: raised / was raised as part of the request handling.  This is
    #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or
    #: something similar.
    routing_exception = None
#路由匹配异常的时,用到的属性,通常直接报404 not found(通过werkzeug.exceptions.NotFound)


    # switched by the request context until 1.0 to opt in deprecated
    # module functionality
    _is_old_module = False
#设定是否使用旧版本的module而非blueprint的属性


    @property
    def max_content_length(self):
        """Read-only view of the `MAX_CONTENT_LENGTH` config key."""
        ctx = _request_ctx_stack.top                #_request_ctx_stack是一个栈,.top是它的最上面的一个元素
        if ctx is not None:
            return ctx.app.config['MAX_CONTENT_LENGTH']
#根据请求上下文,获取其app的配置


    @property
    def endpoint(self):
        """The endpoint that matched the request.  This in combination with
        :attr:`view_args` can be used to reconstruct the same or a
        modified URL.  If an exception happened when matching, this will
        be `None`.
        """
        if self.url_rule is not None:
            return self.url_rule.endpoint
#只读属性,获取端点,其实是返回self.url_rule.endpoint


    @property
    def module(self):
        """The name of the current module if the request was dispatched
        to an actual module.  This is deprecated functionality, use blueprints
        instead.
        """
        from warnings import warn
        warn(DeprecationWarning('modules were deprecated in favor of '
                                'blueprints.  Use request.blueprint '
                                'instead.'), stacklevel=2)
        if self._is_old_module:
            return self.blueprint
#只读属性,获取module属性,旧版本所用,新版本用blueprint


    @property
    def blueprint(self):
        """The name of the current blueprint"""
        if self.url_rule and '.' in self.url_rule.endpoint:
            return self.url_rule.endpoint.rsplit('.', 1)[0]
#只读属性,获取blueprint属性


    @property
    def json(self):
        """If the mimetype is `application/json` this will contain the
        parsed JSON data.  Otherwise this will be `None`.


        The :meth:`get_json` method should be used instead.
        """
        # XXX: deprecate property
        return self.get_json()
#只读属性,获取请求中的json格式的字符串,并以对应的数据结构返回它


    def get_json(self, force=False, silent=False, cache=True):
        """Parses the incoming JSON request data and returns it.  If
        parsing fails the :meth:`on_json_loading_failed` method on the
        request object will be invoked.  By default this function will
        only load the json data if the mimetype is ``application/json``
        but this can be overriden by the `force` parameter.


        :param force: if set to `True` the mimetype is ignored.
        :param silent: if set to `False` this method will fail silently
                       and return `False`.
        :param cache: if set to `True` the parsed JSON data is remembered
                      on the request.
        """
        rv = getattr(self, '_cached_json', _missing)
        if rv is not _missing:
            return rv


        if self.mimetype != 'application/json' and not force:
            return None


        # We accept a request charset against the specification as
        # certain clients have been using this in the past.  This
        # fits our general approach of being nice in what we accept
        # and strict in what we send out.
        request_charset = self.mimetype_params.get('charset')
        try:
            data = _get_data(self, cache)
            if request_charset is not None:
                rv = json.loads(data, encoding=request_charset)
            else:
                rv = json.loads(data)
        except ValueError as e:
            if silent:
                rv = None
            else:
                rv = self.on_json_loading_failed(e)
        if cache:
            self._cached_json = rv
        return rv
#获取请求中的json格式的字符串,并以对应的数据结构返回它


    def on_json_loading_failed(self, e):
        """Called if decoding of the JSON data failed.  The return value of
        this method is used by :meth:`get_json` when an error occurred.  The
        default implementation just raises a :class:`BadRequest` exception.


        .. versionchanged:: 0.10
           Removed buggy previous behavior of generating a random JSON
           response.  If you want that behavior back you can trivially
           add it by subclassing.


        .. versionadded:: 0.8
        """
        raise BadRequest()
#如果解析json失败,则返回一个错误请求类


    def _load_form_data(self):
        RequestBase._load_form_data(self)


        # in debug mode we're replacing the files multidict with an ad-hoc
        # subclass that raises a different error for key errors.
        ctx = _request_ctx_stack.top
        if ctx is not None and ctx.app.debug and \
           self.mimetype != 'multipart/form-data' and not self.files:
            attach_enctype_error_multidict(self)
#debug模式中,以各种报错信息替换原有的错误




class Response(ResponseBase):
    """The response object that is used by default in Flask.  Works like the
    response object from Werkzeug but is set to have an HTML mimetype by
    default.  Quite often you don't have to create this object yourself because
    :meth:`~flask.Flask.make_response` will take care of that for you.


    If you want to replace the response object used you can subclass this and
    set :attr:`~flask.Flask.response_class` to your subclass.
    """
    default_mimetype = 'text/html'
#设置默认的mime类型为'text/html',其余的和Werkzeug的响应基类一样
0 0
原创粉丝点击