0

I'm new to Flask. I was wondering if I can separate code to a different module in Flask (I know Blueprint can do that). So I tried to separate code like this:

Flask-Project
  -- app.py  
  -- login.py

and here is app.py code:

from flask import Flask

app = Flask(__name__)

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

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

and in login.py:

from app import app


@app.route('/login')
def login():
    return 'login'

when I run this Flask project,I try http://127.0.0.0:5000/login, it shows:

Not Found
The requested URL was not found on the server. 
If you entered the URL manually please check your spelling and try again.

Why does http://127.0.0.0:5000/login not work?

DocZerø
  • 8,037
  • 11
  • 38
  • 66
Adam
  • 9
  • 2
  • How are you running your app? It seems the code in login.py is never run, which is expected if you are just doing `python app.py` or similar, since nowhere in app.py is the code in login.py referenced. – Gino Mempin Mar 20 '22 at 09:42
  • I run the code in Pycharm, it run well while there only app.py ,but when i divide the code to a new login.py file,http://127.0.0.1:5000/login can't be reached. I don't konw how this happen. I use ```from app import app``` to make sure app.route can be invoked. I still don‘t understand why it doesn't work. – Adam Mar 20 '22 at 10:30
  • As I said, _the code in login.py is not run_. Yes you defined the route there, but nothing in app.py is loading/calling the code in login.py. Either use blueprints or see the answer in the link I shared: https://stackoverflow.com/a/59155127/2745495 – Gino Mempin Mar 20 '22 at 10:50
  • thanks for ur patient Gino,I think I need to learn more about how Flask works – Adam Mar 20 '22 at 12:40

1 Answers1

1

You need to load the login.py module so that the handler is registered. The following code should do it. Notice the placement of the import statement. It needs to be after the assignment of app.

from flask import Flask

app = Flask(__name__)

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

import login    # Register handlers for /login

if __name__ == '__main__':
    app.run()
md2perpe
  • 3,372
  • 2
  • 18
  • 22