了解烧瓶请求对象

时间:2018-07-04 11:34:26

标签: python flask

我想了解request中的Flask对象是如何工作的。具体而言,通过查看以下来自here的代码。 enter image description here

我的问题是:request对象与发出的实际请求之间的链接在哪里?

用另一种方式,request.is_json如何知道应该指向哪个数据(通过请求发送的数据)。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

如果我正确理解,请使用评论中的具体内容回答您的问题;

第一次启动request服务器时会创建Flask对象,但是,flask跟踪了请求上下文堆栈,所有请求最终都结束了。

Request stack accessing, source

def _lookup_req_object(name):
    top = _request_ctx_stack.top
    if top is None:
        raise RuntimeError(_request_ctx_err_msg)
    return getattr(top, name)

然后烧瓶将为您的URL调用特定端点,您可以从该端点访问请求对象。由于flask实际上使用了来自werkzeug的BaseRequest对象,因此它继承了get_data方法,该方法反序列化请求数据以供以后解析。

werkzeug get_data() impllementation, source

def get_data(self, as_text=False):
    """The string representation of the request body.  Whenever you call
    this property the request iterable is encoded and flattened.  This
    can lead to unwanted behavior if you stream big data.
    This behavior can be disabled by setting
    :attr:`implicit_sequence_conversion` to `False`.
    If `as_text` is set to `True` the return value will be a decoded
    unicode string.
    .. versionadded:: 0.9
    """
    self._ensure_sequence()
    rv = b''.join(self.iter_encoded())
    if as_text:
        rv = rv.decode(self.charset)
    return rv

特定请求对象再次使用继承的mixins来区分其他内容中的json。

class Request(RequestBase, JSONMixin):
    """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.

如果您想比我快速研究后了解更多信息,或者有任何疑问,请随时发表评论。