[Flask] Should extension use an app instance if it's passed to constructor or just always use flask.current_app?

David Lord davidism at gmail.com
Sat Apr 9 10:51:52 EDT 2016


If the app is passed in, you can optionally choose to use it. See 
Flask-SQLAlchemy for an example of how to check multiple sources for the 
app. It’s probably better to always rely on |current_app|, because then 
instructions for using the extension are consistent: it must always be 
in a valid app context. People following instructions that assume the 
app was passed in is a common source of questions on Stack Overflow. The 
tradeoff is that you have to remember to push an app context (or use a 
shell from Flask-Script, etc. that does that for you), you can’t just 
use the extension directly.

On 04/09/2016 05:58 AM, Andrew Pashkin wrote:

> Hello, everybody!
>
> I'm reading about extensions development 
> <http://flask.pocoo.org/docs/0.10/extensiondev/> and it says:
>
>     As you noticed, |init_app| does not assign |app| to |self|. This
>     is intentional! *Class based Flask extensions must only store the
>     application on the object when the application was passed to the
>     constructor.* This tells the extension: I am not interested in
>     using multiple applications.
>
>     *When the extension needs to find the current application and it
>     does not have a reference to it, it must either use the
>     **|current_app|
>     <http://flask.pocoo.org/docs/0.10/api/#flask.current_app>* context
>     local or change the API in a way that you can pass the application
>     explicitly.
>
> But the example extension 
> <http://flask.pocoo.org/docs/0.10/extensiondev/#the-extension-code>, 
> just uses flask.current_app, without checking whether an application 
> instance was attached to the extension instance:
>
>     ... def  connect(self):
>          return  sqlite3.connect(*current_app*.config['SQLITE3_DATABASE'])
>     ...
>
> So, where is the truth? What extension should really do - always use 
> flask.current_app, or use it only if application instance wasn't 
> passed to the constructor?
> -- 
> With kind regards, Andrew Pashkin.
> cell phone - +7 (985) 898 57 59
> Skype - waves_in_fluids
> e-mail -andrew.pashkin at gmx.co.uk
>
>
> _______________________________________________
> Flask mailing list
> Flask at python.org
> https://mail.python.org/mailman/listinfo/flask

​
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/flask/attachments/20160409/f2a3b424/attachment-0001.html>


More information about the Flask mailing list