4

I would like to be able to use a Flask request out of context.

I realise since Flask 0.10 there is a decorator(@copy_current_request_context) available to do that, and this is how I am using that decorator to try and modify flask-socket . Specifically the @socket.route decorator which is part of flask-sockets:

def route(self, rule, request, **options):

    def decorator(f):
        endpoint = options.pop('endpoint', None)
        @copy_current_request_context
        def do_some_work():
            env = request.environ['wsgi.websocket']
            self.add_url_rule(rule, endpoint, f,env, **options)
        gevent.spawn(do_some_work)
        return f
    return decorator

Although the error this produces does make sense to me - I am assuming there's a way to do what I want.:

RuntimeError: This decorator can only be used at local scopes when a   
request context is on the stack.  For instance within view functions.

I tried passing the request into the decorator, but that didn't work.

To give a little more context, I am trying to add the request.environ['wsgi.websocket'] to a dict inside the Sockets object to be able to access the ws variable (which I understand to be the request environment).

On a higher level, I'd like the ability to do ws.send() from somewhere other than the @route function or view - perhaps another thread that has access to the socket object instance.

I've done something similar with Socket-IO - where the socketio object is all you need to be able to send() and recieve() data - however with Sockets it seems you need the ws object, which is the request.environ['wsgi.websocket']

doru
  • 9,022
  • 2
  • 33
  • 43
Colin Riddell
  • 407
  • 4
  • 17

0 Answers0