flask : how to architect the project with multiple apps?
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