Search code examples
pythonflaskroutesattributeerror

Flask router from other file


I'm now structuring Flask application like below.

myserver
- server.py
- myapp
-- urls.py
-- models.py
-- views.py
-- consts.py

And my codes are here.

server.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

# Flask App
application = Flask(__name__)

# SQLAlchemy
application.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:./local.db"
db = SQLAlchemy(application)

if __name__ == "__main__":
    application.run(debug=True)

urls.py

from server import application
from . import views

@application.route('/')
def version():
    return views.version()

But when i run server.py and open http://localhost:5000/ server says 404 Not Found.

So I searched on stackoverflow, I found some descriptions about Blueprint. And I make blueprint named app like app = Blueprint('app', __name__) and register it from server.py But I got AttributeError: module 'urls' has no attribute 'app' .

How can i define url routers in other file?


Solution

  • Here example with Blueprint. Structure of files:

    /project_folder
       server.py
       urls.py
       urls2.py
    

    server.py:

    from flask import Flask
    from urls import urls_blueprint
    from urls2 import urls2_blueprint
    
    
    app = Flask(__name__)
    # register routes from urls
    app.register_blueprint(urls_blueprint)
    # we can register routes with specific prefix
    app.register_blueprint(urls2_blueprint, url_prefix='/urls2')
    
    if __name__ == "__main__":
        app.run(debug=True)
    

    urls.py:

    from flask import Blueprint
    
    urls_blueprint = Blueprint('urls', __name__,)
    
    
    @urls_blueprint.route('/')
    def index():
        return 'urls index route'
    

    urls2.py:

    from flask import Blueprint
    urls2_blueprint = Blueprint('urls2', __name__,)
    
    
    @urls2_blueprint.route('/')
    def index():
        return 'urls2 index route'
    

    Run server and open http://localhost:5000/ and http://localhost:5000/urls2/.

    Hope this helps.