I would like to understand how the request object from Flask works. Specifically, by looking at the code below, taken from here.

My question is: where is the link between the requestobject, and the actual request that is made?
Put another way, how does request.is_json knows which data it should point to (the data sent through the request).
Thanks for any help!
To answer your question with the specifics given in the comments, if I understood it correctly;
The request object is created when you first start your Flask server, however, flask keeps track of a request context stack, there all requests ends up.
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)
Then the flask calls the specific endpoint for your url and from that endpoint you can access the request object. Since flask actually uses the BaseRequest object from werkzeug it inherits the get_data method which deserializes the request data for later parsing.
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
The specific request object again uses inherited mixins to be able to tell json from other content.
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.
Feel free to continue reading the source if you wanna know more than after my quick time research, or if you have any question just leave a comment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With