Flask Testing: Test App Request? Flask Testing: Test App Request? flask flask

Flask Testing: Test App Request?


There's plenty of reading to do on the subject, so start with the documentation: app_context, test_request_context, and you can always double-check the code: app_context and test_request_context. In addition, here's an article discussion Flask's contexts.

That's a lot of links, so for a break-down:

We can see that app_context creates a new application context, while test_request_context creates a new request context. Application contexts are created in two situations: manually with app_context and when a request context is created, which, in turn, is created with test_request_context or at the beginning of the request.

So when a request comes into your application, a RequestContext is created. The creation of this object creates an application context.

Why test_request_context? You need that context to access the application when working outside of a context created by a request, like proxies that you probably recognize, like current_app, request, g, and session. Going down into the code, when you create a RequestContext with test_request_context instead of request_context, you're getting a EnvironBuilder object.


Check out tbicr 's answer here.

Specifically, this snippet of code

gravatar = u.gravatar()gravatar_256 = u.gravatar(size=256)gravatar_pg = u.gravatar(rating='pg')gravatar_retro = u.gravatar(default='retro')

requires request context since it needs to access 'request' variable.

The definition of gravatar method in User Model needs 'request' variable.

def gravatar(self, size=100, default='identicon', rating='g'):         if request.is_secure: # here            url = 'https://secure.gravatar.com/avatar'         else:              url = 'http://www.gravatar.com/avatar'         hash = self.avatar_hash or hashlib.md5(self.email.encode('utf-8')).hexdigest()         return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(url=url, hash=hash, size=size, default=default, rating=rating)