#๐Ÿ”’ Can't understand test_request_context in flask

16 messages ยท Page 1 of 1 (latest)

sharp spear
#

I don't get when and why we use it. If we want to test a function with request data can't we just do it normally by running the code with a normal function?

past marshBOT
#

@sharp spear

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

sharp spear
#

also why do we often use "with" along with it? what's the point of closing the file when an error occurs?

severe sonnet
#

If you don't close the file when an error occurs it might still be running in the background; leading to memory leaks.

brave temple
#

the great context manager

royal edge
#

@sharp spear ^^

sharp spear
#

yeah thanks guys

#

can someone also explain the reason why using test_request_context is practical?

#

is it so we can test the function within the backend instead of having to start a server?

red wyvern
#

is test_request_context from a library? or is it a module in the std library? Is it a built-in?

royal edge
#

It's plain from the topic title that this is a Flask function.

royal edge
# sharp spear is it so we can test the function within the backend instead of having to start ...

Yes, this.

See: https://flask.palletsprojects.com/en/stable/api/#flask.Flask.request_context
and the docs for test_request_context directly below it.

When your WSGI application (Flask server) responds to a request it makes a request context for you to work from.

In testing you don't run a server, and test_request_server makes the request context suitably from your specification of the request you're testing.

There's example use here:
https://flask.palletsprojects.com/en/stable/testing/#tests-that-depend-on-an-active-context

#

The context manager will be

  • making the context object
  • pushing it onto the state so that it's "just there" for you to use
  • popping it off again when you exit the with
past marshBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.