3
flask-app 
 |_  app.py
 |_  views.py
 |_  models.py
 |_  resources.py

~ app.py

from flask import Flask

app = Flask(__name__)

import views, models, resources


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

~ views.py

from app import app

@app.route('/')
def index():
    home = "<h1>Welcome</h1>"
    return home

For some reason I get a 404 not found error when I try to access localhost:5000.

Read this answer (Can't route to "/login" with flask?) but I doubt it has anything to do with trailing slashes.

When I paste the route back into app.py it starts working again. Why is this? How can I fix my flask app? Would appreciate any help.

ebd
  • 157
  • 4
  • 13

1 Answers1

5

You're having issues with circular imports

You should use Blueprints

Working example for you:


app.py

from flask import Flask
import views, models, resources

app = Flask(__name__)
app.register_blueprint(views.simple_page)    

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

views.py

from flask import Blueprint

simple_page = Blueprint('simple_page', __name__)

@simple_page.route('/')
def index():
    home = "<h1>Welcome</h1>"
    return home

This is also much a nicer pattern because now all your imports are at the top as they should be

jamylak
  • 128,818
  • 30
  • 231
  • 230
  • 1
    Thank you, I have refactored all my code to use Blueprints (http://exploreflask.com/en/latest/blueprints.html, http://flask.pocoo.org/docs/0.12/blueprints/). You are right, much nicer pattern, thank you for your help. – ebd Feb 10 '18 at 05:17