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

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

Related

Logging Flask Application in Heroku

I am trying to find a way to structure my code such that I can view logs in the production server hosted on Heroku.
Every tutorial I found seems to do logging like this:
How to show stdout logs in Heroku using Flask?
However, I am using the application factory pattern which utilizes Blueprints. As such here are some sample:
main.py
from app import create_app
app = create_app()
if __name__ == "__main__":
app.run()
app/_ _ init _ _.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
...
db = SQLAlchemy()
...
def create_app():
app = Flask(__name__)
...
db.init_app(app)
from .routes.demo_blueprint import demo_blueprint
...
# Register the routes to the Flask object
app.register_blueprint(demo_blueprint)
...
app/routes/demo_blueprint.py
from app import db
...
demo_blueprint = Blueprint('demo_blueprint', __name__)
#demo_blueprint.route('/demo', methods=['GET'])
...
In order to perform logging at the blueprint level, I would need to import app from main.py. However, this would cause an import error since __init__.py imports the blueprint before app is created. I was wondering if there were any work arounds for this.
Turns out it was a simple fix. To access the application context in the Blueprint, just use current_app. Following the example:
How to show stdout logs in Heroku using Flask?
main.py
from app import create_app
app = create_app()
if __name__ == "__main__":
app.run()
app/_ _ init _ _.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
...
db = SQLAlchemy()
...
def create_app():
app = Flask(__name__)
if __name__ != '__main__':
gunicorn_logger = logging.getLogger('gunicorn.error')
app.logger.handlers = gunicorn_logger.handlers
app.logger.setLevel(gunicorn_logger.level)
...
db.init_app(app)
from .routes.demo_blueprint import demo_blueprint
...
# Register the routes to the Flask object
app.register_blueprint(demo_blueprint)
...
app/routes/demo_blueprint.py
from flask import ***current_user***
from app import db
...
demo_blueprint = Blueprint('demo_blueprint', __name__)
#demo_blueprint.route('/demo', methods=['GET'])
def demo():
current_app.logger.debug('debug message: %s', 'test')
...

flask automatic redirects when I start the server

I have a bare-minimum getting started with flask code. When I run server my terminal gets flooaded with 405 URL call(I am not making API calls explicitly from anywhere) No idea why it's doing that.
views.py
from app import app
from flask import jsonify
#app.route('/')
def index():
return jsonify({'message': 'Hello, World!'})
app.py
from flask import Flask
from flask_restful import Api
app = Flask(__name__)
api = Api(app)
import views, models, resources
api.add_resource(resources.UserRegistration, '/registration')
api.add_resource(resources.UserLogin, '/login')
api.add_resource(resources.UserLogoutAccess, '/logout/access')
api.add_resource(resources.UserLogoutRefresh, '/logout/refresh')
api.add_resource(resources.TokenRefresh, '/token/refresh')
api.add_resource(resources.AllUsers, '/users')
api.add_resource(resources.SecretResource, '/secret')
SS of the error

Run flask app with python instead of flask run

I'm trying to run my flask app with "python app.py" instead of "flask run" command.
My goal is to launch the app on cpanel server and just about every tutorial requires the applications to be called using the "python" method.
Here is my folder structure:
project
webapp
init.py
templates
static
auth.py
main.py
app.py <-------------- I want this to be called with python instead of flask run command outside the folder
Here is my init_.py file:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
# init SQLAlchemy so we can use it later in our models
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = '9OLWxND4o83j4iuopO'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
db.init_app(app)
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.init_app(app)
from .models import User
#login_manager.user_loader
def load_user(user_id):
# since the user_id is just the primary key of our user table, use it in the query for the user
return User.query.get(int(user_id))
# blueprint for auth routes in our app
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
# blueprint for non-auth parts of app
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
return app
And app.py is:
from webapp import app
I'm a newbie in flask, any help is appreciated
Insert the call to create_app at the end of init.py:
if __name__ == '__main__':
create_app().run(host='0.0.0.0', port=5000, debug=True)
The if statement avoid calling the app many times. It can only be called directly. Flask default host is 127.0.0.1 (localhost). Use 0.0.0.0 at production for better traffic monitoring. Default port is also 5000, so it's up to you to include. For better readability, you should explicit it.
Then call it
python webapp/init.py

How to integrate Angular 6 Single Page Application with FLASK architecture?

I'm using one of the Angular 6 template for frontend and using Python to do some heavier computation of images.
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__,static_url_path='')
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
#app.route('/')
def index():
return app.send_static_file('./index.html')
#app.route('/api/test')
def test():
socketio.emit('resp', {'data': 'got it!'});
return "done"
if _name_ == '__main__':
socketio.run(app)
I tried integrating angular 6 template with FLASK it worked for me but on refresh of the application or by changing state it throws me following error
"Page not found 404"
Please, help with integrating the Single Page Application.

Why does my view function 404?

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

Categories