5

Directory Structure:

__init__:

from flask import flask 

app = Flask(__name__)


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

Views:

from app import app

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

I hope someone can explain what I am doing wrong here - I guess I'm not understanding how to properly import app. This results in a 404. However when views is moved back to __init__ everything works properly.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Shilo
  • 313
  • 3
  • 16

1 Answers1

6

You need to explicitly import your views module in your __init__:

from flask import flask 

app = Flask(__name__)
from . import views    

Without importing the module, the view registrations are never made.

Do keep the script portion outside of your package. Add a separate file in Final_app (so outside the app directory) that runs your development server; say run.py:

def main():
    from app import app
    app.run()

if __name__ == '__main__'
    main()
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Is my directory structure correct or am i missing something else? Im unable to import views, No module named views – Shilo Jul 12 '15 at 00:59
  • @Chris_S: your package setup is indeed convoluted as you put a script in the `__init__` file. How are you currently running the server, with `python app/__init__.py`? – Martijn Pieters Jul 12 '15 at 01:02
  • Yes, should the contents of init be in their own file? – Shilo Jul 12 '15 at 01:03
  • @Chris_S: See [Python3: Attempted relative import in non-package](https://stackoverflow.com/q/20582335); you really should avoid putting scripts inside packages. Then use `from . import views` in `__init__`. – Martijn Pieters Jul 12 '15 at 01:12
  • When I attempted `from . import views' i was greeted with: `SystemError: Parent module '' not loaded, cannot perform relative import' When I moved everything from `__init__` to its own file and tried `import views` that resulted in `no module named views` I think something else is going on here. – Shilo Jul 12 '15 at 01:24
  • @Chris_S: when you use `__init__.py` as the script there is indeed no parent package, which is why I advocated creating a separate `run.py` script *outside* the `app` package. – Martijn Pieters Jul 12 '15 at 01:27
  • Oh I missed the edited answer. Everything is working as it should now. Thank you for the help – Shilo Jul 12 '15 at 01:32