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.
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'm trying to write a simple server that disconnects a user after a min of inactivity.
ive found a simple way of doing it with threading.Timer (restarting the timer every time there is an activity).
im getting RuntimeError when using disconnect in a Timer.
tried using app.app_context and app.test_request_context but either I don't know how and where to use them or it simply doesn't work.
server code:
from flask import Flask, request
from flask_socketio import SocketIO, emit, disconnect
from threading import Timer
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
sio = SocketIO(app)
clients = {}
class Client:
def __init__(self, user, sid, client_time):
self.user = user
self.sid = sid
self.client_time = client_time
self.activity_timer = Timer(10, self.disc_after_60)
self.start_timer()
def disc_after_60(self):
disconnect(self.sid)
del clients[self.user]
def start_timer(self):
if self.activity_timer.is_alive():
self.activity_timer.cancel()
self.activity_timer.start()
else:
self.activity_timer.start()
#sio.on('register')
def handle_register(client_user, client_time):
clients[client_user] = Client(client_user, request.sid, client_time)
emit('message', ("SERVER", f"{client_user} has joined the server!"), broadcast=True)
client side I just connect using register.
the full error message:
Exception in thread Thread-8:
Traceback (most recent call last):
File "C:\Users\idshi\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\idshi\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 1254, in run
self.function(*self.args, **self.kwargs)
File "C:\Users\idshi\PycharmProjects\PyChat excersize\Server\fsserver.py", line 24, in disc_after_60
disconnect(self.sid)
File "C:\Users\idshi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask_socketio\__init__.py", line 919, in disconnect
socketio = flask.current_app.extensions['socketio']
File "C:\Users\idshi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\werkzeug\local.py", line 348, in __getattr__
return getattr(self._get_current_object(), name)
File "C:\Users\idshi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\werkzeug\local.py", line 307, in _get_current_object
return self.__local()
File "C:\Users\idshi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask\globals.py", line 52, in _find_app
raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context(). See the
documentation for more information.
I would be glad if someone can help me with this. Thanks in advance.
The disconnect() function needs to be called with an application context installed, as that's the only way to know what's the application instance.
Try this:
def disc_after_60(self):
with app.app_context():
disconnect(sid=self.sid, namespace='/')
del clients[self.user]
My problem:
I'm having trouble with a Flask application when it comes to specifying the return type of a function that calls on jsonify() in the return. Flask's jsonify is ultimately returning a current_app.response_class. However, by specifying this type of return in the signature, I get an error.
The error:
Traceback (most recent call last):
File "wsgi.py", line 1, in <module>
from app import app as application
File "./app.py", line 94, in <module>
def handle_msg_request() -> current_app.response_class:
File "/usr/local/lib/python3.7/site-packages/werkzeug/local.py", line 348, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/local/lib/python3.7/site-packages/werkzeug/local.py", line 307, in _get_current_object
return self.__local()
File "/usr/local/lib/python3.7/site-packages/flask/globals.py", line 51, in _find_app
raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context(). See the
documentation for more information.
The offending code:
from flask import Flask, render_template, request, jsonify, send_from_directory, current_app
#app.route("/requestmessages", methods=['POST'])
def handle_msg_request() -> current_app.response_class:
last_id = int(request.form['lastId'])
data = get_all_chat_dict(min=last_id)
if len(data) == 0:
return jsonify(hasNewData=False)
return jsonify(hasNewData=True, dataRows=data)
Related/Similar issue:
I saw how this question had been solved by using with for the context, but I'm not quite sure how I'd apply that here, since I'm just trying to specify the return type for a function.
How can I go about specifying the return type in my signature when this type appears to be intertwined with the application's context?
Here is my code:
blueprint = Blueprint('client', __name__, template_folder='templates')
#blueprint.before_request
def load_session_from_cookie():
account = check_sso_cookie(request.cookies, for_view=False)
# if error occurred, return error
if 'message' in account:
session.pop('accountId', None)
return redirect(settings.LOGIN_URL)
if 'accountId' in session:
return redirect(url_for('home'))
elif 'accountId' in account:
session['accountId'] = account.get('accountId')
return redirect(url_for('home'))
else:
session.pop('accountId', None)
return redirect(settings.LOGIN_URL)
Excuse my ignorance, this is my first Flask app that deals with session management. The above code keeps returning the error of RuntimeError: working outside of request context.
Here is the stacktrace:
Traceback (most recent call last):
File "runserver.py", line 1, in <module>
from api import app
File "/Users/dmonsewicz/dev/autoresponders/api/__init__.py", line 13, in <module>
import client
File "/Users/dmonsewicz/dev/autoresponders/api/client/__init__.py", line 33, in <module>
#blueprint.before_request(load_session_from_cookie())
File "/Users/dmonsewicz/dev/autoresponders/api/client/__init__.py", line 16, in load_session_from_cookie
account = check_sso_cookie(request.cookies, for_view=False)
File "/Users/dmonsewicz/.virtualenvs/autoresponders-api/lib/python2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
File "/Users/dmonsewicz/.virtualenvs/autoresponders-api/lib/python2.7/site-packages/werkzeug/local.py", line 297, in _get_current_object
return self.__local()
File "/Users/dmonsewicz/.virtualenvs/autoresponders-api/lib/python2.7/site-packages/flask/globals.py", line 20, in _lookup_req_object
raise RuntimeError('working outside of request context')
Anyone else run into this issue?
You need to register the function, not the return value of the function:
blueprint.before_request(load_session_from_cookie)
Note, no # either. This passes the function object to the blueprint.before_request() registration method.
Your version instead first called the load_session_from_cookie function, and the time your module is loaded, there is no request yet, hence the exception.
The # decorator syntax is normally used before the function definition, and Python will automatically call it for you:
#blueprint.before_request
def load_session_from_cookie():
# ... your function ...
Note that this time we don't call it.
The latter form is the intended syntax, you only need to use the explicit form (the first) if you cannot apply the decorator at module load time (say, because blueprint is loaded dynamically later on, in a blueprint factory function or similar).
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.