python - 了解 Flask 请求对象

标签 python flask

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

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

换句话说,request.is_json 如何知道它应该指向哪些数据(通过请求发送的数据)。

感谢您的帮助!

最佳答案

如果我理解正确的话,用评论中给出的细节回答你的问题;

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)

然后 flask 调用您的 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

特定的请求对象再次使用继承的 mixin 来区分 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.

如果你想在我的快速研究之后了解更多信息,请随时继续阅读源代码,或者如果你有任何问题,请发表评论。

关于python - 了解 Flask 请求对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51172720/

相关文章:

python - 在开发过程中设置 Python 路径

python - 如何在 flask 中一一处理请求?

python - 让 Flask 只接受路由上的 POST 请求

javascript - 从 javascript 与正在运行的 python 进行通信的正确方法

python - 使用 str.format() 和字典

python - 如何在 Python 中打印我的对象名称

python - 使用列表理解 "merge"列表中的列表

python - yticks 的字体大小出乎意料地可变

python - 使用参数时 flask 中的 url_for

flask - 发生错误时显示主页