示例#1
0
 def test_rpc(self):
     '''Send a message to the rpc'''
     loop = self.http._loop
     ws = yield from self.http.get(self.ws, websocket_handler=Message(loop))
     self.assertEqual(ws.status_code, 101)
     ws.write('Hello there!')
     data = yield from ws.handler.get()
     data = json.loads(data)
     self.assertEqual(data['message'], 'Hello there!')
     result = yield from self.rpc.message('Hi!')
     self.assertEqual(result, 'OK')
     data = yield from ws.handler.get()
     data = json.loads(data)
     self.assertEqual(data['message'], 'Hi!')
示例#2
0
文件: tests.py 项目: japaks/pulsar
 def test_rpc(self):
     '''Send a message to the rpc'''
     ws = yield self.http.get(self.ws,
                              websocket_handler=MessageHandler()).on_headers
     self.assertEqual(ws.handshake.status_code, 101)
     ws.write('Hello there!')
     data = yield ws.handler.get()
     data = json.loads(data)
     self.assertEqual(data['message'], 'Hello there!')
     result = yield self.rpc.message('Hi!')
     self.assertEqual(result, 'OK')
     data = yield ws.handler.get()
     data = json.loads(data)
     self.assertEqual(data['message'], 'Hi!')
示例#3
0
 def test_rpc(self):
     '''Send a message to the rpc'''
     ws = yield self.http.get(self.ws,
                              websocket_handler=MessageHandler()
                              ).on_headers
     self.assertEqual(ws.handshake.status_code, 101)
     ws.write('Hello there!')
     data = yield ws.handler.get()
     data = json.loads(data)
     self.assertEqual(data['message'], 'Hello there!')
     result = yield self.rpc.message('Hi!')
     self.assertEqual(result, 'OK')
     data = yield ws.handler.get()
     data = json.loads(data)
     self.assertEqual(data['message'], 'Hi!')
示例#4
0
 def _data_and_files(self, data=True, files=True, future=None):
     result = {}, None
     chunk = None
     if future is None:
         stream = self.environ.get('wsgi.input')
         if self.method not in ENCODE_URL_METHODS and stream:
             chunk = stream.read()
             if isinstance(chunk, Future):
                 return chain_future(
                     chunk, partial(self._data_and_files, data, files))
     else:
         chunk = future
     if chunk is not None:
         content_type, options = self.content_type_options
         charset = options.get('charset', 'utf-8')
         if content_type in JSON_CONTENT_TYPES:
             result = json.loads(chunk.decode(charset)), None
         elif content_type:
             self.environ['wsgi.input'] = BytesIO(chunk)
             result = parse_form_data(self.environ, charset)
         else:
             result = chunk, None
         self.environ['wsgi.input'] = BytesIO(chunk)
     self.cache.data_and_files = result
     return self.data_and_files(data, files)
示例#5
0
 def _ready(self, data):
     self.environ['wsgi.input'] = BytesIO(data)
     try:
         self.result = (json.loads(data.decode(self.charset)), None)
     except Exception as exc:
         raise BadRequest('Could not decode JSON') from exc
     return self.result
示例#6
0
文件: twitter.py 项目: Danzeer/pulsar
 def process_data(self, response, **kw):
     '''Callback passed to :class:`HttpClient` for processing
     streaming data.
     '''
     if response.status_code == 200:
         messages = []
         data = response.recv_body()
         while data:
             idx = data.find(b'\r\n')
             if idx < 0:     # incomplete data - add to buffer
                 self.buffer.append(data)
                 data = None
             else:
                 self.buffer.append(data[:idx])
                 data = data[idx+2:]
                 msg = b''.join(self.buffer)
                 self.buffer = []
                 if msg:
                     body = json.loads(msg.decode('utf-8'))
                     if 'disconnect' in body:
                         msg = body['disconnect']
                         self.logger.warning('Disconnecting (%d): %s',
                                             msg['code'], msg['reason'])
                     elif 'warning' in body:
                         message = body['warning']['message']
                         self.logger.warning(message)
                     else:
                         messages.append(body)
         if messages:
             # a list of messages is available
             if self.cfg.callable:
                 self.cfg.callable(self, messages)
示例#7
0
 def _data_and_files(self, data=True, files=True, future=None):
     result = {}, None
     chunk = None
     if future is None:
         stream = self.environ.get('wsgi.input')
         if self.method not in ENCODE_URL_METHODS and stream:
             chunk = stream.read()
             if isinstance(chunk, Future):
                 return chain_future(
                     chunk, partial(self._data_and_files, data, files))
     else:
         chunk = future
     if chunk is not None:
         content_type, options = self.content_type_options
         charset = options.get('charset', 'utf-8')
         if content_type in JSON_CONTENT_TYPES:
             result = json.loads(chunk.decode(charset)), None
         elif content_type:
             self.environ['wsgi.input'] = BytesIO(chunk)
             result = parse_form_data(self.environ, charset)
         else:
             result = chunk, None
         self.environ['wsgi.input'] = BytesIO(chunk)
     self.cache.data_and_files = result
     return self.data_and_files(data, files)
示例#8
0
 def _ready(self, data):
     self.environ['wsgi.input'] = BytesIO(data)
     try:
         self.result = (json.loads(data.decode(self.charset)), None)
     except Exception as exc:
         raise BadRequest('Could not decode JSON') from exc
     return self.result
示例#9
0
 def process_data(self, response, **kw):
     if response.status_code == 200:
         messages = []
         data = response.recv_body()
         while data:
             idx = data.find(b'\r\n')
             if idx < 0:
                 self.buffer.append(data)
                 data = None
             else:
                 self.buffer.append(data[:idx])
                 data = data[idx + 2:]
                 msg = b''.join(self.buffer)
                 self.buffer = []
                 if msg:
                     body = json.loads(msg.decode('utf-8'))
                     if 'disconnect' in body:
                         msg = body['disconnect']
                         self.logger.warning('Disconnecting (%d): %s',
                                             msg['code'], msg['reason'])
                     elif 'warning' in body:
                         message = body['warning']['message']
                         self.logger.warning(message)
                     else:
                         messages.append(body)
         if messages:
             # a list of messages is available
             if self.cfg.callable:
                 self.cfg.callable(self, messages)
示例#10
0
文件: test.py 项目: quantmind/lux
 def parse_frame(self, websocket, frame):
     parser = frame_parser(kind=1)
     frame = parser.decode(frame)
     wsclient = websocket.cache.wsclient
     websocket.connection.reset_mock()
     msg = _json.loads(frame.body[1:])[0]
     return wsclient.protocol.decode(msg)
示例#11
0
文件: store.py 项目: huobao36/pulsar
 def design_delete(self, name):
     '''Delete an existing design document at ``name``.
     '''
     response = yield self.request('head', self._database, '_design', name)
     if response.status_code == 200:
         rev = json.loads(response.headers['etag'])
         yield self.request('delete', self._database, '_design', name,
                            rev=rev)
示例#12
0
 def on_message(self, websocket, msg):
     request = websocket.request
     client = request.cache.mailclient
     if msg and client:
         msg = json.loads(msg)
         if 'mailbox' in msg:
             mailbox = yield client.examine(msg['mailbox'])
             self.write(request, json.dumps({'mailbox': mailbox}))
示例#13
0
文件: manage.py 项目: robgil/pulsar
 def on_message(self, websocket, msg):
     request = websocket.request
     client = request.cache.mailclient
     if msg and client:
         msg = json.loads(msg)
         if 'mailbox' in msg:
             mailbox = yield client.examine(msg['mailbox'])
             self.write(request, json.dumps({'mailbox': mailbox}))
示例#14
0
文件: app.py 项目: huobao36/pulsar
 def test_websocket(self):
     ws = yield self.http.get(self.ws, websocket_handler=MessageHandler())
     response = ws.handshake
     self.assertEqual(response.status_code, 101)
     self.assertEqual(response.headers["upgrade"], "websocket")
     self.assertEqual(response.connection, ws.connection)
     self.assertTrue(ws.connection)
     self.assertIsInstance(ws.handler, MessageHandler)
     #
     data = yield ws.handler.get()
     data = json.loads(data)
     self.assertEqual(data["message"], "joined")
     #
     ws.write("Hello there!")
     data = yield ws.handler.get()
     data = json.loads(data)
     self.assertEqual(data["message"], "Hello there!")
示例#15
0
 def test_websocket(self):
     ws = yield self.http.get(self.ws, websocket_handler=MessageHandler()
                              ).on_headers
     self.assertTrue(ws)
     self.assertIsInstance(ws.handler, MessageHandler)
     ws.write('Hello there!')
     data = yield ws.handler.get()
     data = json.loads(data)
     self.assertEqual(data['message'], 'Hello there!')
示例#16
0
 def test_websocket(self):
     c = self.http
     ws = yield c.get(self.ws, websocket_handler=MessageHandler(c._loop))
     response = ws.handshake
     self.assertEqual(response.status_code, 101)
     self.assertEqual(response.headers['upgrade'], 'websocket')
     self.assertEqual(response.connection, ws.connection)
     self.assertTrue(ws.connection)
     self.assertIsInstance(ws.handler, MessageHandler)
     #
     data = yield ws.handler.get()
     data = json.loads(data)
     self.assertEqual(data['message'], 'joined')
     #
     ws.write('Hello there!')
     data = yield ws.handler.get()
     data = json.loads(data)
     self.assertEqual(data['message'], 'Hello there!')
示例#17
0
文件: app.py 项目: azazel75/pulsar
 def test_websocket(self):
     c = self.http
     ws = yield c.get(self.ws, websocket_handler=MessageHandler(c._loop))
     response = ws.handshake
     self.assertEqual(response.status_code, 101)
     self.assertEqual(response.headers['upgrade'], 'websocket')
     self.assertEqual(response.connection, ws.connection)
     self.assertTrue(ws.connection)
     self.assertIsInstance(ws.handler, MessageHandler)
     #
     data = yield ws.handler.get()
     data = json.loads(data)
     self.assertEqual(data['message'], 'joined')
     #
     ws.write('Hello there!')
     data = yield ws.handler.get()
     data = json.loads(data)
     self.assertEqual(data['message'], 'Hello there!')
示例#18
0
 def to_python(self, value, store=None):
     if value is None:
         return self.get_default()
     if isinstance(value, str):
         try:
             return json.loads(value)
         except TypeError:
             return None
     else:
         return value
示例#19
0
文件: fields.py 项目: robgil/pulsar
 def to_python(self, value, store=None):
     if value is None:
         return self.get_default()
     if isinstance(value, str):
         try:
             return json.loads(value)
         except TypeError:
             return None
     else:
         return value
示例#20
0
文件: store.py 项目: robgil/pulsar
 def design_delete(self, name):
     '''Delete an existing design document at ``name``.
     '''
     response = yield self.request('head', self._database, '_design', name)
     if response.status_code == 200:
         rev = json.loads(response.headers['etag'])
         yield self.request('delete',
                            self._database,
                            '_design',
                            name,
                            rev=rev)
示例#21
0
def media_libraries():
    global _media_libraries
    if _media_libraries is None:
        if os.path.isfile('libs.json'):  # pragma    nocover
            with open('libs.json') as f:
                data = f.read()
            _media_libraries = json.loads(data)
        else:
            from pulsar import new_event_loop
            from pulsar.apps.http import HttpClient
            http = HttpClient(loop=new_event_loop())
            try:
                response = http.get(_libs_url)
                _media_libraries = response.json()
            except Exception:  # pragma    nocover
                http.logger.error('Could not import media library',
                                  exc_info=True)
                _media_libraries = {'libs': {}, 'deps': {}}
    return _media_libraries
示例#22
0
 def _data_and_files(self):
     result = {}, None
     stream = self.environ.get('wsgi.input')
     try:
         if self.method not in ENCODE_URL_METHODS and stream:
             chunk = yield stream.read()
             content_type, options = self.content_type_options
             charset = options.get('charset', 'utf-8')
             if content_type in JSON_CONTENT_TYPES:
                 result = json.loads(chunk.decode(charset)), None
             else:
                 self.environ['wsgi.input'] = BytesIO(chunk)
                 result = parse_form_data(self.environ, charset)
             # set the wsgi.input to a readable file-like object for
             # third-parties application (django or any other web-framework)
             self.environ['wsgi.input'] = BytesIO(chunk)
     finally:
         self._cached_data_and_files = result
     coroutine_return(result)
示例#23
0
def media_libraries():
    global _media_libraries
    if _media_libraries is None:
        if os.path.isfile('libs.json'):     # pragma    nocover
            with open('libs.json') as f:
                data = f.read()
            _media_libraries = json.loads(data)
        else:
            from pulsar import new_event_loop
            from pulsar.apps.http import HttpClient
            http = HttpClient(loop=new_event_loop())
            try:
                response = http.get(_libs_url)
                _media_libraries = response.json()
            except Exception:   # pragma    nocover
                http.logger.error('Could not import media library',
                                  exc_info=True)
                _media_libraries = {'libs': {}, 'deps': {}}
    return _media_libraries
示例#24
0
 def _data_and_files(self, data=True, files=True):
     result = {}, None
     stream = self.environ.get("wsgi.input")
     chunk = None
     try:
         if self.method not in ENCODE_URL_METHODS and stream:
             chunk = stream.read()
             if isinstance(chunk, Future):
                 chunk = yield chunk
             content_type, options = self.content_type_options
             charset = options.get("charset", "utf-8")
             if content_type in JSON_CONTENT_TYPES:
                 result = json.loads(chunk.decode(charset)), None
             else:
                 self.environ["wsgi.input"] = BytesIO(chunk)
                 result = parse_form_data(self.environ, charset)
     finally:
         self.cache.data_and_files = result
         if chunk is not None:
             self.environ["wsgi.input"] = BytesIO(chunk)
     coroutine_return(self.data_and_files(data, files))
示例#25
0
 def json(self, charset=None):
     '''Decode content as a JSON object.'''
     return json.loads(self.content_string(charset))
示例#26
0
 def json(self, charset=None):
     """Decode content as a JSON object.
     """
     return _json.loads(self.text(charset))
示例#27
0
文件: __init__.py 项目: arhik/pulsar
 def json(self, charset=None):
     """Decode content as a JSON object.
     """
     return json.loads(self.text(charset))
示例#28
0
 def json(self):
     """Decode content as a JSON object.
     """
     return _json.loads(self.text)
示例#29
0
 def xhr_send(self, request):
     data = yield request.body_data()
     msg = json.loads(data)
     self.handle.on_message(WebSocketProxy(request), msg)
     request.response.status_code = 204
     return request.response
示例#30
0
 def _ready(self, data):
     self.result = (json.loads(data.decode(self.charset)), None)
     return self.result
示例#31
0
 def _ready(self, data):
     self.environ["wsgi.input"] = BytesIO(data)
     self.result = (json.loads(data.decode(self.charset)), None)
     return self.result
示例#32
0
 def __call__(self, channels, message):
     self.callback(json.loads(message))
示例#33
0
 def json(self, charset=None):
     '''Decode content as a JSON object.'''
     return json.loads(self.content_string(charset))
示例#34
0
文件: views.py 项目: pombredanne/lux
 def xhr_send(self, request):
     data = yield request.body_data()
     msg = json.loads(data)
     self.handle.on_message(WebSocketProxy(request), msg)
     request.response.status_code = 204
     return request.response
示例#35
0
 def load(cls, data, method=None):
     method = method or 'json'
     if method == 'json':
         return cls(**json.loads(to_string(data)))
     else:
         raise ImproperlyConfigured('Unknown serialisation "%s"' % method)
示例#36
0
 def __call__(self, channels, message):
     self.callback(json.loads(message))
示例#37
0
 def json(self):
     """Decode content as a JSON object.
     """
     return _json.loads(self.text)
示例#38
0
def load_pkg(name, dir=None):
    p = os.path
    dir = dir or JS_DIR
    with open(os.path.join(dir, name)) as f:
        data = f.read()
    return json.loads(data)