This question already has an answer here:
Quickstart Flask application failing for some reason
(1 answer)
Closed 6 years ago.
Edit: This question apparently has an answer here
Quickstart Flask application failing for some reason
As well as a (closed and apparently fixed) GitHub issue here:
https://github.com/pallets/werkzeug/issues/798
Unfortunately I'm still experiencing the problem, even with Werkzeug 0.12-dev (the latest code from GitHub).
I've just started developing a simple Flask application with Python 3.4 on Windows. Literally, at the moment, here are the only contents of fileserve.py.
import os.path
from flask import abort, Flask
base_directory = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config.from_pyfile(os.path.join(base_directory, 'fileserve.cfg'))
#app.route('/')
def index():
abort(403)
if __name__ == '__main__':
app.run(debug=True)
When I try running the application, I get the following traceback:
Traceback (most recent call last):
File "fileserve.py", line 22, in <module>
app.run(debug=True)
File "C:\Users\jscholes\dev\fileserve\env\lib\site-packages\flask\app.py", line 772, in run
run_simple(host, port, self, **options)
File "C:\Users\jscholes\dev\fileserve\env\lib\site-packages\werkzeug\serving.py", line 633, in run_simple
application = DebuggedApplication(application, use_evalex)
File "C:\Users\jscholes\dev\fileserve\env\lib\site-packages\werkzeug\debug\__init__.py", line 249, in __init__
if self.pin is None:
File "C:\Users\jscholes\dev\fileserve\env\lib\site-packages\werkzeug\debug\__init__.py", line 259, in _get_pin
self._pin, self._pin_cookie = get_pin_and_cookie_name(self.app)
File "C:\Users\jscholes\dev\fileserve\env\lib\site-packages\werkzeug\debug\__init__.py", line 169, in get_pin_and_cookie_name
h.update('cookiesalt')
TypeError: Unicode-objects must be encoded before hashing
This error occurs even with a simple "hello world" app:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return 'Hello world'
app.run(debug=True)
Is Flask's support for Python 3 just not very good? Is there a workaround for this? Working without the option of debug mode is not a great prospect.
Upgrade your werkzeug installation.
In my install, with werkzeug.__version__ == 0.11.7, line 169 reads:
h.update(b'cookiesalt')
Related
so I'm pretty new to Flask and i've been following a tutorial but I have been getting a strange problem. I have the following code, a python3 script, launched in atom with the hydrogen package enabled and jupyter. I have the virtual environment running in the background in a terminal.
from flask import Flask
app = Flask(__name__)
if __name__ == '__main__':
app.run(debug=True)
So obviously the script is very basic and it's just used to see if i can connect to localhost, however when running it (through Hydrogen) I get the following error:
Serving Flask app 'main'
Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
Running on http://127.0.0.1:5000
Press CTRL+C to quit
Restarting with stat
Traceback (most recent call last):
File "/home/uses12/.local/lib/python3.10/site-packages/ipykernel_launcher.py", line 17, in
app.launch_new_instance()
File "/home/uses12/.local/lib/python3.10/site-packages/traitlets/config/application.py", line 977, in launch_instance
app.initialize(argv)
File "/home/uses12/.local/lib/python3.10/site-packages/traitlets/config/application.py", line 110, in inner
return method(app, *args, **kwargs)
File "/home/uses12/.local/lib/python3.10/site-packages/ipykernel/kernelapp.py", line 666, in initialize
self.init_sockets()
File "/home/uses12/.local/lib/python3.10/site-packages/ipykernel/kernelapp.py", line 307, in init_sockets
self.shell_port = self._bind_socket(self.shell_socket, self.shell_port)
File "/home/uses12/.local/lib/python3.10/site-packages/ipykernel/kernelapp.py", line 244, in _bind_socket
return self._try_bind_socket(s, port)
File "/home/uses12/.local/lib/python3.10/site-packages/ipykernel/kernelapp.py", line 220, in _try_bind_socket
s.bind("tcp://%s:%i" % (self.ip, port))
File "/home/uses12/.local/lib/python3.10/site-packages/zmq/sugar/socket.py", line 232, in bind
super().bind(addr)
File "zmq/backend/cython/socket.pyx", line 568, in zmq.backend.cython.socket.Socket.bind
File "zmq/backend/cython/checkrc.pxd", line 28, in zmq.backend.cython.checkrc._check_rc
zmq.error.ZMQError: Address already in use
Upon looking online, a possible solution was to specify the port in the app. parameters, however no matter what port I specify it ALWAYS says that the address is already in use, leading me to believe that there is some deeper issue. I've done a check to see what services are using those ports and it's always just two instances of python3, I guess because Flask is set to debug. I'm completely lost. Can anyone help? Thanks so much.
I was trying to build flask-web API. When I am trying to run the app.py code, I have got this error, please refer the code which I have mentioned below. Do I have to install some package to get 'package' into 'main'?
I tried to run in different platforms such jupyter notebook, spyder and Google Colab too, but it didn't work, and getting similar issues.
Here is my app.py code whic is giving error:
from flask import Flask, request, jsonify, render_template
import pickle
app = Flask(__name__)
model = pickle.load(open('model.pkl', 'rb'))
#app.route('/')
def home():
return render_template('index.html')
#app.route('/predict',methods=['POST'])
def predict():
'''
For rendering results on HTML GUI
'''
int_features = [int(x) for x in request.form.values()]
final_features = [np.array(int_features)]
prediction = model.predict(final_features)
output = round(prediction[0], 2)
return render_template('index.html', prediction_text='Employee Salary should be $ {}'.format(output))
#app.route('/predict_api',methods=['POST'])
def predict_api():
'''
For direct API calls trought request
'''
data = request.get_json(force=True)
prediction = model.predict([np.array(list(data.values()))])
output = prediction[0]
return jsonify(output)
if __name__ == "__main__":
app.run(debug=True)
Here is the error message I have got:
* Serving Flask app "__main__" (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: on
* Restarting with stat
Traceback (most recent call last):
File "<ipython-input-21-3add8626fce0>", line 36, in <module>
app.run(debug=True)
File "C:\Users\ishwo\Anaconda3\lib\site-packages\flask\app.py", line 990, in run
run_simple(host, port, self, **options)
File "C:\Users\ishwo\Anaconda3\lib\site-packages\werkzeug\serving.py", line 1007, in run_simple
run_with_reloader(inner, extra_files, reloader_interval, reloader_type)
File "C:\Users\ishwo\Anaconda3\lib\site-packages\werkzeug\_reloader.py", line 332, in run_with_reloader
sys.exit(reloader.restart_with_reloader())
File "C:\Users\ishwo\Anaconda3\lib\site-packages\werkzeug\_reloader.py", line 159, in restart_with_reloader
args = _get_args_for_reloading()
File "C:\Users\ishwo\Anaconda3\lib\site-packages\werkzeug\_reloader.py", line 76, in _get_args_for_reloading
if __main__.__package__ is None:
AttributeError: module '__main__' has no attribute '__package__'}
If I import logstash, running locally I get the following error
Connected to pydev debugger (build 162.1812.1)
/home/vagrant/.envs/emailservice/lib/python3.4/site-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.cache is deprecated, use flask_cache instead.
.format(x=modname), ExtDeprecationWarning
Traceback (most recent call last):
File "/home/vagrant/.pycharm_helpers/pydev/pydevd.py", line 1580, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "/home/vagrant/.pycharm_helpers/pydev/pydevd.py", line 964, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/home/vagrant/.pycharm_helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/emailService/app.py", line 59, in <module>
import logstash
File "/home/vagrant/.envs/emailservice/lib/python3.4/site-packages/logstash/__init__.py", line 2, in <module>
from event import Event
ImportError: No module named 'event'
Process finished with exit code 1
my app.py file looks mostly like this. I run it locally through a vagrant session. If I remove the import logstash from the local branch of the if, the application starts up fine and I get local console log output.
import logging
import os
import sys
from flask import Flask
from flask_restful import Api
from flask_cache import Cache
from flask_sqlalchemy import SQLAlchemy
from opbeat.contrib.flask import Opbeat
from tasks import make_celery
app = Flask(__name__)
app.secret_key = os.environ.get('SECRET_KEY', 'SUCHSECRETSWOW')
app.config.from_object(os.environ.get('APP_SETTINGS', 'config.DevelopmentConfig'))
cache = Cache(app)
db = SQLAlchemy(app)
api = Api(app)
celery = make_celery(app)
if len(app.config['OPBEAT_ORGANIZATION_ID']):
opbeat = Opbeat(
app,
organization_id=app.config['OPBEAT_ORGANIZATION_ID'],
app_id=app.config['OPBEAT_APP_ID'],
secret_token=app.config['OPBEAT_SECRET_TOKEN'],
)
#app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
return response
def clear_cache():
cache.clear()
def start_resources():
from emailService.api import HealthApi
api.add_resource(HealthApi, '/health')
def start_tasks():
from emailService.tasks import KickoffFetchEmailPeriodTask
if __name__ == '__main__':
if app.config.get('DEVELOPMENT', False):
#The reason this exists is purely because of my error.
import logstash
app.logger.setLevel(logging.DEBUG)
app.logger.addHandler(logging.StreamHandler())
else:
import logstash
app.logger = logging.getLogger('python-logstash-logger')
app.logger.setLevel(logging.INFO)
app.logger.addHandler(logstash.LogstashHandler('myhost.veryhost.suchhost', 5959, version=1))
app.logger.addHandler(logging.StreamHandler())
clear_cache()
start_tasks()
start_resources()
app.logger.debug('Starting app')
app.run(host='0.0.0.0', port=16600, debug=True, use_reloader=False)
All of the google searches result in a great big fat sum total of nothing helpful.
You're probably running into this issue, you have pip installed logstash instead of python-logstash
Run this and it should work afterwards:
> pip uninstall logstash
> pip install python-logstash
I have a Flask app where this is my main.py
from king_slayer.database import init_db, manager
from king_slayer.views import fetch_production
if __name__ == '__main__':
init_db()
manager.run()
Before the manger.run() gets executed I want to call
fetch_production()
so I did this.
from king_slayer.database import init_db, manager
from king_slayer.views import fetch_production
if __name__ == '__main__':
init_db()
with manager.app.test_request_context():
fetch_production()
manager.run()
It works.
The problem is when I kill the Flask app and then restart it, It wont startup for like 60-120 seconds. No errors, Nothing. The browser wont load anything. simple 'Problem loading page' appears and after sometime it works fine unless I again restart the Flask app.
If I remove
with manager.app.test_request_context():
fetch_production()
the delay doesn't happens.
P.S
If I dont use with manager.app.test_request_context():
Flask throws this error.
Traceback (most recent call last):
File "main.py", line 8, in <module>
fetch_production()
File "/home/jarvis/Development/kingslayer/king_slayer/king_slayer/views.py", line 156, in fetch_production
results={"msg": "Database Updated", }
File "/home/jarvis/Development/kingslayer/local/lib/python2.7/site-packages/flask/json.py", line 235, in jsonify
and not request.is_xhr:
File "/home/jarvis/Development/kingslayer/local/lib/python2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
File "/home/jarvis/Development/kingslayer/local/lib/python2.7/site-packages/werkzeug/local.py", line 297, in _get_current_object
return self.__local()
File "/home/jarvis/Development/kingslayer/local/lib/python2.7/site-packages/flask/globals.py", line 20, in _lookup_req_object
raise RuntimeError('working outside of request context')
RuntimeError: working outside of request context
What is happening ?
P.P.S fetch_production() does something like this
requests.get(config.SERVER, auth=HTTPBasicAuth(config.AUTH_USER, config.AUTH_PASSWORD))
makes a few function calls, functions that are defined in views.py and then creates an .ini file in the file system. Then in the end returns a return jsonify.
requests.get(config.SERVER, auth=HTTPBasicAuth(config.AUTH_USER, config.AUTH_PASSWORD))
is actually very fast and if the fetch_production() is called manually it doesn't take more than a few milliseconds.
I'm following the Flask Tutorial (Flaskr) in order to experiment with using Neo4j-embedded for Python. This is in a virtualenv. Here is my 'main' app code:
import os
import jpype
from neo4j import GraphDatabase
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
app = Flask(__name__)
app.config.from_pyfile(os.environ['APP_SETTINGS'])
def connectDB():
return GraphDatabase(app.config['DATABASE'])
def initDB():
db = connectDB()
with db.transaction:
users = db.node()
roles = db.node()
db.reference_node.USERS(users)
db.reference_node.ROLES(roles)
userIndex = db.node.indexes.create('users')
user = db.node(name=app.config['ADMIN'])
user.INSTANCE_OF(users)
userIndex['name'][app.config['ADMIN']] = user
role = db.node(type='superadmin')
role.INSTANCE_OF(roles)
role.ASSIGN_TO(user)
db.shutdown()
print "Database initialized."
def testDB():
db = connectDB()
with db.transaction:
userIndex = db.node.indexes.get('users')
user = userIndex['name'][app.config['ADMIN']].single
username = user['name']
db.shutdown()
print "Admin username is '%s'. Database exists." % username
#app.before_request
def before_request():
jpype.attachThreadToJVM()
g.db = connectDB()
#app.teardown_request
def teardown_request(exception):
g.db.shutdown()
#app.route('/')
def index():
with g.db.transaction:
userIndex = g.db.node.indexes.get('users')
user = userIndex['name'][app.config['ADMIN']].single
username = user['name']
fields = dict(username=username)
return render_template('index.html', fields=fields)
if os.path.exists(app.config['DATABASE']) == False:
initDB()
else:
testDB()
initDB() and testDB() work perfectly fine - without Gremlin, PyLucene, etc. - just jpype and neo4j-embedded. Initially, the JVM would fail and the app would terminate when I would request index(). I scoured the net to learn that I needed to add the line "jpype.attachThreadToJVM()" into before_request() to solve that issue with python threading the JVM and the app does not terminate. However, this leads immediately to another issue:
Traceback (most recent call last):
File "/ht/dev/envFlask/lib/python2.7/site-packages/flask/app.py", line 1518, in __call__
return self.wsgi_app(environ, start_response)
File "/ht/dev/envFlask/lib/python2.7/site-packages/flask/app.py", line 1506, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/ht/dev/envFlask/lib/python2.7/site-packages/flask/app.py", line 1504, in wsgi_app
response = self.full_dispatch_request()
File "/ht/dev/envFlask/lib/python2.7/site-packages/flask/app.py", line 1264, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/ht/dev/envFlask/lib/python2.7/site-packages/flask/app.py", line 1262, in full_dispatch_request
rv = self.dispatch_request()
File "/ht/dev/envFlask/lib/python2.7/site-packages/flask/app.py", line 1248, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/ht/dev/apps/evobox/evobox/__init__.py", line 68, in index
userIndex = g.db.node.indexes.get('users')
File "/ht/dev/envFlask/lib/python2.7/site-packages/neo4j/index.py", line 36, in get
return self._index.forNodes(name)
java.lang.RuntimeExceptionPyRaisable: java.lang.IllegalArgumentException: No index provider 'lucene' found. Maybe the intended provider (or one more of its dependencies) aren't on the classpath or it failed to load.
Google search of the entire last line didn't go anywhere. Just searching "java.lang.IllegalArgumentException: No index provider 'lucene' found." lead to nothing in the context of python.
The neo4j messages.log seems to show the database was opened 3 times (initDB(), testDB(), and index()). The classpath is the same for each instance:
Class Path: /ht/dev/envFlask/local/lib/python2.7/site-packages/neo4j/javalib/neo4j-jmx-1.5.M02.jar:/ht/dev/envFlask/local/lib/python2.7/site-packages/neo4j/javalib/neo4j-lucene-index-1.5.M02.jar:/ht/dev/envFlask/local/lib/python2.7/site-packages/neo4j/javalib/neo4j-graph-matching-1.5.M02.jar:/ht/dev/envFlask/local/lib/python2.7/site-packages/neo4j/javalib/neo4j-1.5.M02.jar:/ht/dev/envFlask/local/lib/python2.7/site-packages/neo4j/javalib/neo4j-kernel-1.5.M02.jar:/ht/dev/envFlask/local/lib/python2.7/site-packages/neo4j/javalib/geronimo-jta_1.1_spec-1.1.1.jar:/ht/dev/envFlask/local/lib/python2.7/site-packages/neo4j/javalib/lucene-core-3.1.0.jar:/ht/dev/envFlask/local/lib/python2.7/site-packages/neo4j/javalib/neo4j-graph-algo-1.5.M02.jar:/ht/dev/envFlask/local/lib/python2.7/site-packages/neo4j/javalib/neo4j-udc-1.5.M02.jar:/ht/dev/envFlask/local/lib/python2.7/site-packages/neo4j/javalib/neo4j-cypher-1.5.M02.jar:/ht/dev/envFlask/local/lib/python2.7/site-packages/neo4j/javalib/scala-library-2.9.0-1.jar
I also modified index() to connectDB and attachThreadToJVM directly like initDB() and testDB() without using the 'g' global - this resulted in exact same error.
What am I possibly missing/overlooking to get neo4j-embedded and jpype working on a threaded request and not just in the 'main' app?
Note: I'm aware of the RESTful Web Service solutions with py2neo or Rexster/Bulbs, but I want avoid that for now.
EDIT: Using JPype-0.5.4.2, Neo4j-embedded-1.5.b2, Java-6-openjdk
One issue with this pattern is that you run the risk of starting multiple databases pointed at the same location, which will lead to problems. What you would want is a single instance of the database that follows the full lifecycle of your application.
Why it's not finding the lucene provider is a harder question.. The index provider is loaded using java service loader, which means that JPype should not affect it. As long as the JVM start alright, and the lucene-index implementation jar is on the classpath, it should work.
It may be related to threading somehow, I'm currently writing a fix to automaitcally handle the "attachThreadToJVM()" calls. I'll add a test case to make sure reading indexes from a separate thread works as expected as well.
The threading work is currently kept updated in this mailing list thread:
http://neo4j-community-discussions.438527.n3.nabble.com/Neo4j-Python-embedding-problems-with-shutdown-and-threads-td3476163.html
Tried replicating the error, using a clean install of neo4j, flask , and jpipe, using the standard java default path. Could not produce that log.
But I got an error of
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "teststack.py", line 27, in initDB
userIndex = db.node.indexes.create('users')
File "/usr/local/lib/python2.7/dist-packages/neo4j/index.py", line 32, in create
return self._index.forNodes(name, to_java(config))
jpype._jexception.RuntimeExceptionPyRaisable: java.lang.IllegalArgumentException: Supplied index configuration:
{}
doesn't match stored config in a valid way:
{provider=lucene, type=exact}
for 'users'
when using initDB
fixed with
userIndex = db.node.indexes.create(users)