from flask import flask
app = Flask(__name__)
#app.route('/'):
def index():
return 'hrllo'
I keep getting
Serving Flask app 'application.py' (lazy loading)
Environment: development
Debug mode: on
Usage: flask run [OPTIONS]
Try 'flask run --help' for help.
Error: While importing 'application', an ImportError was raised.
Try:
from flask import Flask #changed "flask" to "Flask"
app = Flask(__name__)
#app.route('/') #removed ":"
def index():
return 'hello'
app.run() #added this line to run your application
from flask import Flask, correction in your first line.
Remove the colon at the end of the line marking the route.
Also, you should do app.run() at the end of the code snippet.
Related
Usecase: I have a python flask app that runs background_function() before serving any requests on routes.
When I execute the flask app, I receive the error - RuntimeError: Working outside of application context. I receive the error since I try to get the application context before any request is served.
What is the best pythonic way to execute the background_function() in this example?
from flask import Flask
from download import Download
app = Flask(__name__)
app.config.from_pyfile('config.py')
# run backgroung function
Download.background_function()
#app.route('/')
def index():
return 'Welcome!'
if __name__ == '__main__':
app.run()
The config file
FILE_LOCATION = os.environ['FILE_LOCATION'] # "file/path/on/server"
# Many other variables are present in this file
The download file
from flask import current_app as app
class Download:
#staticmethod
def background_function():
file_path = app.config["FILE_LOCATION"]
# code to download file from server to local
return
Try this:
from flask import Flask
from download import Download
app = Flask(__name__)
#app.route('/')
def index():
return 'Welcome!'
if __name__ == '__main__':
Download.background_function()
app.run()
the download file
from flask import current_app as app
class Download:
#staticmethod
def background_function():
print("testing")
given output:
testing
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
As you can see, the function runs first and prints testing and then runs the application.
trying to host my flask app (run.py) on PythonAnywhere. Have my virtualenv setup and all of my modules imported via pip. The flask app is stored at this location:
/home/goldsilvermonitor/GSM/run.py
Set up my WSGI file and it keeps giving my the error:
TypeError: 'module' object is not callable
My flask file look like this: (run.py)
from flask import Flask, flash, redirect, render_template, request, session, abort, url_for
app = Flask(__name__)
# ./Home Script:
#app.route("/")
#app.route("/index")
def index():
return render_template('index.html')
# ./Disclaimer Page:
#app.route("/disclaimer")
def disclaimer():
return render_template('disclaimer.html')
# ./data.xml:
app.route("/dataxml")
def dataxml():
return render_template('data.xml')
# ./404 Page
#app.errorhandler(404)
def page_not_found(e):
# 404 status set explicitly
return render_template('404.html'), 404
# FLask Debug Script:s
if __name__ == "__main__":
app.run(host="0.0.0.0", port='5000', debug=True)
And my WSGI file looks like this:
# +++++++++++ FLASK +++++++++++
# Flask works like any other WSGI-compatible framework, we just need
# to import the application. Often Flask apps are called "app" so we
# may need to rename it during the import:
#
#
import sys
#
## The "/home/goldsilvermonitor" below specifies your home
## directory -- the rest should be the directory you uploaded your Flask
## code to underneath the home directory. So if you just ran
## "git clone git#github.com/myusername/myproject.git"
## ...or uploaded files to the directory "myproject", then you should
## specify "/home/goldsilvermonitor/myproject"
path = '/home/goldsilvermonitor/GSM'
if path not in sys.path:
sys.path.append(path)
#
import run as application # noqa
#
# NB -- many Flask guides suggest you use a file called run.py; that's
# not necessary on PythonAnywhere. And you should make sure your code
# does *not* invoke the flask development server with app.run(), as it
# will prevent your wsgi file from working.
I have no idea what is causing this error. Have tried reuploading the files, redoing the WSGI config. But to no avail. If someone could help me then that would be great! Also should I remove the debug=true from the flask file before I go live?
You're trying to import a module (the file run.py) and then use it as an application; the application is the app object in that file, so in the WSGI file you should replace this:
import run as application # noqa
...with this:
from run import app as application # noqa
I have the following app which when I run using
flask run
seems to execute without error but when I perform python app.py gives me the following error:
➣ $ python app.py
Traceback (most recent call last):
File "app.py", line 14, in <module>
app.secret_key = os.environ['SECRET_KEY']
File "/Users/pkaramol/Workspace/second_flask/venv/bin/../lib/python3.7/os.py", line 678, in __getitem__
raise KeyError(key) from None
KeyError: 'SECRET_KEY'
#!/usr/bin/env python
import os
from flask import Flask
from flask_jwt import JWT, jwt_required
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
import settings
from resources.item import Item, ItemList
app = Flask(__name__)
api = Api(app)
app.config.from_pyfile('settings.py')
app.secret_key = os.environ['SECRET_KEY']
db = SQLAlchemy(app)
if __name__ == "__main__":
print("Starting flask app...")
print(os.end['SECRET_KEY'])
db.create_all()
api.add_resource(Item, '/item/<string:name>')
api.add_resource(ItemList, '/items')
What is the difference in the two ways of running the flask app and why in the second case the environment is not rendered appropriately?
I am using python-dotenv to inject env vars from .env file
btw in the first case where the app starts without errors, I do not see the print statement I use for debug.
and if in the case of flask run the code below if __name__ == '__main__' is not called, how will I initialise my db by calling db.create_all()?
Replace app.secret_key assignment with arbitrary string.
i am a noob in python programming. Recently i was learning Flask framework for web development. After completed some basic flask doc demo i was trying to separate my 1 page simple hello world into mvc.
As in the way this is my project structure
Main folder
---> application [folder]
--> __init__.py
--> route.py
--->run.py
At run.py i have this code :
import application
At the application's _init_.py i have this code :
from flask import Flask
app = Flask(__name__)
import route
And at route.py i have this code :
from flask import Flask
from application import app
#app.route('/')
def index():
return "hello world"
app.run(debug=True,host='0.0.0.0')
Now when a go to my terminal and start server this happens
(venv)nihan#rko:~/apps/blog$ python run.py
* Running on http://0.0.0.0:5000/
* Restarting with reloader
^C^C127.0.0.1 - - [02/Sep/2013 00:25:45] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [02/Sep/2013 00:25:45] "GET / HTTP/1.1" 200 -
Now you can see this script runs correctly but it does not response to and request until i shut the process.
My question is why server does not sends anything until i press CTRL + C ? And how to solve this problem?
You should also avoid circular imports, for example by using blueprints.
run.py
from application import app
app.run(debug=True, host='0.0.0.0')
application/__init__.py
from flask import Flask
from route import mod
app = Flask(__name__)
app.register_blueprint(mod, url_prefix='/')
application/route.py
from flask import Flask, Blueprint
mod = Blueprint('app', __name__)
#mod.route('/')
def index():
return "hello world"
The quick fix of that is
In route.py :
from flask import Flask
from application import app
#app.route('/')
def index():
return "hello world"
app.run(
host='0.0.0.0',
debug=True
)
You should move the app.run() call to run.py. This should happen after everything related to the app is imported, it's not a good idea to have it inside the app itself.
I call app.run(debug=True) in my flask file.
and I have it deployed with uWSGI and nginx (I followed these instructions)
uwsgi -s /tmp/uwsgi.sock -w flask_file_name:app -H /path/to/virtual/env --chmod-socket 666
But when I get an error, I don't get any debug information in the browser or in the uWSGI log.
Any ideas?
flask_file_name.py:
from flask import Flask, make_response, Response, jsonify
import json
app = Flask(__name__)
app.debug = True
#app.route("/")
def hello():
return "Hello World!"
if __name__ == '__main__':
app.run()
This question is old, but I'll post this for future reference...
If you want to get the werkzeug error page to work with uwsgi, try using werkzeug's DebuggedApplication middleware:
from werkzeug.debug import DebuggedApplication
app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
That should do the trick but DO NOT FORGET to do this ONLY in development environments.
According to the Flask mailing list you cannot use Flask's debug option with uWSGI, because it's not to be used in a forking environment.
You see 502 because flask/werkzeug do not send any data to the webserver,
so nginx will returns a 502.
You can emulate the debugger using --catch-exceptions option in uWSGI
(but please do not do it in production)
So, the reason you're seeing 502s will be because of that. The fix would be to add --catch-exceptions to uWSGI on execution.
The problem is uwsgi does not call app.run(). It calls app(). So instead you can do this:
from flask import Flask
app = Flask(__name__)
app.debug = True
For me it only worked after I combined the two answers above like this:
from flask import Flask
app = Flask(__name__)
from werkzeug.debug import DebuggedApplication
app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
app.debug = True