Skip to content

Commit 1a5e4af

Browse files
committed
websocket handler calls are automatically wrapped inside the flask
application and request context (thanks to Mark Hildreth http://stackoverflow.com/a/18522837 for the tip)
1 parent 0424c50 commit 1a5e4af

File tree

3 files changed

+25
-9
lines changed

3 files changed

+25
-9
lines changed

README.rst

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -147,16 +147,20 @@ WebSocket client abstraction with fully non-blocking methods.
147147
``connected``
148148

149149

150-
Advanced Usage
151-
--------------
152-
Normally websocket routes happen outside of the normal request context. You can
153-
get a request context in your websocket handler by using
154-
``app.request_context``::
150+
Application and Request Context
151+
-------------------------------
152+
153+
The ``flask_uwsgi_websocket.GeventWebSocketMiddleware`` automatically wraps the
154+
websocket handler call inside the flask application and request context.
155+
This means the ``flask.current_app`` and ``flask.request`` LocalProxy instances
156+
will be bounded and all Flask extensions activated::
157+
158+
from flask import current_app, request
155159

156160
app = Flask(__name__)
157161
ws = GeventWebSocket(app)
158162

159163
@ws.route('/websocket')
160164
def websocket(ws):
161-
with app.request_context(ws.environ):
162-
print request.args
165+
print current_app #<Flask>
166+
print request #<Request 'http://localhost:5000/websocket' [GET]>

flask_uwsgi_websocket/_gevent.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from flask import current_app
2+
13
from gevent import killall, sleep, spawn, wait
24
from gevent.event import Event
35
from gevent.queue import Queue
@@ -57,7 +59,7 @@ def __call__(self, environ, start_response):
5759
send_queue, recv_event, recv_queue, self.websocket.timeout)
5860

5961
# spawn handler
60-
handler = spawn(handler, client)
62+
handler = spawn(handler_context_wrapper, handler, client, self.websocket.app)
6163

6264
# spawn recv listener
6365
def listener(client):
@@ -100,3 +102,13 @@ def listener(client):
100102

101103
class GeventWebSocket(WebSocket):
102104
middleware = GeventWebSocketMiddleware
105+
106+
107+
def handler_context_wrapper(handler, client, app):
108+
with app.app_context():
109+
#now flask.current_app will be bound :)
110+
with current_app.request_context(client.environ):
111+
#and now flask.request is bound, should the handler need it :)
112+
handler(client)
113+
114+

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
setup(
55
name='Flask-uWSGI-WebSocket',
6-
version='0.2.5',
6+
version='0.2.5.1',
77
url='https://github.com/zeekay/flask-uwsgi-websocket',
88
license='MIT',
99
author='Zach Kelling',

0 commit comments

Comments
 (0)