コード例 #1
0
ファイル: websocket.py プロジェクト: danmur/pyramid_sockjs
    def send():
        if session.state == STATE_CLOSING:
            websocket.send(close_frame(3000, 'Go away!'))
            websocket.close()
            session.closed()
            return

        while True:
            try:
                message = [session.get_transport_message(timeout=TIMING)]
            except Empty:
                message = 'h'
                session.heartbeat()
            else:
                message = message_frame(message)

            if session.state == STATE_CLOSING:
                try:
                    websocket.send(close_frame(3000, 'Go away!'))
                    websocket.close()
                except:
                    pass
                session.closed()
                break

            elif session.state == STATE_CLOSED:
                break

            try:
                websocket.send(message)
            except:
                session.close()
                session.closed()
                break
コード例 #2
0
ファイル: websocket.py プロジェクト: Bleno/pyramid_sockjs
    def send():
        if session.state == STATE_CLOSING:
            websocket.send(close_frame(3000, 'Go away!'))
            websocket.close()
            session.closed()
            return

        while True:
            try:
                message = [session.get_transport_message(timeout=TIMING)]
            except Empty:
                message = 'h'
                session.heartbeat()
            else:
                message = message_frame(message)

            if session.state == STATE_CLOSING:
                try:
                    websocket.send(close_frame(3000, 'Go away!'))
                    websocket.close()
                except:
                    pass
                session.closed()
                break

            elif session.state == STATE_CLOSED:
                break

            try:
                websocket.send(message)
            except:
                session.close()
                session.closed()
                break
コード例 #3
0
ファイル: htmlfile.py プロジェクト: DanMauger/pyramid_sockjs
    def __call__(self, environ, start_response):
        request = self.request
        callback = request.GET.get('c', None)
        if callback is None:
            self.status = 500
            self.body = '"callback" parameter required'
            return super(HTMLFileTransport, self).__call__(
                environ, start_response)

        write = start_response(self.status, self.headerlist)
        prelude = PRELUDE % callback.encode('UTF-8')
        prelude += ' ' * 1024
        write(prelude)

        timing = self.timing
        session = self.session

        if session.state == STATE_NEW:
            write('<script>\np("o");\n</script>\r\n')
            session.open()

        size = 0

        try:
            while True:
                try:
                    message = [session.get_transport_message(timeout=timing)]
                except Empty:
                    message = HEARTBEAT
                    session.heartbeat()
                else:
                    message = message_frame(message)

                if session.state == STATE_CLOSING:
                    try:
                        write("<script>\np(%s);\n</script>\r\n" %
                              encode(close_frame('session closed','connection expired')))
                    except Exception as e:
                        print "Error closing html streaming sockjs protocol"
                    session.closed()
                    break

                message = "<script>\np(%s);\n</script>\r\n" % encode(message)
                try:
                    write(message)
                except:
                    session.closed()
                    raise StopStreaming()

                size += len(message)
                if size > self.maxsize:
                    break
        finally:
            session.release()

        return []
コード例 #4
0
    def __call__(self, environ, start_response):
        request = self.request
        callback = request.GET.get('c', None)
        if callback is None:
            self.status = 500
            self.body = '"callback" parameter required'
            return super(HTMLFileTransport,
                         self).__call__(environ, start_response)

        write = start_response(self.status, self.headerlist)
        prelude = PRELUDE % callback
        prelude += ' ' * 1024
        write(prelude)

        timing = self.timing
        session = self.session

        if session.state == STATE_NEW:
            write('<script>\np("o");\n</script>\r\n')
            session.open()

        size = 0

        try:
            while True:
                try:
                    message = [session.get_transport_message(timeout=timing)]
                except Empty:
                    message = HEARTBEAT
                    session.heartbeat()
                else:
                    message = message_frame(message)

                if session.state == STATE_CLOSING:
                    write("<script>\np(%s);\n</script>\r\n" %
                          encode(close_frame('Go away!')))
                    session.closed()
                    break

                message = "<script>\np(%s);\n</script>\r\n" % encode(message)
                try:
                    write(message)
                except:
                    session.closed()
                    raise StopStreaming()

                size += len(message)
                if size > self.maxsize:
                    break
        finally:
            session.release()

        return []
コード例 #5
0
ファイル: eventsource.py プロジェクト: Bleno/pyramid_sockjs
    def __call__(self, environ, start_response):
        write = start_response(
            self.status,
            [('Content-Type','text/event-stream; charset=UTF-8'),
             ('Cache-Control',
              'no-store, no-cache, must-revalidate, max-age=0'),
             session_cookie(self.request)])
        write('\r\n')

        timing = self.timing
        session = self.session

        if session.state == STATE_NEW:
            write("data: o\r\n\r\n")
            session.open()

        size = 0

        try:
            while True:
                try:
                    message = [session.get_transport_message(timeout=timing)]
                except Empty:
                    message = HEARTBEAT
                    session.heartbeat()
                else:
                    message = message_frame(message)

                if session.state == STATE_CLOSING:
                    write("data: %s\r\n\r\n"%close_frame(1000, 'Go away!'))
                    session.closed()
                    break

                if session.state != STATE_OPEN:
                    break

                try:
                    write("data: %s\r\n\r\n" % message)
                except:
                    session.closed()
                    raise StopStreaming()

                size += len(message)
                if size >= self.maxsize:
                    break
        finally:
            session.release()

        return []
コード例 #6
0
    def __call__(self, environ, start_response):
        write = start_response(
            self.status, [('Content-Type', 'text/event-stream; charset=UTF-8'),
                          ('Cache-Control',
                           'no-store, no-cache, must-revalidate, max-age=0'),
                          session_cookie(self.request)])
        write('\r\n')

        timing = self.timing
        session = self.session

        if session.state == STATE_NEW:
            write("data: o\r\n\r\n")
            session.open()

        size = 0

        try:
            while True:
                try:
                    message = [session.get_transport_message(timeout=timing)]
                except Empty:
                    message = HEARTBEAT
                    session.heartbeat()
                else:
                    message = message_frame(message)

                if session.state == STATE_CLOSING:
                    write("data: %s\r\n\r\n" % close_frame(1000, 'Go away!'))
                    session.closed()
                    break

                if session.state != STATE_OPEN:
                    break

                try:
                    write("data: %s\r\n\r\n" % message)
                except:
                    session.closed()
                    raise StopStreaming()

                size += len(message)
                if size >= self.maxsize:
                    break
        finally:
            session.release()

        return []
コード例 #7
0
def get_messages(session, timeout, heartbeat=True):
    messages = []
    try:
        messages.append(session.get_transport_message(timeout=timeout))
        while True:
            try:
                messages.append(session.get_transport_message(block=False))
            except Empty:
                break
    except Empty:
        if heartbeat:
            messages = HEARTBEAT
            session.heartbeat()
        else:
            messages = 'a[]'
    else:
        messages = message_frame(messages, '\n')

    return messages
コード例 #8
0
def JSONPolling(session, request):
    meth = request.method
    response = request.response
    response.headers['Content-Type'] = 'application/javascript; charset=UTF-8'
    response.headerlist.append(
        ('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0'))
    session_cookie(request)

    if session.state == STATE_NEW:
        callback = request.GET.get('c', None)
        if callback is None:
            return HTTPServerError('"callback" parameter required')

        response.text = '%s("o");\r\n' % callback
        session.open()
        session.release()

    elif meth == "GET":
        callback = request.GET.get('c', None)
        if callback is None:
            return HTTPServerError('"callback" parameter required')

        if session.state in (STATE_CLOSING, STATE_CLOSED):
            response.text = "%s(%s);\r\n" % (
                callback, encode(close_frame(3000, 'Go away!')))
            if session.state == STATE_CLOSING:
                session.closed()
        else:
            messages = []
            try:
                messages.append(session.get_transport_message(timeout=timing))
                while True:
                    try:
                        messages.append(
                            session.get_transport_message(block=False))
                    except Empty:
                        break

            except Empty:
                messages = HEARTBEAT
                session.heartbeat()
            else:
                messages = message_frame(messages)

            response.text = "%s(%s);\r\n" % (callback, encode(messages))

        session.release()

    elif meth == "POST":
        data = request.body_file.read()

        ctype = request.headers.get('Content-Type', '').lower()
        if ctype == 'application/x-www-form-urlencoded':
            if not data.startswith('d='):
                return HTTPServerError("Payload expected.")

            data = unquote_plus(data[2:])

        if not data:
            return HTTPServerError("Payload expected.")

        try:
            messages = decode(data)
        except:
            return HTTPServerError("Broken JSON encoding.")

        for msg in messages:
            session.message(msg)

        response.status = 200
        response.headers['Content-Type'] = 'text/plain; charset=UTF-8'
        response.body = 'ok'
    else:
        raise Exception("No support for such method: %s" % meth)

    return response
コード例 #9
0
ファイル: xhrstreaming.py プロジェクト: Bleno/pyramid_sockjs
    def __call__(self, environ, start_response):
        request = self.request
        if request.method == 'OPTIONS':
            self.status = 204
            self.content_type = 'application/javascript; charset=UTF-8'
            self.headerlist.append(
                ("Access-Control-Allow-Methods", "OPTIONS, POST"))
            self.headerlist.extend(cache_headers(request))
            return super(XHRStreamingTransport, self).__call__(
                environ, start_response)

        write = start_response(
            self.status, self._abs_headerlist(environ))
        write(self.open_seq)

        session = self.session

        #if session.state == STATE_CLOSED:
        #    write('%s\n'%close_frame(1002, "Connection interrupted"))
        #    return ()

        try:
            session.acquire(self.request)
        except: # should use specific exception
            write(close_frame(2010, "Another connection still open", '\n'))
            return ()

        if session.state == STATE_NEW:
            write(OPEN)
            session.open()

        if session.state in (STATE_CLOSING, STATE_CLOSED):
            write(close_frame(3000, 'Go away!', '\n'))
            if session.state == STATE_CLOSING:
                session.closed()
            return ()

        stream_size = 0
        timing = self.timing

        try:
            while True:
                try:
                    message = [session.get_transport_message(timeout=timing)]
                except Empty:
                    message = HEARTBEAT
                    session.heartbeat()
                else:
                    message = message_frame(message, '\n')

                if session.state == STATE_CLOSING:
                    write(close_frame(3000, 'Go away!', '\n'))
                    session.closed()
                    raise StopStreaming()

                if session.state != STATE_OPEN:
                    break

                try:
                    write(message)
                except:
                    session.closed()
                    raise StopStreaming()

                stream_size += len(message)
                if stream_size > self.maxsize:
                    break
        finally:
            session.release()

        return []
コード例 #10
0
    def test_message_frame_endline(self):
        from pyramid_sockjs import protocol

        msg = protocol.message_frame(['msg1', 'msg2'], '\n')
        self.assertEqual(msg, 'a%s\n' % protocol.encode(['msg1', 'msg2']))
コード例 #11
0
ファイル: test_protocol.py プロジェクト: Bleno/pyramid_sockjs
    def test_message_frame_endline(self):
        from pyramid_sockjs import protocol

        msg = protocol.message_frame(['msg1', 'msg2'], '\n')
        self.assertEqual(msg, 'a%s\n'%protocol.encode(['msg1', 'msg2']))
コード例 #12
0
    def __call__(self, environ, start_response):
        request = self.request
        if request.method == 'OPTIONS':
            self.status = 204
            self.content_type = 'application/javascript; charset=UTF-8'
            self.headerlist.append(
                ("Access-Control-Allow-Methods", "OPTIONS, POST"))
            self.headerlist.extend(cache_headers(request))
            return super(XHRStreamingTransport,
                         self).__call__(environ, start_response)

        write = start_response(self.status, self._abs_headerlist(environ))
        write(self.open_seq)

        session = self.session

        #if session.state == STATE_CLOSED:
        #    write('%s\n'%close_frame(1002, "Connection interrupted"))
        #    return ()

        try:
            session.acquire(self.request)
        except:  # should use specific exception
            write(close_frame(2010, "Another connection still open", '\n'))
            return ()

        if session.state == STATE_NEW:
            write(OPEN)
            session.open()

        if session.state in (STATE_CLOSING, STATE_CLOSED):
            write(close_frame(3000, 'Go away!', '\n'))
            if session.state == STATE_CLOSING:
                session.closed()
            return ()

        stream_size = 0
        timing = self.timing

        try:
            while True:
                try:
                    message = [session.get_transport_message(timeout=timing)]
                except Empty:
                    message = HEARTBEAT
                    session.heartbeat()
                else:
                    message = message_frame(message, '\n')

                if session.state == STATE_CLOSING:
                    write(close_frame(3000, 'Go away!', '\n'))
                    session.closed()
                    raise StopStreaming()

                if session.state != STATE_OPEN:
                    break

                try:
                    write(message)
                except:
                    session.closed()
                    raise StopStreaming()

                stream_size += len(message)
                if stream_size > self.maxsize:
                    break
        finally:
            session.release()

        return []
コード例 #13
0
ファイル: jsonp.py プロジェクト: Bleno/pyramid_sockjs
def JSONPolling(session, request):
    meth = request.method
    response = request.response
    response.headers['Content-Type'] = 'application/javascript; charset=UTF-8'
    response.headerlist.append(
        ('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0'))
    session_cookie(request)

    if session.state == STATE_NEW:
        callback = request.GET.get('c', None)
        if callback is None:
            return HTTPServerError('"callback" parameter required')

        response.text = '%s("o");\r\n' % callback
        session.open()
        session.release()

    elif meth == "GET":
        callback = request.GET.get('c', None)
        if callback is None:
            return HTTPServerError('"callback" parameter required')

        if session.state in (STATE_CLOSING, STATE_CLOSED):
            response.text = "%s(%s);\r\n"%(
                callback, encode(close_frame(3000, 'Go away!')))
            if session.state == STATE_CLOSING:
                session.closed()
        else:
            messages = []
            try:
                messages.append(session.get_transport_message(timeout=timing))
                while True:
                    try:
                        messages.append(
                            session.get_transport_message(block=False))
                    except Empty:
                        break

            except Empty:
                messages = HEARTBEAT
                session.heartbeat()
            else:
                messages = message_frame(messages)

            response.text = "%s(%s);\r\n"%(callback, encode(messages))

        session.release()

    elif meth == "POST":
        data = request.body_file.read()

        ctype = request.headers.get('Content-Type', '').lower()
        if ctype == 'application/x-www-form-urlencoded':
            if not data.startswith('d='):
                return HTTPServerError("Payload expected.")

            data = unquote_plus(data[2:])

        if not data:
            return HTTPServerError("Payload expected.")

        try:
            messages = decode(data)
        except:
            return HTTPServerError("Broken JSON encoding.")

        for msg in messages:
            session.message(msg)

        response.status = 200
        response.headers['Content-Type'] = 'text/plain; charset=UTF-8'
        response.body = 'ok'
    else:
        raise Exception("No support for such method: %s"%meth)

    return response