Forums

Problems with importing views - unable to detect undefined names

Hi, I'm having problems with basic views import. No matter how I try to import views ("import views", "from views import ", "import * from views") I get an error: "from views import " used. unable to detect undefined names "views.*". imported but unused.

On my website there's an error 404: Not Found. The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

What do I do wrong?

My code:

main.py

from flask import Flask

app = Flask(__name__)

if __name__ == '__main__':
    from views import *
    app.run()

views.py

from main import app

@app.route('/', methods=['GET'])
def info():
    return 'hello'

It works when I change main.py to:

from flask import Flask

app = Flask(__name__)

@app.route('/', methods=['GET'])
def info():
    return 'hello'

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

The first issue is simply the linter saying that if you import *, then it cannot work out if there are unused imports that you're not using. It's just a warning.

If you're getting a 404, it's because you haven't defined a view for the URL you're trying to access.

No, that was not the case

I figured that my import was wrong, that below works:

from flask import Flask

app = Flask(__name__)


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

import views   #(or: from views import *)

Yes -- Flask is only aware of views that you have imported, so it doesn't matter if you have a file called views.py somewhere in your file storage that defines a view for a URL; if you don't import it, then as far as Flask is concerned, you haven't defined it.