Flask Web Development: Developing Web Applications with Python

Category: Programming
Author: Miguel Grinberg
4.5
This Month Stack Overflow 1

Comments

by anonymous   2019-01-13

I think you should really consider reorganizing your app structure. The way you are doing it will lead to circular imports which is probably why you have your views import after your app creation. I would suggest moving your app factory into its own file since you will reuse it in your tests.

my_app/factory.py

def create_app():
    # init extensions
    # init blueprints
    return app

Then while your app is small simply keep the views in app.py As your app gets larger consider implementing the blueprint design pattern -> docs

my_app/app.py

from factory import create_app

app = create_app()

@app.route('/')
def index():
    return 'hello'

if __name__ == '__main__':
    app.run()

In your tests

test_example.py

from factory import create_app

@py.fixture
def client():
    return create_app().test_client()

def test_route(client):
    response = client.get('/')
    assert response.json() == 'hello', 'Route should return "hello"'

Miguel Grinberg has a really great blog on Flask he's the author of Flask Web Development which is an excellent resource. Looks like he is in the process of rewriting his tutorial on flask.

Blueprints example

my_app/factory.py

def create_app():
    app = Flask(__name__)
    from main import main
    app.register_blueprint(main)

    return app

my_app/main.py

from flask import Blueprint

main = Blueprint('main', __name__)

@main.route('/')
def index():
    return "hello"

my_app/app.py

from factory import create_app

app = create_app()

if __name__ == '__main__':
    app.run()

Hope that helps