Why does my view function 404? - python

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.

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()

Related

Why flask app run but browser is not loading the page?

I was developing a web application and it was woking fine, then I closed the project and re-opened it after a few hours, the project ran without error, but when I go to localhost:5000 it doesn't even load. I tried the same project in another laptop and it works perfectly.
I also tried a simple project in the problematic one like this. The program run, but the browser won't load the page, also here if I use my second laptop it works perfectly. What I should do to fix? Literally like 2 hours ago was working fine
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world(): # put application's code here
return 'Hello World!'
if __name__ == '__main__':
app.run()
My application code is:
from flask import Flask, render_template
from flask_login import current_user, LoginManager
from DaisPCTO.db import get_user_by_id
from flask_bootstrap import Bootstrap
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = "qwnfdopqwebnpqepfm"
Bootstrap(app)
login_manager = LoginManager()
login_manager.login_view = "auth_blueprint.login"
login_manager.init_app(app)
#app.route("/")
def home():
print("hello")
return render_template("page.html", user=current_user, roleProf = True if current_user.is_authenticated and current_user.hasRole("Professor") else False)
#login_manager.user_loader
def load_user(UserID):
return get_user_by_id(UserID)
from DaisPCTO.auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
from DaisPCTO.courses import courses as courses_blueprint
app.register_blueprint(courses_blueprint, url_prefix="/courses")
return app
i'm not putting all the blueprint, this is only the init.py file
In you application you don't run your app you just create a function
if __name__ == '__main__':
app = create_app()
app.run()
If you add this to your code you should be abble to see it in http://localhost:5000

How do I solve "flask.cli.NoAppException: Could not import filename"?

I have a simple app.
app.py:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return app.send_static_file('../../public/index.html')
if __name__== '__main__':
app.run(debug=True)
When I run it using flask run I get this error:
flask.cli.NoAppException: Could not import app
My FLASK_APP is set to {path-to-app}/app.py, and I am running the command from the folder that the file is in.
Can somebody help?
Your html file "index.html" needs to be in a folder called 'templates' which should be in the folder 'app.py' is also in.

NameError when splitting app and views code

I want to divide my code into two parts, the app initialization and the view definitions. I import my views and define my app, but I get NameError: name 'manager' is not defined. Why am I getting this error? How do I split up my code correctly?
manage.py:
from flask import Flask,render_template
from flask.ext.script import Manager
import viewports
manager = Flask(__name__)
if __name__=='__main__':
manager.run()
viewports.py
#manager.route('/')
def Home():
return render_template('Home.html', title='FrontPage')
You created a circular import: first you import viewports, which imports manager, which is only defined after you import viewports. You also didn't organize your code correctly, everything should be under one package. You also confused creating a Flask-Script manager with creating a Flask app. Also, flask.ext is deprecated, import directly from the package name.
my_project/
my_app/
__init__.py
views.py
manage.py
__init__.py:
from flask import Flask
from flask_script import Manager
app = Flask(__name__)
manager = Manager(app)
from my_app import views
views.py:
from my_app import app
#app.route('/')
def index():
return 'Hello, World!'
manage.py:
from my_app import manager
manager.run()

python flask-restful cannot get app access in resource class

Here is the sample code from flask-restful doc
from flask import Flask
from flask.ext import restful
app = Flask(__name__)
api = restful.Api(app)
class HelloWorld(restful.Resource):
def get(self):
return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
if __name__ == '__main__':
app.run(debug=True)
The HelloWorld class is in the same python file, say app.py, it works.
Now I am going to put the HelloWorld class to a separate class file, like following layout:
app
app/__init__.py # hold above code except the HelloWorld class.
app/resource
app/resource/__init__.py # empty
app/resource/HelloWorld.py # hold the above HelloWorld class.
The app/__init__.py contains :
from flask import Flask
from flask.ext import restful
from resource.HelloWorld import HelloWorld
app = Flask(__name__)
api = restful.Api(app)
api.add_resource(HelloWorld, '/')
if __name__ == '__main__':
app.run(debug=True)
And the HelloWorld.py is:
from flask.ext import restful
from app import app
class HelloWorld(restful.Resource):
def get(self):
return {'hello': 'world'}
Running the app would get exception:
ImportError: No module named app on HelloWorld.py
I do need to access app to read some information like app.config, how can i make it work?
You have a circular import; when the line from resource.HelloWorld import HelloWorld executes, app has not yet been assigned to, so in Helloworld.py the line from app import app fails.
Either import HelloWorld later:
from flask import Flask
from flask.ext import restful
app = Flask(__name__)
api = restful.Api(app)
from resource.HelloWorld import HelloWorld
api.add_resource(HelloWorld, '/')
if __name__ == '__main__':
app.run(debug=True)
or import just the app module in HelloWorld.py:
from flask.ext import restful
import app
class HelloWorld(restful.Resource):
def get(self):
return {'hello': 'world'}
and refer to app.app within a function or method called at a later time.

Why doesn't this cause circular import

I have a flask app.
app.py
app = Flask(__name__)
from views import *
if __name__=="__main__":
app.run()
views.py
from app import app
#app.route('/')
def home():
return "Homepage"
So, here app.py is importing everything form views.py and views need app which is defined in app.py. But still its not causing circular import. Why?
I run this application using:
python app.py
This looks similar to the Larger Applications document which Flask allows you to do when creating apps.
From the docs:
Circular Imports
Every Python programmer hates them, and yet we just added some: circular imports (That’s when two modules depend on each other. In this case views.py depends on __init__.py). Be advised that this is a bad idea in general but here it is actually fine. The reason for this is that we are not actually using the views in __init__.py and just ensuring the module is imported and we are doing that at the bottom of the file.
If we try to follow what the program does, it is something like that:
app = Flask(__name__) # OK
from views import * # Goes into views.py
from app import app # Looks into app.py, finds it, import it
# Defines home
#app.route('/')
def home():
return "Homepage"
# import home and app, overriding app in app.py
# But views.app is the same as app.app, so it is still
# the same object
# Run main
if __name__=="__main__":
app.run()
I bet it computes something like that. Since app is defined before being imported, it's ok.

Categories