Skip to content

Commit

Permalink
ensure Flask's json is called with an app context
Browse files Browse the repository at this point in the history
Fixes #297
  • Loading branch information
miguelgrinberg committed Aug 9, 2016
1 parent 027af38 commit 7aa0611
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions flask_socketio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import socketio
import flask
from flask import json as flask_json
from werkzeug.debug import DebuggedApplication
from werkzeug.serving import run_with_reloader

Expand Down Expand Up @@ -141,6 +142,25 @@ def init_app(self, app, **kwargs):
write_only=write_only)
self.server_options['client_manager'] = queue

if 'json' in self.server_options and \
self.server_options['json'] == flask_json:
# flask's json module is tricky to use because its output
# changes when it is invoked inside or outside the app context
# so here to prevent any ambiguities we replace it with wrappers
# that ensure that the app context is always present
class FlaskSafeJSON(object):
@staticmethod
def dumps(*args, **kwargs):
with app.app_context():
return flask_json.dumps(*args, **kwargs)

@staticmethod
def loads(*args, **kwargs):
with app.app_context():
return flask_json.loads(*args, **kwargs)

self.server_options['json'] = FlaskSafeJSON

resource = kwargs.pop('path', kwargs.pop('resource', 'socket.io'))
if resource.startswith('/'):
resource = resource[1:]
Expand Down

0 comments on commit 7aa0611

Please sign in to comment.