I would like to know how can I change the name of the Flask WSGI App during the development stage.
Using the Flask Mega-Tutorial as reference, I was able to successfully setup a "Hello World" app.
Digressions from the tutorial:
Use pipenv as my Python virtual environment manager (instead of venv)
Name of the app is astronomer.py.
Now, I want to build on top of the existing app and customize the code to my requirements; starting with the app name that I have defined in the .flaskenv file as FLASK_APP env var.
Accordingly, I have updated the name of the root level Python script from astronomer.py (in the tutorial) to galielo.py (for my use). After changing the corresponding value of FLASK_APP and restarting the flask server via $ pipenv run flask run, the app crashes with the following error:
$ pipenv run flask run [12:29:33]
* Serving Flask app "astronomer.py" (lazy loading)
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 302-012-958
127.0.0.1 - - [09/Oct/2019 12:29:57] "GET / HTTP/1.1" 500 -
Traceback (most recent call last):
File "/Users/kshitij10496/.local/share/virtualenvs/galileo-iQPdbs28/lib/python3.7/site-packages/flask/cli.py", line 240, in locate_app
__import__(module_name)
ModuleNotFoundError: No module named 'astronomer'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/kshitij10496/.local/share/virtualenvs/galileo-iQPdbs28/lib/python3.7/site-packages/flask/cli.py", line 338, in __call__
self._flush_bg_loading_exception()
File "/Users/kshitij10496/.local/share/virtualenvs/galileo-iQPdbs28/lib/python3.7/site-packages/flask/cli.py", line 326, in _flush_bg_loading_exception
reraise(*exc_info)
File "/Users/kshitij10496/.local/share/virtualenvs/galileo-iQPdbs28/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/Users/kshitij10496/.local/share/virtualenvs/galileo-iQPdbs28/lib/python3.7/site-packages/flask/cli.py", line 314, in _load_app
self._load_unlocked()
File "/Users/kshitij10496/.local/share/virtualenvs/galileo-iQPdbs28/lib/python3.7/site-packages/flask/cli.py", line 330, in _load_unlocked
self._app = rv = self.loader()
File "/Users/kshitij10496/.local/share/virtualenvs/galileo-iQPdbs28/lib/python3.7/site-packages/flask/cli.py", line 388, in load_app
app = locate_app(self, import_name, name)
File "/Users/kshitij10496/.local/share/virtualenvs/galileo-iQPdbs28/lib/python3.7/site-packages/flask/cli.py", line 250, in locate_app
raise NoAppException('Could not import "{name}".'.format(name=module_name))
flask.cli.NoAppException: Could not import "astronomer".
Debugging
After logging into the virtual env and checking for the value of the env var FLASK_APP, I get the old value of astronomer.py. This explains why the application is not starting. However, I'm not able to understand why this is happening?
I even tried using "eager-loading" the app using: $ pipenv run flask run --eager-loading
Still, the app does not start with the same error message ofcourse.
I was able to solve this manually by unsetting the env var FLASK_APP from within the virtual env and restarting the flask server. I'm curious to know about why the app is not loading the file .flaskenv at initialization and if there is an automated way to do this?
With Pipenv, I think things are a little bit different when it comes to environment variables. As per the documentation, there is a builtin mechanism for loading a .env file:
If a .env file is present in your project, $ pipenv shell and $ pipenv run will automatically load it, for you
So I guess you should rename your file from .flaskenv to .env and then safely remove the python-dotenv dependency.
Related
I have a python-flask hangman game, that I tried to wrap into a single executable file using pyinstaller with the following command line:
pyinstaller -w -F --add-data "templates:templates" --add-data "static:static" hangman.py
It seemed to work fine, and created build, dist, as well as the .spec file However, when I try to run the executable, I get the following error:
flask_sqlalchemy/__init__.py:800: UserWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True to suppress this warning.
* Serving Flask app "hangman" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
Traceback (most recent call last):
File "hangman.py", line 101, in <module>
File "flask/app.py", line 990, in run
File "werkzeug/serving.py", line 1012, in run_simple
File "werkzeug/serving.py", line 956, in inner
File "werkzeug/serving.py", line 807, in make_server
File "werkzeug/serving.py", line 701, in __init__
File "socketserver.py", line 452, in __init__
File "http/server.py", line 138, in server_bind
File "socketserver.py", line 466, in server_bind
OSError: [Errno 98] Address already in use
[46425] Failed to execute script 'hangman' due to unhandled exception!
I am relatively new to programming, so please don't mind any wrong use of technical terms.
Try to turn off the reloader like this :
app.run(debug=True, use_reloader=False)
[Edit]
it seems like some other application is using the same port. Check it by
netstat -tulpn
To get more information, you can use also :
tasklist
When you got the pid, I'd suggest stop it manually
You can also kill it via command kill:
Taskkill /PID THE_PORT /F
I have specified an app.yaml file as follows:
runtime: python
env: standard
# this assumes that the entrypoint is app.py
entrypoint: gunicorn -b :$PORT main:app
threadsafe: true
After running gcloud app deploy I'm faced with a 500 error and the logs reveal the following
Traceback (most recent call last):
File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/base/data/home/runtimes/python27_experiment/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
File "/base/data/home/apps/g~test-website/20170924t080410.404328292497306090/app.py", line 3, in <module>
from flask import Flask, render_template
ImportError: No module named flask
Can anyone help me configure a standard environment
You are combining syntax for the flexible environment and the standard environment in your app.yaml
Look at the documentation for the app.yaml and stick to the standard environment reference. The env parameter is only used for flex and entrypoint is only for flex. The runtime parameter should be python27 as python means the deprecated Python 2.5 runtime.
Given that you're trying to use Flask, you should probably read the getting started guide that is specifically for Flask.
When I try to import non-standard modules into my Flask app with debug mode on and run it locally, the Flask server crashes with an ImportError for _tkinter. If I remove the import for the non-standard module, or turn off debug mode, everything works as expected.
Examples
The following runs fine, and "Hello, World" can be seen at localhost:5000
from flask import Flask
app = Flask(__name__)
#app.route("/")
def home():
return "Hello, World"
if __name__ == '__main__':
app.run(debug=True)
If I add the following line at the top of the file
import dateparser
I get the following Traceback when I run the file:
flask#ubuntu:~/tkerr$ python app.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
Traceback (most recent call last):
File "app.py", line 10, in <module>
app.run(debug=True)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 622, in run_simple
reloader_type)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/_reloader.py", line 269, in run_with_reloader
reloader.run()
File "/usr/local/lib/python2.7/dist-packages/werkzeug/_reloader.py", line 159, in run
for filename in chain(_iter_module_files(), self.extra_files):
File "/usr/local/lib/python2.7/dist-packages/werkzeug/_reloader.py", line 70, in _iter_module_files
for package_path in getattr(module, '__path__', ()):
File "/usr/lib/python2.7/dist-packages/six.py", line 116, in __getattr__
_module = self._resolve()
File "/usr/lib/python2.7/dist-packages/six.py", line 105, in _resolve
return _import_module(self.mod)
File "/usr/lib/python2.7/dist-packages/six.py", line 76, in _import_module
__import__(name)
File "/usr/lib/python2.7/lib-tk/tkCommonDialog.py", line 11, in <module>
from Tkinter import *
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 42, in <module>
raise ImportError, str(msg) + ', please install the python-tk package'
ImportError: No module named _tkinter, please install the python-tk package
For confirmation, with debug mode turned off everything runs as expected, even if I use the dateparser module. For example, the following shows "2015-01-01 00:00:00"
import dateparser
from flask import Flask
app = Flask(__name__)
#app.route("/")
def home():
return str(dateparser.parse("1 jan"))
if __name__ == '__main__':
app.run()
Importing any standard Python modules, such as
import json
works fine. But any other modules installed through pip cause the same issue.
If I run (as prompted by the error)
sudo apt-get install python-tk
Then the Traceback is replaced with an ImportError for _winreg
flask#ubuntu:~/tkerr$ python app.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
Traceback (most recent call last):
File "app.py", line 11, in <module>
app.run(debug=True)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 622, in run_simple
reloader_type)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/_reloader.py", line 269, in run_with_reloader
reloader.run()
File "/usr/local/lib/python2.7/dist-packages/werkzeug/_reloader.py", line 159, in run
for filename in chain(_iter_module_files(), self.extra_files):
File "/usr/local/lib/python2.7/dist-packages/werkzeug/_reloader.py", line 70, in _iter_module_files
for package_path in getattr(module, '__path__', ()):
File "/usr/lib/python2.7/dist-packages/six.py", line 116, in __getattr__
_module = self._resolve()
File "/usr/lib/python2.7/dist-packages/six.py", line 105, in _resolve
return _import_module(self.mod)
File "/usr/lib/python2.7/dist-packages/six.py", line 76, in _import_module
__import__(name)
ImportError: No module named _winreg
Details
Python 2.7.7; Ubuntu 14.04 (VMWare VM); Flask/Werkzeug 0.10.1
A solution would be appreciated, but more so I'd love to gain insight into what could cause Flask to require tkinter, considering it displays all debug output from within the web browser.
edit Add output from pip freeze
Flask==0.10.1
Jinja2==2.7.3
MarkupSafe==0.23
PAM==0.4.2
Pillow==2.3.0
PyMySQL==0.6.6
PyYAML==3.11
Twisted-Core==13.2.0
Twisted-Web==13.2.0
Werkzeug==0.10.1
adium-theme-ubuntu==0.3.4
apt-xapian-index==0.45
argparse==1.2.1
beautifulsoup4==4.4.1
ccsm==0.9.11.3
chardet==2.0.1
colorama==0.2.5
command-not-found==0.3
compizconfig-python==0.9.11.3
dateparser==0.3.0
debtagshw==0.1
defer==1.0.6
dirspec==13.10
duplicity==0.6.23
feedparser==5.1.3
html5lib==0.999
httplib2==0.8
itsdangerous==0.24
lockfile==0.8
lxml==3.3.3
oauthlib==0.6.1
oneconf==0.3.7
pexpect==3.1
piston-mini-client==0.7.5
pyOpenSSL==0.13
pycrypto==2.6.1
pycups==1.9.66
pycurl==7.19.3
pygobject==3.12.0
pyserial==2.6
pysmbc==1.0.14.1
python-apt==0.9.3.5
python-dateutil==2.4.2
python-debian==0.1.21-nmu2ubuntu2
pyxdg==0.25
reporter==0.1.2
reportlab==3.0
requests==2.2.1
sessioninstaller==0.0.0
six==1.5.2
software-center-aptd-plugins==0.0.0
system-service==0.1.6
unity-lens-photos==1.0
urllib3==1.7.1
virtualenv==1.11.4
wsgiref==0.1.2
xdiagnose==3.6.3build2
youtube-dl==2014.02.17
zope.interface==4.0.5
I just tried running the following code on my Windows 10 machine and it worked fine for me.
Flask-Test.py
import dateparser
from flask import Flask
app = Flask(__name__)
#app.route("/")
def home():
return str(dateparser.parse("1 jan"))
if __name__ == '__main__':
app.run(debug=True)
I think there may be an issue with the python environment that you're currently working in. Perhaps try creating a virtual environment to operate out of using virtualenv to make sure that your environment is setup correctly.
If you would like to following along with the steps that I took to setup up a virtual environment to test the code, see below. The commands used might be slightly different when running from Ubuntu.
pip install virtualenv
Navigate to the folder where you have your test code saved and create the Virtual Environment using the following command
virtualenv env
Activate the virtual environment by navigating to the 'activate' file. In my case it was located at
.\venv\Scripts\activate
Download Flask and dateparser using pip
pip install Flask
pip install dateparser
Finally, activate the test file through the virtual environment
python .\Flasky-Test.py
Navigating to localhost returned a value of 2015-01-01 00:00:00 for me ok.
Edit
I just tried running your list of packages and managed to replicate the error that you were receiving. I believe the problem might be with the version of six that you are using. Try running
pip install six --upgrade
And let me know if that fixes the problem for you - it did for me.
I'm having trouble starting Flask for Python 2.7 via Eclipse & Chrome; it's so temperamental am having trouble clarifying the situations it works/doesn't:
Files are .project (Eclipse), init.py & pymongo1.py
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return 'index page'
app.run(debug=True)
I load Eclipse, hit Run and get:
pydev debugger: starting (pid: 5296)
Finding files... done.
Importing test modules ... * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
pydev debugger: starting (pid: 2312)
Finding files... done.
Importing test modules ...
which simply hands. In Chrome, http://127.0.0.1:5000/ or 127.0.0.1:5000/ won't load anything. Changing 'index page' to 'Index page' & hitting save gives
* Detected change in 'C:\\Users\\Eddie\\Desktop\\dev\\health\\pymongo1.py', reloading
127.0.0.1 - - [28/Sep/2015 14:57:49] "GET / HTTP/1.1" 200 -
pydev debugger: Start reloading module: "pymongo1" ...
pydev debugger: Start reloading module: "pymongo1" ...
..and keeps Chrome loading. Hitting Run on Eclipse then gives:
pydev debugger: Start reloading module: "pymongo1" ...
pydev debugger: Start reloading module: "pymongo1" ...
* Detected change in 'C:\\Users\\Eddie\\Desktop\\dev\\health\\pymongo1.py', reloading
pydev debugger: Start reloading module: "pymongo1" ...
* Detected change in 'C:\\Users\\Eddie\\Desktop\\dev\\health\\pymongo1.py', reloading
Traceback (most recent call last):
File "C:\Users\Eddie\Downloads\eclipse\plugins\org.python.pydev_4.0.0.201504132356\pysrc\pydev_runfiles.py", line 468, in __get_module_from_str
mod = __import__(modname)
File "C:\Users\Eddie\Downloads\eclipse\plugins\org.python.pydev_4.0.0.201504132356\pysrc\pydev_monkey_qt.py", line 71, in patched_import
return original_import(name, *args, **kwargs)
File "C:\Users\Eddie\Desktop\dev\health\pymongo1.py", line 115, in <module>
app.run(debug=True)
File "C:\Python27\lib\site-packages\flask-0.10.1-py2.7.egg\flask\app.py", line 772, in run
run_simple(host, port, self, **options)
File "C:\Python27\lib\site-packages\werkzeug-0.10.4-py2.7.egg\werkzeug\serving.py", line 623, in run_simple
reloader_type)
File "C:\Python27\lib\site-packages\werkzeug-0.10.4-py2.7.egg\werkzeug\_reloader.py", line 229, in run_with_reloader
reloader.run()
File "C:\Python27\lib\site-packages\werkzeug-0.10.4-py2.7.egg\werkzeug\_reloader.py", line 131, in run
self.trigger_reload(filename)
File "C:\Python27\lib\site-packages\werkzeug-0.10.4-py2.7.egg\werkzeug\_reloader.py", line 111, in trigger_reload
sys.exit(3)
SystemExit: 3
ERROR: Module: pymongo1 could not be imported (file: C:\Users\Eddie\Desktop\dev\health\pymongo1.py).
Tried shutting down other apps in case they run on the same port, like Google Photos. Any clues why it temperamentally loads content/seems to be getting stuck on the 'importing test module' part? Regards
Resolved by #riotburn and #Joe Doherty. The py file needed starting from Windows PowerShell.
I'm having an import error on Travis builds, the error is related to the configuration of flask:
from flask import Flask
app = Flask(__name__)
app.config.from_object('config')
On local machine, the flask app run correctly. But on travis here is the error trace
$ nosetests --with-coverage --cover-package=core
E.........................
======================================================================
ERROR: Failure: ImportStringError (import_string() failed for 'config'. Possible reasons are:
- missing __init__.py in a package;
- package or module path not included in sys.path;
- duplicated package or module name taking precedence in sys.path;
- missing module, class, function or variable;
Debugged import:
- 'config' not found.
Original exception:
ImportError: No module named config)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/travis/virtualenv/python2.7_with_system_site_packages/local/lib/python2.7/site-packages/nose/loader.py", line 414, in loadTestsFromName
addr.filename, addr.module)
File "/home/travis/virtualenv/python2.7_with_system_site_packages/local/lib/python2.7/site-packages/nose/importer.py", line 47, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/home/travis/virtualenv/python2.7_with_system_site_packages/local/lib/python2.7/site-packages/nose/importer.py", line 94, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/home/travis/build/dzlab/sentimentpy/webapp/app/__init__.py", line 6, in <module>
app.config.from_object('config')
File "/home/travis/virtualenv/python2.7_with_system_site_packages/local/lib/python2.7/site-packages/flask/config.py", line 162, in from_object
obj = import_string(obj)
File "/home/travis/virtualenv/python2.7_with_system_site_packages/local/lib/python2.7/site-packages/werkzeug/utils.py", line 426, in import_string
sys.exc_info()[2])
File "/home/travis/virtualenv/python2.7_with_system_site_packages/local/lib/python2.7/site-packages/werkzeug/utils.py", line 408, in import_string
return __import__(import_name)
ImportStringError: import_string() failed for 'config'. Possible reasons are:
- missing __init__.py in a package;
- package or module path not included in sys.path;
- duplicated package or module name taking precedence in sys.path;
- missing module, class, function or variable;
What's wrong with my configuration?
import_string only takes absolute module imports. Since config is not a top-level module, but part of webapp, you need to specify webapp.config. See http://flask.pocoo.org/docs/0.10/config/#configuring-from-files:
app = Flask(__name__)
app.config.from_object('yourapplication.default_settings')
app.config.from_envvar('YOURAPPLICATION_SETTINGS')
I came across this issue recently and could not figure it out until I had an epiphany after 2nd days by reading Markus's answer.
Just in-case someone out there is looking for a solution to load the configuration from config.py and the flask app is using a package structure then ensure to provide the full classpath to the config class file in app.config.from_object().
For e.g., I had a configuration myproj/app/config.py in my flask project myproj and the class file with the configuration was DevelopmentConfig. You need to provide it as follows:
app.config.from_object('app.config.DevelopmentConfig')
Another example would be if you put the same file under myproj/instance/config.py then, you call it as:
app.config.from_object('instance.config.DevelopmentConfig')
During the development of your app, the easiest way to change your settings would be to put an environment variable in myapp/.env file like so:
FLASK_APP=app
APP_SETTINGS="app.config.DevelopmentConfig"
and use the variable in your app.config.from_object() call:
app.config.from_object(os.environ['APP_SETTINGS'])
But do remember that for the .env to take effect, you need to start your app with flask run instead of running the app directly.