0

I am trying to figure out the files structure of a flask app. I've used flask-dotenv and the FLASK_APP is main.py

myapp/.flaskenv - specifies the FLASK_APP myapp/main.py myapp/app/init.py - has the create_app() function. This imports a db as well from db.py myapp/app/db.py - the database related functions

I'd like to have all routes in a separate routes.py file (rather than within the create_app() method. myapp/app/routes.py

I'd appreciate some help in finding how is it that I can link this routes.py in.

Thanks in advance

Rob T
  • 74
  • 1
  • 3

1 Answers1

2

You can use blueprint to organize and register your routes.

Essentially, you can have a folder structure like this:

app/ <-- your entire application folder
    auth/                               <-- blueprint package for /auth route
        __init__.py                     <-- blueprint creation
        routes.py                       <-- authentication routes
    profile/
        __init__.py                     <-- blueprint package for /profile route
        routes.py                       <-- profile routes
    __init__.py                         <-- ceate_app and blueprint registration

Under your routes package, for example in auth folder:

# app/auth/__init__.py
# this is initialize auth blueprint
from flask import Blueprint
bp = Blueprint('auth',__name__,)
from app.auth import routes

Then you can put all your authentication routes in auth/routes.py, but instead of using app.route, you need to use bp.route like this:

# app/auth/routes.py
# this is where you can put all your authentication routes
from app.auth import bp
# notice here the route '/login' is actually prefixed with 'auth'
# because in the following code I added "url_prefix='/auth' " in the create_app() factory.
# the full routes will be 'auth/login' on your website.
@bp.route('/login', methods=['GET','POST'])
def login():
    ....your login code...

Then in your __init__.py you can do this:

# app/__init__.py
from app.auth import bp as auth_bp
from app.profile import bp as profile_bp
    
def create_app(config):
    app = Flask(__name__)
    app.config.from_object(config)
    app.register_blueprint(auth_bp,url_prefix='/auth')
    app.register_blueprint(profile_bp,url_prefix='/profile')

This way all routes to yourdomain.com/auth/... will be in app/auth/routes.py ; all routes to yourdomain.com/profile/... will be in your app/profile/routes.py.

Check this wonderful tutorial about Flask for more details:

Flask mega tutorial by Miguel Grinberg

This specific part is about how you can better organize your application structure.

fusion
  • 1,327
  • 6
  • 12
  • I see, thanks. Well actually I was trying to avoid using blueprints. This would be just a very simple test app on my own localhost. Is it possible without blueprint? – Rob T Aug 31 '20 at 23:40