I followed official document, installed virtualenv and flask, and then python hello.py
But there is something wrong:
* Running on http://127.0.0.1:5000/
* Restarting with reloader: inotify events
Traceback (most recent call last):
File "hello.py", line 9, in <module>
app.run(debug=True)
File "/home/aa/prj/env/lib/python2.7/site-packages/Flask-0.7.2-py2.7.egg/flask/app.py", line 553, in run
return run_simple(host, port, self, **options)
File "/home/aa/prj/env/lib/python2.7/site-packages/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 609, in run_simple
run_with_reloader(inner, extra_files, reloader_interval)
File "/home/aa/prj/env/lib/python2.7/site-packages/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 528, in run_with_reloader
reloader_loop(extra_files, interval)
File "/home/aa/prj/env/lib/python2.7/site-packages/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 436, in reloader_loop
reloader(fnames, interval=interval)
File "/home/aa/prj/env/lib/python2.7/site-packages/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 464, in _reloader_inotify
mask = reduce(lambda m, a: m | getattr(EventsCodes, a), mask, 0)
File "/home/aa/prj/env/lib/python2.7/site-packages/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 464, in <lambda>
mask = reduce(lambda m, a: m | getattr(EventsCodes, a), mask, 0)
AttributeError: type object 'EventsCodes' has no attribute 'IN_DELETE_SELF'
my hello.py:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return "Hello World!"
if __name__ == '__main__':
app.run(debug=True)
but if without debug that's ok? why?
my /env/lib/python2.7/site-packages:
distribute-0.6.10-py2.7.egg
Jinja2-2.6-py2.7.egg
Werkzeug-0.7-py2.7.egg
easy-install.pth
pip-0.7.2-py2.7.egg
This seems to be a bug triggered by a change in pyinotify's API, which you must also have installed. You could remove pyinotify or use a dirty hack to force it to use stat() instead of pyinotify. To line 496 of werkzeug/serving.py try adding (below the part where it attempts to import pyinotify):
# dirty hack
reloader = _reloader_stat_loop
reloader_name = "stat() polling"
Make sure to also report the bug to the werkzeug developers.
Related
Flask RESTApi newbie here
I am trying to build a RESTapi service in Flask (and I am trying to save the output as a .txt file) using flask_restful for a code of mine using the pydifact module as follows:
import datetime
from pydifact.message import Message
from pydifact.segments import Segment
from flask import Flask, request
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class RestAPI(Resource):
def get(self, ABSENDER_ID, EMPFÄNGER_ID, ERSTELLUNG_DATUM_ZEIT, REFERENCE):
MSCONS = Message()
def erstellung_datum_zeit(dt_time):
# Needed for the UNB segment
dt_time = dt_time.strftime('%Y%m%d%H%M')
return dt_time
def UNA_UNB_segment(absender_id, empfänger_id, erst_datum, ref):
MSCONS.add_segment(Segment('UNA', ":+.? '"))
MSCONS.add_segment(Segment('UNB', ['UNOC', '3'], [absender_id, '14'], [
empfänger_id, '500'], [erst_datum[2:8], erst_datum[8:]], ref, '', 'TL'))
ERSTELLUNG_DATUM_ZEIT = str(
erstellung_datum_zeit(datetime.datetime.now()))
UNA_UNB_segment(ABSENDER_ID, EMPFÄNGER_ID,
ERSTELLUNG_DATUM_ZEIT, REFERENCE)
result = MSCONS.serialize()
final_result = result
PATH_FOR_TXT = r'C:\Users\kashy\OneDrive\Desktop\Codes\mscons.txt'
textfile = open(PATH_FOR_TXT, 'w')
textfile.write(result)
textfile.close()
return {'result': final_result}
api.add_resource(
RestAPI,
'/RestAPI/<int:ABSENDER_ID>/<int:EMPFÄNGER_ID/<int:ERSTELLUNG_DATUM_ZEIT/<int:REFERENCE>')
if __name__ == '__main__':
app.run(debug=True)
The ABSENDER_ID, EMPFÄNGER_ID, ERSTELLUNG_DATUM_ZEIT, REFERENCE should all be user inputs and they should be all in string format.
When I do /RestAPI/<str:ABSENDER_ID>/<str:EMPFÄNGER_ID/<str:ERSTELLUNG_DATUM_ZEIT/<str:REFERENCE>, i get the following error:
C:\Users\kashy\OneDrive\Desktop\Codes\pydifact> & C:/Users/kashy/Anaconda3/envs/py36/python.exe c:/Users/kashy/OneDrive/Desktop/Codes/api.py
Traceback (most recent call last):
File "c:/Users/kashy/OneDrive/Desktop/Codes/api.py", line 44, in <module>
self.url_map.add(rule)
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 1401, in add
rule.bind(self)
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 730, in bind
self.compile()
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 790, in compile
_build_regex(self.rule if self.is_leaf else self.rule.rstrip("/"))
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 779, in _build_regex
convobj = self.get_converter(variable, converter, c_args, c_kwargs)
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 738, in get_converter
raise LookupError("the converter %r does not exist" % converter_name)
LookupError: the converter 'str' does not exist
and when I do
/RestAPI/<int:ABSENDER_ID>/<int:EMPFÄNGER_ID/<int:ERSTELLUNG_DATUM_ZEIT/<int:REFERENCE>, I get the following error:
PS C:\Users\kashy\OneDrive\Desktop\Codes\pydifact> & C:/Users/kashy/Anaconda3/envs/py36/python.exe c:/Users/kashy/OneDrive/Desktop/Codes/api.py
Traceback (most recent call last):
File "c:/Users/kashy/OneDrive/Desktop/Codes/api.py", line 44, in <module>
'/RestAPI/<int:ABSENDER_ID>/<int:EMPFÄNGER_ID/<int:ERSTELLUNG_DATUM_ZEIT/<int:REFERENCE>')
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\flask_restful\__init__.py", line 382, in add_resource
self._register_view(self.app, resource, *urls, **kwargs)
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\flask_restful\__init__.py", line 448, in _register_view
app.add_url_rule(rule, view_func=resource_func, **kwargs)
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\flask\app.py", line 98, in wrapper_func
return f(self, *args, **kwargs)
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\flask\app.py", line 1277, in add_url_rule
self.url_map.add(rule)
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 1401, in add
rule.bind(self)
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 730, in bind
self.compile()
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 790, in compile
_build_regex(self.rule if self.is_leaf else self.rule.rstrip("/"))
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 766, in _build_regex
for converter, arguments, variable in parse_rule(rule):
File "C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\werkzeug\routing.py", line 226, in parse_rule
raise ValueError("malformed url rule: %r" % rule)
ValueError: malformed url rule: '/RestAPI/<int:ABSENDER_ID>/<int:EMPFÄNGER_ID/<int:ERSTELLUNG_DATUM_ZEIT/<int:REFERENCE>'
I am totally new to this and just started learning it using the Building a REST API using Python and Flask | Flask-RESTful tutorial.
Can anyone please tell me what is the mistake I am doing?
Your url routes have problem. In the first one, it should be string instead of str and in the second one you have a missing > at the end of int:EMPFÄNGER_ID and int:ERSTELLUNG_DATUM_ZEIT
Correct ones should be:
/RestAPI/<string:ABSENDER_ID>/<string:EMPFANGER_ID>/<string:ERSTELLUNG_DATUM_ZEIT>/<string:REFERENCE>
and
/RestAPI/<int:ABSENDER_ID>/<int:EMPFANGER_ID>/<int:ERSTELLUNG_DATUM_ZEIT>/<int:REFERENCE>
Note: I replaced Ä with A in urls above because that might also cause malformed url rule issue.
I'm trying to control a robot with ROS and flask. The problem is that when i kill ROS with ctrl-c (SIGINT) flask is slowing this process down because it is not closing right away. I have implemented a signal_handler to handle the ctrl-c and close flask.
The problem is that when i run this and press
ctrl-c i closes everything right away but i get the following error:
RuntimeError: Working outside of request context.
How can i fix this error?
#!/usr/bin/env python
import rospy
from raspimouse_ros.msg import MotorFreqs
from time import sleep
from flask import Flask, request
from os.path import join, dirname
from signal import signal, SIGINT
cwd = dirname(__file__)
open(join(cwd, "file.html"))
app = Flask(__name__)
deltaX = 0
deltaY = 0
pub = rospy.Publisher('/motor_raw', MotorFreqs, queue_size=10)
rospy.init_node('control')
msg = MotorFreqs()
def signal_handler(signal_received, frame):
msg.left = 0
msg.right = 0
pub.publish(msg)
print("Quitting .......")
func = request.environ.get('werkzeug.server.shutdown')
func()
signal(SIGINT,signal_handler)
#app.route("/")
def main():
with open(join(cwd, "file.html"), 'r') as f:
program = f.read()
return program
#app.route("/SetSpeed")
def SetSpeed():
global deltaX
global deltaY
deltaX = int(float(request.args.get('x')) * 4)
deltaY = int(float(request.args.get('y')) * 10)
publisher()
return ""
def publisher():
msg.left = int(-deltaY+deltaX)
msg.right = int(-deltaY-deltaX)
rospy.loginfo(msg)
pub.publish(msg)
app.run(host="0.0.0.0")
[control-1] killing on exit
Quitting .......
Traceback (most recent call last):
File "/home/pi/workspace/src/manual_control/scripts/control.py", line 54, in <module>
app.run(host="0.0.0.0")
File "/usr/lib/python2.7/dist-packages/flask/app.py", line 841, in run
run_simple(host, port, self, **options)
File "/usr/lib/python2.7/dist-packages/werkzeug/serving.py", line 708, in run_simple
inner()
File "/usr/lib/python2.7/dist-packages/werkzeug/serving.py", line 673, in inner
srv.serve_forever()
File "/usr/lib/python2.7/dist-packages/werkzeug/serving.py", line 511, in serve_forever
HTTPServer.serve_forever(self)
File "/usr/lib/python2.7/SocketServer.py", line 231, in serve_forever
poll_interval)
File "/usr/lib/python2.7/SocketServer.py", line 150, in _eintr_retry
return func(*args)
File "/home/pi/workspace/src/manual_control/scripts/control.py", line 28, in signal_handler
func = request.environ.get('werkzeug.server.shutdown')
File "/usr/lib/python2.7/dist-packages/werkzeug/local.py", line 343, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/lib/python2.7/dist-packages/werkzeug/local.py", line 302, in _get_current_object
return self.__local()
File "/usr/lib/python2.7/dist-packages/flask/globals.py", line 37, in _lookup_req_object
raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
shutting down processing monitor...
... shutting down processing monitor complete
done
The request context is active when a request arrives and is destroyed after it finishes, so it is not availale in the signal_handler function, you can, however, access app_context.
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__'}
every time i run the code i see Serving Flask-SocketIO app "app.py"
i don't even have SpcketIO on my system
import os, passlib ,requests ,time ,json
from flask import Flask, session , render_template , request,redirect,url_for ,jsonify
from flask_session import Session
import pandas as pd
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
from werkzeug import secure_filename
from datetime import date , datetime
from flask_sqlalchemy import SQLAlchemy
from passlib.hash import sha256_crypt
from flask_login import LoginManager , UserMixin , current_user ,login_user ,login_required ,logout_user
app = Flask(__name__)
by the end of my code I've this
if __name__ == "__main__":
app.run(debug=True)
i run the system by cmd: flask run
I used to ignore this error as everything else was working but when i tried to add app.run(debug=True,host='0.0.0.0')
also debug=True didn't seem to be doing anything anymore i had to turn it on through the CMD set Flask_Debug=1
i got an error stating ValueError: signal only works in main thread
and the app didn't run at all
the exact error
* Serving Flask-SocketIO app "app.py"
* Forcing debug mode on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 885-769-473
Exception in thread Thread-1:
Traceback (most recent call last):
File "c:\users\mena\appdata\local\programs\python\python37-32\lib\threading.py
", line 917, in _bootstrap_inner
self.run()
File "c:\users\mena\appdata\local\programs\python\python37-32\lib\threading.py
", line 865, in run
self._target(*self._args, **self._kwargs)
File "c:\users\mena\appdata\local\programs\python\python37-32\lib\site-package
s\flask_socketio\cli.py", line 59, in run_server
return run_command()
File "c:\users\mena\appdata\local\programs\python\python37-32\lib\site-package
s\click\core.py", line 764, in __call__
return self.main(*args, **kwargs)
File "c:\users\mena\appdata\local\programs\python\python37-32\lib\site-package
s\click\core.py", line 717, in main
rv = self.invoke(ctx)
File "c:\users\mena\appdata\local\programs\python\python37-32\lib\site-package
s\click\core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\mena\appdata\local\programs\python\python37-32\lib\site-package
s\click\core.py", line 555, in invoke
return callback(*args, **kwargs)
File "c:\users\mena\appdata\local\programs\python\python37-32\lib\site-package
s\click\decorators.py", line 64, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "c:\users\mena\appdata\local\programs\python\python37-32\lib\site-package
s\click\core.py", line 555, in invoke
return callback(*args, **kwargs)
File "c:\users\mena\appdata\local\programs\python\python37-32\lib\site-package
s\flask\cli.py", line 771, in run_command
threaded=with_threads, ssl_context=cert)
File "c:\users\mena\appdata\local\programs\python\python37-32\lib\site-package
s\werkzeug\serving.py", line 812, in run_simple
reloader_type)
File "c:\users\mena\appdata\local\programs\python\python37-32\lib\site-package
s\werkzeug\_reloader.py", line 267, in run_with_reloader
signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
File "c:\users\mena\appdata\local\programs\python\python37-32\lib\signal.py",
line 47, in signal
handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread
to get back to work i had to turn off the debug in cmd set Flask_Debug=0
what's wrong with my system ?
please check if there is any other thread running or not. And try running your app by command python app.py from terminal instead of flask run. may be flask run command invoking other services to which are not necessary to your application.
Also I am assuming you are working on Linux system. In terminal (Windows cmd) and in your project directory where your app.py is located just enter python (python/python3 depnds whichever version you are using) app.py and hit enter.
try this on command line
python app.py
or
python3 app.py
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.