flask : how to architect the project with multiple apps? - python

Lets say I want to build a project Facebook
I need a project structure like
facebook/
__init__.py
feed/
__init__.py
models.py
business.py
views.py
chat/
__init__.py
models.py
business.py
views.py
games/
__init__.py
models.py
business.py
views.py
common/
common.py
runserver.py
How can I structure this well so that when I run
python facebook/runserver.py
It loads views from all my apps internally?
I want to keep this structure because extending the project further is more natural way
I am trying to follow their advice, but don't really understand where I need to write
from flask import Flask
app = Flask(__name__)
and how to import all views from all apps at one place, please help
If lets say I write the above code in facebook/__init__.py, then how in facebook/feed/views.py, I can do
from facebook import app

Use blueprints. Each one of your sub-applications should be a blueprint, and you load every one of them inside your main init file.
Answering your second question
from flask import Flask
app = Flask(__name__)
You should put this into facebook/__init__.py
BTW, my runserver.py and settings.py always resides one level under facebook/.
Like this:
facebook/
__init__.py
feed/
__init__.py
models.py
business.py
views.py
chat/
__init__.py
models.py
business.py
views.py
games/
__init__.py
models.py
business.py
views.py
common/
common.py
runserver.py
settings.py
Content of runserver.py:
from facebook import app
app.run()
I suppose the content of settings.py should not be explained.
Content of facebook/__init__.py:
from flask import Flask
app = Flask(__name__)
app.config.from_object('settings')
from blog.views import blog #blog is blueprint, I prefer to init them inside views.py file
app.register_blueprint(blog,url_prefix="/blog")

I have tried blueprints and came up with a solution which works for me, let me know if you have other ideas.
Project Structure
facebook/
runserver.py
feed/
__init__.py
views.py
chat/
__init__.py
views.py
Code
# create blueprint in feed/__init__.py
from flask import Blueprint
feed = Blueprint('feed', __name__)
import views
# create blueprint in chat/__init__.py
from flask import Blueprint
chat = Blueprint('chat', __name__)
import views
# add views (endpoints) in feed/views.py
from . import feed
#feed.route('/feed')
def feed():
return 'feed'
# add views (endpoints) in chat/views.py
from . import chat
#chat.route('/chat')
def chat():
return 'chat'
# register blueprint and start flask app
from flask import Flask
from feed import feed
from chat import chat
app = Flask(__name__)
app.register_blueprint(feed)
app.register_blueprint(chat)
app.run(debug=True)
In Action
* Running on http://127.0.0.1:5000/
# Hit Urls
http://127.0.0.1:5000/feed # output feed
http://127.0.0.1:5000/chat # output chat

Related

Why is flask rendering the wrong template [duplicate]

I have a Flask app with blueprints. Each blueprint provides some templates. When I try to render the index.html template from the second blueprint, the first blueprint's template is rendered instead. Why is blueprint2 overriding blueprint1's templates? How can I render each blueprint's templates?
app/
__init__.py
blueprint1/
__init__.py
views.py
templates/
index.html
blueprint2/
__init__.py
views.py
templates/
index.html
blueprint2/__init__.py:
from flask import Blueprint
bp1 = Blueprint('bp1', __name__, template_folder='templates', url_prefix='/bp1')
from . import views
blueprint2/views.py:
from flask import render_template
from . import bp1
#bp1.route('/')
def index():
return render_template('index.html')
app/__init__.py:
from flask import Flask
from blueprint1 import bp1
from blueprint2 import bp2
application = Flask(__name__)
application.register_blueprint(bp1)
application.register_blueprint(bp2)
If I change the order the blueprints are registered, then blueprint2's templates override blueprint1's.
application.register_blueprint(bp2)
application.register_blueprint(bp1)
This is working exactly as intended, although not as you expect.
Defining a template folder for a blueprint only adds the folder to the template search path. It does not mean that a call to render_template from a blueprint's view will only check that folder.
Templates are looked up first at the application level, then in the order blueprints were registered. This is so that an extension can provide templates that can be overridden by an application.
The solution is to use separate folders within the template folder for templates related to specific blueprints. It's still possible to override them, but much harder to do so accidentally.
app/
blueprint1/
templates/
blueprint1/
index.html
blueprint2/
templates/
blueprint2/
index.html
Point each blueprint at its templates folder.
bp = Blueprint('bp1', __name__, template_folder='templates')
When rendering, point at the specific template under the templates folder.
render_template('blueprint1/index.html')
See Flask issue #1361 for more discussion.
I vaguely remember having trouble with something like this early on. You haven't posted all of your code, but I have four suggestions based on what you've written. Try the first, test it, and then if it still is not working, try the next ones, but independently test them to see if they work:
First, I cant't see your views.py file, so be sure you're importing the appropriate blueprint in your views.py files:
from . import bp1 # in blueprint1/views.py
from . import bp2 # in blueprint2/views.py
Second, you may need to fix the relative import statements in __init__.py as follows (note the period preceding the subfolders):
from .blueprint1 import blueprint1 as bp1
from .blueprint2 import blueprint2 as bp2
Third, since you're hardcoding the path to your templates in your render_template function, try removing template_folder='templates' from your blueprint definition.
Fourth, it looks like you named the url_prefix for your blueprint as "/bp1" when you registered it. Therefore, if the hard coded link to your file system still does not work:
render_template('blueprint1/index.html')
then also try this and see what happens:
render_template('bp1/index.html')
Again, I can't see your full code, but I hope this helps.

How to add views to a blueprint in separate files

I have a huge application that was getting hard to update its views. To 'fix' this, I had separate the views into a few files, using blueprints. The problem is that the blueprints are also getting very big, because the long documentation that each view has and the different verifications that each view requires.
I had tried to do an import like this:
Where I have a main file that contains the Flask application (which imports the blueprint), a file that contains the blueprint and a file the imports the blueprint and configure the views in it. The problem is that with this approach the views are not rendered, because flow reasons.
The main file, in the root of a folder:
from flask import Flask
from source import test
application = Flask(__name__)
application.register_blueprint(test)
application.run()
The blueprint file, inside a subfolder in the root folder:
from flask import Blueprint
test = Blueprint('test', __name__)
The view file, inside the same subfolder as the blueprint file:
from .test import test
#test.route('/home', methods=['GET', 'POST'])
def home():
return 'home'
I had also tried to add the blueprint decorator to a declared function, this way the views are add to the blueprint in the blueprint file, but I don't think this is a good approach or a scalable approach - and it didn't work ^ - ^.
I expect to create a blueprint in a file, import the blueprint in other files and add views to the blueprint and then import the blueprint and add it to the Flask application.
You need to import the views content in blueprint file.
I have created the scenario and able to get the view. Additionally, I have updated the naming convention.
Folder structure:
.
├── app.py
└── blueprints
├── example_blueprint.py
├── example_views.py
└── __init__.py
app.py:
from flask import Flask
from blueprints.example_blueprint import bp
app = Flask(__name__)
app.register_blueprint(bp)
blueprints/example_blueprint.py:
from flask import Blueprint
bp = Blueprint('bp', __name__,
template_folder='templates')
from .example_views import *
blueprints/example_views.py:
from .example_blueprint import bp
#bp.route('/home', methods=['GET', 'POST'])
def home():
return 'home'
blueprints/__init__.py: Blank file
Output:
Running the application:
export FLASK_APP=app.py
export FLASK_ENV=development
flask run
requirements.txt:
Click==7.0
Flask==1.0.3
itsdangerous==1.1.0
Jinja2==2.10.1
MarkupSafe==1.1.1
pkg-resources==0.0.0
Werkzeug==0.15.4
Reference:
Flask documentation on Blueprints
In root folder change main file:
from flask import Flask
from source.listener import test
application = Flask(__name__)
application.register_blueprint(test)
application.run()
The blueprint file, inside a subfolder in the root folder:
listener.py
from flask import Blueprint
from source.view import home
test = Blueprint('test', __name__)
test.add_url_rule('/home', view_func=home,methods=['GET', 'POST'])
The view file, inside the same subfolder as the blueprint file:
from flask import request
def home():
if request.method == 'POST':
user = request.form['name']
return "Welcome "+user
else:
return 'home'
Get Request O/P:
Home
Post Request O/P:
Welcome username
The view module isn't discovered since only the Blueprint object is imported.
From the organization of your Blueprint and particularly the import that you have shared in your main file, I can deduct the existence of an __init__.py in the blueprint folder that exports the blueprint object.
Importing the views in that file should have the app discover the views registered in the blueprint.
i.e.
blueprint/__init__.py:
from .test import test
from . import views

How to import blueprints with the same name as the file they are in?

Background
I'm trying to set up a blueprint whose name matches the filename it resides in, so that when I reference it in my app.py I know where the blueprint comes from. This should be possible because the example on exploreflask uses the same pattern. Still, I cannot figure out how to make this work with my structure.
File structure
├── app.py
├── frontend
   ├── __init__.py
   └── views
   ├── home.py
   └── __init__.py
Example
frontend/views/home.py
from flask import Blueprint, render_template
home = Blueprint('home', __name__)
home1 = Blueprint('home1', __name__)
frontend/views/__init__.py
from .home import home
from .home import home1
app.py
from flask import Flask
from frontend.views import home
from frontend.views import home1
print (type(home)) --> <class 'function'>
print (type(home1)) --> <class 'flask.blueprints.Blueprint'>
As home1 registers correctly as a Blueprint but home does not I suspect that
there is a name collision but I don't know how to resolve it despite looking into
this excellent article on importing conventions.
As a result, when I try to register my blueprints with the app
this will work:
app.register_blueprint(home1, url_prefix='/home1') --> Fine
but this won't:
app.register_blueprint(home, url_prefix='/home')
--> AttributeError: 'function' object has no attribute 'name'
Why not just go along with using home1?
I want to understand how the collision can be resolved
I want to be able to use route names that are the same as the filename they are in like so:
frontend/views/home.py
from flask import Blueprint, render_template
home = Blueprint('home', __name__)
#home.route('/')
def home():
pass
I think your views/__init__.py file is causing this issue. It's making python assume your home.py file is a module to be imported. I believe the line from frontend.views import home is trying to import the home.py file rather than your intended home.home Blueprint.
Here's a working example:
/app.py
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run()
/app/__init__.py
from flask import Flask
def create_app():
app = Flask(__name__)
from .bp import bp
app.register_blueprint(bp)
return app
/app/bp/__init__.py
from flask import Blueprint
bp = Blueprint('bp', __name__, template_folder='templates')
from . import views
/app/bp/views.py
from app.bp import bp
#bp.route('/helloworld')
def helloworld():
return "hello world"
Try to use Capital letters in the Blueprint Module.
also you can use the url_prefix in the module.
Home = Blueprint("Home", __name__, url_prefix="/home")
#Home.route("/")
def home():
pass

Flask blueprints cannot import module

I'm learning Blueprints for Flask, but I am having trouble with importing the correct modules. This is my setup:
Folder structure:
- app.py
templates/
nomad/
- __init__.py
- nomad.py
app.py
from flask import Flask
from nomad.nomad import nblueprint
app = Flask(__name__)
app.register_blueprint(nblueprint)
nomad.py
from flask import render_template, Blueprint, abort
from app import app
nblueprint = Blueprint('nblueprint', __name__, template_folder='templates')
# Routes for this blueprint
#app.route ....
__init__.py is empty
The error I'm getting: ImportError: cannot import name nblueprint. I know my import statement is probably wrong, but what should it be and why?
EDIT:
If I remove from app import app, then I can successfully import nblueprint in app.py. But I need app in nomad.py because it needs to handle routes. Why is that line causing issues with importing, and how would I get around this?
Blueprints is for define application route so you don't need to use app instance and blueprint in same place for route defination.
#nomad.py
#nblueprint.route('/')
You are getting error because while you register the blueprint at the same time you use app instance. So as you said when you remove the from app ... it solve the problem.
The recommend way is define your view for that blueprint in blueprint package in your example nomad package, it should be like this:
...
nomad/
__init__.py
views.py
#nomad/__init__.py
nblueprint = Blueprint(...)
#nomad/views.py
from . import nblueprint
#nblueprint.route('/')
...

My hello world flask program is not running?

I'm a beginner in Flask, And i'm trying to create a simple hello world program but it's giving me errors on everytime with Undefined variable from import: run.
Here is my directory looks like:
/MyApplicationName:
/app
/__init__.py
/views.py
/run.py
My __init__.py is:
from flask import Flask
app = Flask(__name__)
import views
Here is my views.py:
from app import app
#app.route("/")
#app.route("/index")
def main():
return "Hello Flask!!"
Here is my last one run.py:
from app import app
if __name__ == "__main__":
app.run(debug=True)
Every time it gives me this error:
Undefined variable from import: run.
HELP WOULD BE APPRECIATED
Move:
from flask import Flask
app = Flask(__name__)
to views.py. Then make __init__.py:
from views import app
You have a circular import, but I'm not exactly sure as to why it's throwing the error it's throwing.
Have a look at flask-script, anyway evaluate to use a factory, something like create_app() that returns an app object.
It seems to be the common practice when using flask:
def create_app():
app = Flask(
'portal', static_folder='static/build', static_url_path='/static'
)
init_config(app)
init_login(app)
init_csrf(app)
app.register_blueprint(views)
return app
Without changing a single line of what you've coded, just move run.py out of the app directory.
Your project directory should look then like this:
└── MyApplication
├── __init__.py
├── app
│   ├── __init__.py
│   ├── views.py
└── run.py
Happy coding,
J.

Categories