How does flask's app pattern works? - python

I'm willing to understand how Flask's internal app pattern works. I'm not talking about blueprints.
Flask is working differently from eg. Django because you can instanciate any number of apps and give them config.
I'm wondering how Flask's handles config. How does it pass this object to all the parts of the app.
I'm wondering about that because I want to refactor the config of my application to follow this pattern, so I need to understand it.
Edit: I don't have any problem with the Config. I'm just trying to replicate the pattern used in Flask.
Thanks,
Alexis.

In Flask app.config is a dictionary. You can put your configuration data there. That's it.
Wherever you import of reference app it will come with it's config attribute which you can access.

Related

What does it mean to register a blueprint into the app in Flask?

I am going through the flask documentation and the source code of flask to develop a deeper understanding of the framework. Also, I have gone through What are Flask Blueprints, exactly?.
I understand how blueprint helps in modularization of code and reuse of functions.
But it seems that I am not grokking Flask app object and what does it mean to register a blueprint to it.
In the code documentation, it says that a blueprint defers the need for an application by recording them for later registrations. Also, a Blueprint is an object that allows defining application functions without requiring application object ahead of time.
I understand that we use blueprint the same way. As in instead of #app.route, you use, #bp.route and then register that bp into the app by calling app.register_blueprint(some_bp).
Can somebody help me understand it in a better way and help fill the gap in my understanding?
Here I am going to detail the two points that you mentioned. You can also read this response that details the use of blueprint and check the flask official example on github.
a blueprint defers the need for an application by recording them for later registrations
A good practice for bigger applications is to use Application Factory. There are multiple reasons to use that:
Testing.
Multiple instances.
Application factory looks like:
def create_app():
app = Flask(__name__)
return app
When you start your application with the following commands, flask will look for create_app function and call it:
$ export FLASK_APP=myapp
$ flask run
Now that your application is running, the app object is not accessible outside the scope of the function because it will be created while flask run is executed. So you can not do in your file:
def create_app():
...
#app.route() # this does not work, because app does not exist.
For small applications or specific cases, you could define your route inside the create_app.
def create_app():
app = Flask(__name__)
#app.route("Hello")
def hello():
return "Hello"
return app
You clearly see the problem now. You are going to create all your routes inside a unique function (unreadable, bad practices, ...)
Here comes the blueprint. If you have created blueprints in your app (see flaskr example). You can register them in create_app when flask run is executed. You can register them whenever you want in your create_app after some initialization of extensions, some startup code, or whatever. You can also do dynamic registration.
def create_app():
app = Flask(__name__)
# apply the blueprints to the app
from mymodule import auth, blog
app.register_blueprint(auth.bp)
app.register_blueprint(blog.bp)
For the second point:
a Blueprint is an object that allows defining application functions without requiring application object ahead of time.
As you can see above, when we register a blueprint to an app. The blueprint does not know the app.
app.register(blueprint) # blueprint is registered to the app.
# unlike extensions that need to know the app.
db.init_app(app) # initialization and the app is giving to the extension.
Blueprint can create routes without the app object and can be attached to an existing app. So you can define your routes as they are in an app without really being in.
They are multiple advantages to use blueprints, routes as a module, multiple blueprints, provide template filters, static files, templates, and other utilities through blueprints, ... Some are details here: Modular Applications with Blueprints
The flask documentation is really well documented and everything that I have explained are explained in the flask documentation. Also the flaskr example is the most correct way to create a basic app and there is a official tutorial for following the different steps of the creation of flaskr.

Difference between namespaces and blueprints in flask-restful and flask

I am unable to understand the what purpose does blueprints and namespaces serve in web app.
I read the documentation but cannot figure it out exactly.
It would be really helpful for me if you give a simple explanation with example for each case.
Thanks!
I may still be missing something, but this tutorial seems to clarify the documentation a bit more.
Regarding #code_dredd's comment:
why should anyone choose to use a Blueprint over a Namespace (or viceversa) when both claim to have the same purpose?
Namespaces appear to be intended for organizing REST endpoints within a given API, whereas Blueprints, in this context, appear to be intended for allowing multiple APIs to be mixed and matched with other APIs or non-REST routes on a Flask App, according to Flask's design specification.
As per flask-restplus:
Flask-RESTPlus provides a way to use almost the same pattern as Flask’s blueprint. The main idea is to split your app into reusable namespaces.
from: http://flask-restplus.readthedocs.io/en/stable/scaling.html
namespace is from the Flask-RESTPlus and Blueprint is from flask to organize your app.
the namespaces modules (specific to Flask-RESTPlus) are reusable namespaces designed like you would do with Flask’s Blueprint.

Is flask instantiate required in each module of the app?

Hi I'm a Django developer and recently have started working on an existing flask app of the organization. I found the coder of the app has added a following line in each module/file of the app.
app = Flask(__name__)
From this line, I understood that, it instantiates the flask app. But if so, why that line is added in each module. He has used the variable app multiple times. But I doubt, this line should be at once only and later it should be imported.
So, the query is :
Is the flask instantiate required in each module of the app?
Note - The earlier coder has left the organisation and nobody is familiar with flask in my org.
No, the developer is misunderstanding how Flask works. You create one Flask() instance and import that in every module of the project that needs to have access to it.

Flask testing database application context

How can I structure my flask project such that my models can be aware of if TESTING is enabled (and thereby use a testing database), without having them deal with or have any knowledge of app context.
I'm developing this as an open source project so the source might shed some light on this: https://github.com/nficano/jotonce.com/blob/master/jotonce/messages/models.py#L33
I think you're running into this problem because you don't provide a way for users to specify configuration at run-time. Instead, managers.py grabs whatever settings that are specified in your settings.py file without consulting what settings the end-user might have specified.
Since you do have factory.py, you could potentially import current_app from Flask (assuming that your db functions are called within an app context) and use the settings value there. If that's an option for you, Flask has some good suggestions for configuration handling.
If you're running this outside of your application context, I don't think how factory.py is currently structured is going to work for you. You'll need to handle your own configuration manually.
You can take a look at https://github.com/Robpol86/Flask-Large-Application-Example/blob/master/pypi_portal/application.py for an example of a large flask project that uses the app factory with different configuration values well.
Good luck, and happy holidays!

Flask project structure

I want to know what is the best folder structure to follow when using Flask. I want to achieve the following:
/myproject
runserver.py
/app1
...
/app2
....
And of course I want to share my database configuration with all my apps. How can I achieve this? In the documentation they always talk of ONE app
PD: I'm comming from django.
PD2: I've also read this: http://flask.pocoo.org/docs/blueprints/ and this: http://flask.pocoo.org/docs/patterns/packages/#modules-and-resources
I found myself that best for me is to divide an application into blueprints. That is, split the whole thing not into separate WSGI applications but rather into these Flask-like objects which get registered in the Flask app. They provide possibilities to register errorhandlers, template context processors, etc. for views registered as endpoints of blueprint or for whole application - your choice.
Sharing of database connection object can be done through use of class with name "request_globals_class" (it must be declared in your application class which of course inherits Flask). When you provide an attribute for this class it is then accessible for a view (or whatever runs in request handling context) as an attribute of flask.g object.

Categories

Resources