S
S
Sergey2020-05-15 18:00:11
Flask
Sergey, 2020-05-15 18:00:11

How can I easily include route in flask?

Good afternoon.
It is necessary to put the routes in a separate file in the flask project.
But there is no way to do it.
I made a simple example for clarity:

app.py

from flask import Flask
app = Flask(__name__)
import route
if __name__ == '__main__':
    app.run()

route.py
from app import app
@app.route('/')
def hello_world():
    return 'Hello World!'


Everything starts up fine:
python app.py
but when I go to the page:
127.0.0.1:5000
it says:
Not Found

And it seems that the task is simple, but I can’t solve it in any way.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mumische, 2020-05-19
@mumische

Flask uses Blueprints for this. The code should look something like this:
app.py

from flask import Flask
from route import app_route

app = Flask(__name__)
app.register_blueprint(app_route)

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

route.py
from flask import Blueprint

app_route = Blueprint('route', __name__)

@app_route.route('/')
def index():
  return 'Hello world!'

S
Sergey Gornostaev, 2020-05-15
@sergey-gornostaev

You have a cyclic import, in Python this is not possible. Read the documentation about code organization in Flask projects, it has everything you need.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question