flask : how to architect the project with multiple apps?

Issue

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

Solution

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

Answered By – daydreamer

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published