flask 源碼解析:請求

轉載於:http://cizixs.com/2017/01/18/flask-insight-request

簡介

對於物理鏈路來說,請求只是不同電壓信號,它根本不知道也不需要知道請求格式和內容到底是怎樣的; 對於 TCP 層來說,請求就是傳輸的數據(二進制的數據流),它只要發送給對應的應用程序就行了; 對於 HTTP 層的服務器來說,請求必須是符合 HTTP 協議的內容; 對於 WSGI server 來說,請求又變成了文件流,它要讀取其中的內容,把 HTTP 請求包含的各種信息保存到一個字典中,調用 WSGI app; 對於 flask app 來說,請求就是一個對象,當需要某些信息的時候,只需要讀取該對象的屬性或者方法就行了。

可以看到,雖然是同樣的請求數據,在不同的階段和不同組件看來,是完全不同的形式。因爲每個組件都有它本身的目的和功能,這和生活中的事情一個道理:對於同樣的事情,不同的人或者同一個人不同人生階段的理解是不一樣的。

這篇文章呢,我們只考慮最後一個內容,flask 怎麼看待請求。

請求

我們知道要訪問 flask 的請求對象非常簡單,只需要 from flask import request

from flask import request

with app.request_context(environ):
    assert request.method == 'POST'

前面一篇文章 已經介紹了這個神奇的變量是怎麼工作的,它最後對應了 flask.wrappers:Request 類的對象。 這個類內部的實現雖然我們還不清楚,但是我們知道它接受 WSGI server 傳遞過來的 environ 字典變量,並提供了很多常用的屬性和方法可以使用,比如請求的 method、path、args 等。 請求還有一個不那麼明顯的特性——它不能被應用修改,應用只能讀取請求的數據。

這個類的定義很簡單,它繼承了 werkzeug.wrappers:Request,然後添加了一些屬性,這些屬性和 flask 的邏輯有關,比如 view_args、blueprint、json 處理等。它的代碼如下:

from werkzeug.wrappers import Request as RequestBase


class Request(RequestBase):
    """
    The request object is a :class:`~werkzeug.wrappers.Request` subclass and
    provides all of the attributes Werkzeug defines plus a few Flask
    specific ones.
    """

    #: 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.
    url_rule = None

    #: A dict of view arguments that matched the request.  If an exception
    #: happened when matching, this will be ``None``.
    view_args = None

    @property
    def max_content_length(self):
        """Read-only view of the ``MAX_CONTENT_LENGTH`` config key."""
        ctx = _request_ctx_stack.top
        if ctx is not None:
            return ctx.app.config['MAX_CONTENT_LENGTH']

    @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

    @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]

    @property
    def is_json(self):
        mt = self.mimetype
        if mt == 'application/json':
            return True
        if mt.startswith('application/') and mt.endswith('+json'):
            return True
        return False

這段代碼沒有什難理解的地方,唯一需要說明的就是 @property 裝飾符能夠把類的方法變成屬性,這是 python 中經常見到的用法。

接着我們就要看 werkzeug.wrappers:Request

class Request(BaseRequest, AcceptMixin, ETagRequestMixin,
              UserAgentMixin, AuthorizationMixin,
              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:`CommonRequestDescriptorsMixin` for common headers
    """

這個方法有一點比較特殊,它沒有任何的 body。但是有多個基類,第一個是 BaseRequest,其他的都是各種 Mixin。 這裏要講一下 Mixin 機制,這是 python 多繼承的一種方式,如果你希望某個類可以自行組合它的特性(比如這裏的情況),或者希望某個特性用在多個類中,就可以使用 Mixin。 如果我們只需要能處理各種 Accept 頭部的請求,可以這樣做:

class Request(BaseRequest, AcceptMixin)
    pass

但是不要濫用 Mixin,在大多數情況下子類繼承了父類,然後實現需要的邏輯就能滿足需求。

我們先來看看 BaseRequest:

class BaseRequest(object):
    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

能看到實例化需要的唯一變量是 environ,它只是簡單地把變量保存下來,並沒有做進一步的處理。Request 的內容很多,其中相當一部分是被 @cached_property 裝飾的方法,比如下面這種:

    @cached_property
    def args(self):
        """The parsed URL parameters."""
        return url_decode(wsgi_get_bytes(self.environ.get('QUERY_STRING', '')),
                          self.url_charset, errors=self.encoding_errors,
                          cls=self.parameter_storage_class)

    @cached_property
    def stream(self):
        """The stream to read incoming data from.  Unlike :attr:`input_stream`
        this stream is properly guarded that you can't accidentally read past
        the length of the input.  Werkzeug will internally always refer to
        this stream to read data which makes it possible to wrap this
        object with a stream that does filtering.
        """
        _assert_not_shallow(self)
        return get_input_stream(self.environ)

    @cached_property
    def form(self):
        """The form parameters."""
        self._load_form_data()
        return self.form

    @cached_property
    def cookies(self):
        """Read only access to the retrieved cookie values as dictionary."""
        return parse_cookie(self.environ, self.charset,
                            self.encoding_errors,
                            cls=self.dict_storage_class)

    @cached_property
    def headers(self):
        """The headers from the WSGI environ as immutable
        :class:`~werkzeug.datastructures.EnvironHeaders`.
        """
        return EnvironHeaders(self.environ)

@cached_property 從名字就能看出來,它是 @property 的升級版,添加了緩存功能。我們知道 @property 能把某個方法轉換成屬性,每次訪問屬性的時候,它都會執行底層的方法作爲結果返回。 @cached_property 也一樣,區別是隻有第一次訪問的時候纔會調用底層的方法,後續的方法會直接使用之前返回的值。 那麼它是如何實現的呢?我們能在 werkzeug.utils 找到它的定義:

class cached_property(property):

    """A decorator that converts a function into a lazy property.  The
    function wrapped is called the first time to retrieve the result
    and then that calculated result is used the next time you access
    the value.

    The class has to have a `__dict__` in order for this property to
    work.
    """

    # implementation detail: A subclass of python's builtin property
    # decorator, we override __get__ to check for a cached value. If one
    # choses to invoke __get__ by hand the property will still work as
    # expected because the lookup logic is replicated in __get__ for
    # manual invocation.

    def __init__(self, func, name=None, doc=None):
        self.__name__ = name or func.__name__
        self.__module__ = func.__module__
        self.__doc__ = doc or func.__doc__
        self.func = func

    def __set__(self, obj, value):
        obj.__dict__[self.__name__] = value

    def __get__(self, obj, type=None):
        if obj is None:
            return self
        value = obj.__dict__.get(self.__name__, _missing)
        if value is _missing:
            value = self.func(obj)
            obj.__dict__[self.__name__] = value
        return value

這個裝飾器同時也是實現了 __set__ 和 __get__ 方法的描述器。 訪問它裝飾的屬性,就會調用 __get__ 方法,這個方法先在 obj.__dict__ 中尋找是否已經存在對應的值。如果存在,就直接返回;如果不存在,調用底層的函數 self.func,並把得到的值保存起來,再返回。這也是它能實現緩存的原因:因爲它會把函數的值作爲屬性保存到對象中。

關於 Request 內部各種屬性的實現,就不分析了,因爲它們每個具體的實現都不太一樣,也不復雜,無外乎對 environ 字典中某些字段做一些處理和計算。 接下來回過頭來看看 Mixin,這裏只用 AcceptMixin 作爲例子:

class AcceptMixin(object):

    @cached_property
    def accept_mimetypes(self):
        return parse_accept_header(self.environ.get('HTTP_ACCEPT'), MIMEAccept)

    @cached_property
    def accept_charsets(self):
        return parse_accept_header(self.environ.get('HTTP_ACCEPT_CHARSET'),
                                   CharsetAccept)

    @cached_property
    def accept_encodings(self):
        return parse_accept_header(self.environ.get('HTTP_ACCEPT_ENCODING'))

    @cached_property
    def accept_languages(self):
        return parse_accept_header(self.environ.get('HTTP_ACCEPT_LANGUAGE'),
                                   LanguageAccept)

AcceptMixin 實現了請求內容協商的部分,比如請求接受的語言、編碼格式、相應內容等。 它也是定義了很多 @cached_property 方法,雖然自己沒有 __init__ 方法,但是也直接使用了 self.environ,因此它並不能直接使用,只能和 BaseRequest 一起出現。

參考資料


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章