Is flask instantiate required in each module of the app? - python

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.

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.

Flask app serve as two different apps

I had worked with the Flask application which functions as an admin panel and an API. My admin panel includes login page and bunch of admin stuff in it. So I don't want to expose it to the internet.Admin panel should be only accessible from the intranet however my API should be accessible from the internet.
I have two machines.One is a local machine and other one will be hosted at the AWS. The problem is that the code will be same in the two machines however one will serve as an API and other will serve as an Admin panel.
My supervisor told me that I can use "Flask blueprints" to achieve what I am trying to do but I want to be sure before starting to implement.
Can Flask blueprints solve this problem or are there any other options?
(One thing comes to mind is to separate the API from the admin panel into two different Flask apps. Which is easy to do and solves everything. However I am unable to do that right now. )
Image of what I am trying to do
You can use before_app_request on your blueprint and check if your client ip starts with 192.168 or 10.0 or 172.16
from flask import abort
#blueprint_1.before_request
def check_network():
if not request.remote_addr.startswith("192.168") or ...:
abort(404)
Edit : According to Blueprint documentation before_app_request Such a function is executed before each request, even if outside of a blueprint.
use before_request instead (it will be executed before request on blueprint_1 Blueprint ... i edited my code ...

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!

How does flask's app pattern works?

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.

Saving entities in django-nonrel with google appengine

Update: I've noticed that entities are saved (and available at the Datastore Viewer) when I save them using views (and the create_object function). But when I use shell (manage.py shell) to create and save new entity it isn't commited to the storage (but still can be seen in Tes.objects.all()).
I started playing with the django-nonrel with google appengine and I am getting frustrated by thing as simple as saving Entities.
I've set up my environment as described in instruction. I managed to run sample application and it runs ok. I'd like to extend it so it saves my entity to the storage. To do so:
I added new django module with models.py:
from django.db import models
class Tes(models.Model):
name = models.CharField(max_length=150)
I created a script to save some data:
import os
import sys
sys.path.append("d:\\workspace\\project\\")
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from testmodule.models import Tes
t = Tes(name="test")
t.save()
tes = Tes.objects.all()
for t in tes:
print t.name
The script runs without errrors. When I run it few times one after another, it prints more and more "test" strings. But when I try running it after a minute break the Tes.objects.all() returns nothing. During that time the datastore file changes it size (but maybe that's just some kind of logs). When I look at the http://localhost:8000/_ah/admin/datastore I can select only AhAdminXrsfToken from select field.
Anyway, what am I missing? Where I can find some kind of logs which would tell me what's wrong?
This is a gotcha that causes a lot of confusion. From the djangoappengine docs:
Also, never run manage.py runserver together with other management
commands at the same time. The changes won't take effect. That's an
App Engine SDK limitation which might get fixed in a later release.
So you can't do manage.py runserver and manage.py shell at the same time. If you do, changes to the datastore in one will not be visible in the other. There's a lock on the local datastore enforced by the App Engine SDK. Make sure you have stopped the server before you start the shell.
Shoudn't it be t.put() if you are creating an entity rather than saving it? I use put() to create an entity and it works for me. And if you import django you may want to know that there are alternatives to django such as my choice GAE + Jinja2 + WTForms especially now that google.db.djangoforms is deprecated selecting a form framework for forms, a templating engine and perhaps a db framework and you do't have to import django which often results in forcing you to import much more than you need.
So my recommendation is to avoid import django... and instead use Jinja2 + WTForms. If you really want django on app engine then you might want to check in the project www.allbuttonspressed.com that enables all django for google app engine but be certain that you need this much django when I suspect all we need is a template engine and a form framework and we can do without django.

Categories

Resources