本文整理汇总了Python中msgpack.packb函数的典型用法代码示例。如果您正苦于以下问题:Python packb函数的具体用法?Python packb怎么用?Python packb使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了packb函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: process_request
def process_request():
frames = socket.recv_multipart()
# killed by gsd
i = frames.index('')
command = frames[i + 2]
if command == '\x02':
global interrupted
interrupted = True
return
i = frames.index('', 1)
sequence, timestamp, expiry = msgpack.unpackb(frames[i+1])
method = frames[i+2]
params = msgpack.unpackb(frames[i+3])
try:
global converter
ret = getattr(converter, method)(*params)
except:
ret = ''
frames = frames[:i+1]
now = int(round(time.time() * 1000))
frames.append(msgpack.packb([sequence, now, 200]))
frames.append(msgpack.packb(ret))
socket.send_multipart(frames)
开发者ID:yaobiqing0424,项目名称:pinyin4py,代码行数:29,代码来源:pinyin-demowrk.py
示例2: serve
def serve(self):
# Make stdin non-blocking
fl = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, fl | os.O_NONBLOCK)
# Make stdout blocking
fl = fcntl.fcntl(sys.stdout.fileno(), fcntl.F_GETFL)
fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, fl & ~os.O_NONBLOCK)
unpacker = msgpack.Unpacker(use_list=False)
while True:
r, w, es = select.select([sys.stdin], [], [], 10)
if r:
data = os.read(sys.stdin.fileno(), BUFSIZE)
if not data:
return
unpacker.feed(data)
for type, msgid, method, args in unpacker:
method = method.decode('ascii')
try:
try:
f = getattr(self, method)
except AttributeError:
f = getattr(self.repository, method)
res = f(*args)
except Exception as e:
sys.stdout.buffer.write(msgpack.packb((1, msgid, e.__class__.__name__, e.args)))
else:
sys.stdout.buffer.write(msgpack.packb((1, msgid, None, res)))
sys.stdout.flush()
if es:
return
开发者ID:copart,项目名称:attic,代码行数:30,代码来源:remote.py
示例3: test_msgpack_fifo
def test_msgpack_fifo(self):
import msgpack
v1 = [1, 2, 3, 4]
v2 = [5, 6, 7, 8]
v3 = {b"a": 9, b"b": 10, b"c": 11}
s1 = msgpack.packb(v1)
s2 = msgpack.packb(v2)
s3 = msgpack.packb(v3)
unpacker = msgpack.Unpacker()
unpacker.feed(s1)
unpacker.feed(s2)
unpacker.feed(s3[:4])
assert next(iter(unpacker)) == v1
assert next(iter(unpacker)) == v2
try:
next(iter(unpacker))
except StopIteration:
pass
else:
raise Exception("must fail")
unpacker.feed(s3[4:])
assert next(iter(unpacker)) == v3
开发者ID:JacekPliszka,项目名称:spyne,代码行数:27,代码来源:test_util.py
示例4: default
def default(obj):
# Serialize Bn objects
if isinstance(obj, Bn):
if obj < 0:
neg = b"-"
data = (-obj).binary()
else:
neg = b"+"
data = obj.binary()
return msgpack.ExtType(0, neg + data)
# Serialize EcGroup objects
elif isinstance(obj, EcGroup):
nid = obj.nid()
packed_nid = msgpack.packb(nid)
return msgpack.ExtType(1, packed_nid)
# Serialize EcPt objects
elif isinstance(obj, EcPt):
nid = obj.group.nid()
data = obj.export()
packed_nid = msgpack.packb((nid, data))
return msgpack.ExtType(2, packed_nid)
raise TypeError("Unknown type: %r" % (obj,))
开发者ID:lucamelis,项目名称:petlib,代码行数:25,代码来源:pack.py
示例5: call
def call(self, command, params=None):
"""
Sends the provided command to Serf for evaluation, with
any parameters as the message body.
"""
if self._socket is None:
raise SerfConnectionError('handshake must be made first')
header = msgpack.packb({"Seq": self._counter(), "Command": command})
if params is not None:
body = msgpack.packb(params)
self._socket.sendall(header + body)
else:
self._socket.sendall(header)
unpacker = msgpack.Unpacker()
unpacker.feed(self._socket.recv(4096))
response = SerfResult()
for item in unpacker:
if response.head is None:
response.head = item
else:
response.body = item
break
return response
开发者ID:paha,项目名称:serfclient-py,代码行数:28,代码来源:connection.py
示例6: on_heartbeat
def on_heartbeat(w):
global i
i += 1
w.write(msgpack.packb([1, 0, []]))
w.write(msgpack.packb([3, i, ["echo"]]))
w.write(msgpack.packb([4, i, ["echo"]]))
w.write(msgpack.packb([6, i, []]))
开发者ID:rmoorman,项目名称:cocaine-framework-python,代码行数:7,代码来源:runtime.py
示例7: test_roundtrip_deferred
def test_roundtrip_deferred(self):
from twisted.internet import reactor
from twisted.internet.task import deferLater
v = "yaaay!"
p_ctx = []
class SomeService(ServiceBase):
@rpc(Unicode, _returns=Unicode)
def yay(ctx, u):
def _cb():
return u
p_ctx.append(ctx)
return deferLater(reactor, 0.1, _cb)
app = Application([SomeService], 'tns',
in_protocol=MessagePackDocument(),
out_protocol=MessagePackDocument())
prot = self.gen_prot(app)
request = msgpack.packb({'yay': [v]})
def _ccb(_):
val = prot.transport.value()
print repr(val)
val = msgpack.unpackb(val)
print repr(val)
self.assertEquals(val, [0, msgpack.packb(v)])
prot.dataReceived(msgpack.packb([1, request]))
return p_ctx[0].out_object[0].addCallback(_ccb)
开发者ID:codenginebd,项目名称:spyne,代码行数:31,代码来源:test_msgpack.py
示例8: count
def count(doc):
if attr == '__meta__':
return len(msgpack.packb(doc.doc))
for i, (name, klass, nelem) in enumerate(doc.stores):
if name == attr:
return len(msgpack.packb(doc.instances[i]))
return 0
开发者ID:schwa-lab,项目名称:dr-apps-python,代码行数:7,代码来源:stat.py
示例9: _serialize_context
def _serialize_context(context):
# Our sending format is made up of two messages. The first has a
# quick to unpack set of meta data that our collector is going to
# use for routing and stats. This is much faster than having the
# collector decode the whole event. We're just going to use python
# struct module to make a quick and dirty data structure
context_dict = context.to_dict()
for key in ("host", "type"):
if len(context_dict.get(key, "")) > 64:
raise ValueError("Value too long: %r" % key)
meta_data = struct.pack(
META_STRUCT_FMT, META_STRUCT_VERSION, context_dict["end"], context_dict["host"], context_dict["type"]
)
try:
context_data = msgpack.packb(context_dict)
except TypeError:
try:
# If we fail to serialize our context, we can try again with an
# enhanced packer (it's slower though)
context_data = msgpack.packb(context_dict, default=utils.msgpack_encode_default)
except TypeError:
log.exception("Serialization failure (not fatal, dropping data)")
# One last try after dropping the body
context_dict["body"] = None
context_data = msgpack.packb(context_dict)
return meta_data, context_data
开发者ID:postmates,项目名称:BlueOx,代码行数:30,代码来源:network.py
示例10: aggregate_host
def aggregate_host(request, response):
raw = yield request.read()
TASK = msgpack.unpackb(raw)
taskId = TASK['id']
logger = get_logger_adapter(taskId)
logger.info("Handle task")
cfg = TASK['config'] # config of aggregator
token = TASK['token']
prtime = TASK['prevtime']
currtime = TASK['currtime']
dg = MysqlDG.get_service(DATABASEAPP)
q = TABLEREGEX.sub(token, cfg['query'])
q = TIMEREGEX.sub("1=1", q)
logger.debug("QUERY: %s", q)
pickled_res = yield dg.enqueue("query",
msgpack.packb((token, q)))
res = cPickle.loads(pickled_res)
logger.debug(str(res))
try:
ret = float(res[0][0]) # SELECT COUNT(*)
logger.info("Result from DG %s", ret)
if cfg.get('rps'):
ret = ret / (currtime - prtime)
except Exception:
ret = 0
logger.info("%s", ret)
response.write(msgpack.packb(ret))
response.close()
开发者ID:gitter-badger,项目名称:Combaine,代码行数:28,代码来源:average.py
示例11: handle
def handle(self):
try:
logger.debug("(self:{}) ->".format(self))
while 1:
try:
buffer = self.read(4)
size = struct.unpack("<L", buffer)[0]
try:
if self.server.serialization == "json":
cmd, params = json.loads(self.read(size))
if params is not None:
packet = json.dumps(getattr(self.server.instance, cmd)(params))
else:
packet = json.dumps(getattr(self.server.instance, cmd)())
else:
cmd, params = msgpack.unpackb(self.read(size), encoding='utf-8')
packet = msgpack.packb((0, getattr(self.server.instance, cmd)(*params)), use_bin_type=True)
except:
result = traceback.format_exc()
logger.error(result)
packet = msgpack.packb((2, result), use_bin_type=True)
self.request.sendall(struct.pack("<L", len(packet)) + packet)
except self.EndConnection:
return
except socket.error as e:
logger.error(e)
return
finally:
logger.debug("handle(self:{}) <-".format(self))
开发者ID:AlexLexx706,项目名称:SampleRPC,代码行数:32,代码来源:server.py
示例12: get_payload
def get_payload(self):
# Fill up send_queue with new messages until full.
try:
for i in xrange(self.send_queue_size - len(self.send_queue)):
self.send_queue.append(self.main_queue.get_nowait())
self.main_queue.task_done()
except Queue.Empty:
pass
if not len(self.send_queue):
return '', 0
# self.log("info",
# "Trying to pack queue with {} messages.".format(
# len(self.send_queue)
# )
# )
# Pack messages and try to fit into limit.
msg = msgpack.packb({'data': self.send_queue})
msg_len = len(self.send_queue)
while len(msg) > self.config['max_msg_size_bytes']:
self.measr_avg_size = len(msg) / len(self.send_queue)
self.update_queue_size()
msg = msgpack.packb(
{'data': self.send_queue[:self.send_queue_size]}
)
msg_len = self.send_queue_size
# self.log(
# "info",
# "Packed {} messages with total size {} bytes. {} messages in"
# " the send_queue left.".format(msg_len, len(msg),
# len(self.send_queue))
# )
return msg, msg_len
开发者ID:adanin,项目名称:WallarmApiWriter,代码行数:35,代码来源:wallarm_api_writer.py
示例13: send
def send(self, message):
if config.debug_socket: self.log("Send: %s, to: %s, site: %s, inner_path: %s, req_id: %s" % (message.get("cmd"), message.get("to"), message.get("params", {}).get("site"), message.get("params", {}).get("inner_path"), message.get("req_id")))
self.last_send_time = time.time()
if self.protocol == "zeromq":
if self.zmq_sock: # Outgoing connection
self.zmq_queue.append(message)
if self.zmq_working:
self.log("ZeroMQ already working...")
return
while self.zmq_queue:
self.zmq_working = True
message = self.zmq_queue.pop(0)
self.zmq_sock.send(msgpack.packb(message))
self.handleMessage(msgpack.unpackb(self.zmq_sock.recv()))
self.zmq_working = False
else: # Incoming request
self.server.zmq_sock.send(msgpack.packb(message))
else: # Normal connection
data = msgpack.packb(message)
self.bytes_sent += len(data)
self.server.bytes_sent += len(data)
self.sock.sendall(data)
self.last_sent_time = time.time()
return True
开发者ID:simbam1,项目名称:ZeroNet,代码行数:25,代码来源:Connection.py
示例14: handle_error
def handle_error(self, p_ctx, others, exc):
self.spyne_tpt.get_out_string(p_ctx)
if isinstance(exc, InternalError):
error = self.spyne_tpt.OUT_RESPONSE_SERVER_ERROR
else:
error = self.spyne_tpt.OUT_RESPONSE_CLIENT_ERROR
data = p_ctx.out_document[0]
if isinstance(data, dict):
data = list(data.values())
out_string = msgpack.packb([
error, msgpack.packb(data),
])
self.enqueue_outresp_data(id(p_ctx), out_string)
p_ctx.transport.resp_length = len(out_string)
p_ctx.close()
try:
process_contexts(self, others, p_ctx, error=error)
except Exception as e:
# Report but ignore any exceptions from auxiliary methods.
logger.exception(e)
开发者ID:knoxsp,项目名称:spyne,代码行数:26,代码来源:msgpack.py
示例15: main
def main(argv):
map_path = argv[1]
result_path = argv[2]
t = Teemap(map_path)
result = {}
frontlayer = None # Works thanks to hack in tml
for group in t.groups:
if group.name == 'Game':
for layer in group.layers:
if type(layer) == TileLayer and layer.name == 'Front':
frontlayer = layer
break
add(result, gameTiles, t.gamelayer)
add(result, frontTiles, frontlayer)
# These don't seem to be working
#add(result, switchTiles, switchlayer)
#add(result, speedupTiles, t.speeduplayer)
#add(result, teleTiles, t.telelayer)
with open(result_path, 'wb') as out:
out.write(msgpack.packb(t.gamelayer.width))
out.write(msgpack.packb(t.gamelayer.height))
out.write(msgpack.packb(result))
开发者ID:Munto,项目名称:ddnet-scripts,代码行数:26,代码来源:properties.py
示例16: slave_sync_data
def slave_sync_data(self, port):
"""
同步数据
"""
import time
time.sleep(1)
self._server.is_sync = True
client = PyCachedClient(self._address[0], port)
self.add_slave(client)
logger.info('Slave[%s:%d] Sync data start' % (self._address[0], port))
items = {}
pos = 0
MAX_SEND = 20000 # 同步数据多少Key为一组
all_len = len(self._server.memory.caches.items())
for key, val in self._server.memory.caches.items():
pos += 1
items[key] = val
if pos % MAX_SEND == 0:
client.sync_data(pos, all_len, msgpack.packb(items))
items = {}
if pos % MAX_SEND != 0:
client.sync_data(pos, all_len, msgpack.packb(items))
self._server.is_sync = False
client.sync_ok()
logger.info('Slave[%s:%d] Sync data success' % (self._address[0], port))
开发者ID:eicesoft,项目名称:pycached,代码行数:27,代码来源:net.py
示例17: encode
def encode(self):
ret = {'name': self._name,
'time': get_time(),
'epoch_milli': get_milli(),
'host': get_name(),
'data': msgpack.packb(self.run())}
return msgpack.packb(ret)
开发者ID:Darthone,项目名称:atto,代码行数:7,代码来源:__init__.py
示例18: handle_data
def handle_data(self, message):
payload = msgpack.unpackb(message)
if 'connect' in payload:
host, port_str = payload['connect'].split('::')
port = int(port_str)
self._sock = socket.socket()
self._sock.connect((host, port))
response = msgpack.packb({'type': 'STATUS',
'value': 'OPEN'})
self._send(response)
eventlet.spawn(self._reader)
elif 'close' in payload:
self._sock.close()
status = msgpack.packb({'type': 'STATUS',
'value': 'CLOSED'})
self._send(status)
elif 'content' in payload:
try:
self._sock.send(payload['content'])
except Exception as exc:
print exc
self._sock.close()
else:
message = 'Unknown payload type: {}\n'.format(payload.type)
sys.write(message)
开发者ID:desmaj,项目名称:minreal,代码行数:25,代码来源:tcp.py
示例19: send
def send(self, payload, deprecated=()):
"""Send a message with topic, payload
`
Topic is a unicode string. It will be sent as utf-8 encoded byte array.
Payload is a python dict. It will be sent as a msgpack serialized dict.
If payload has the key '__raw_data__'
we pop if of the payload and send its raw contents as extra frames
everything else need to be serializable
the contents of the iterable in '__raw_data__'
require exposing the pyhton memoryview interface.
"""
assert deprecated is (), "Depracted use of send()"
assert "topic" in payload, "`topic` field required in {}".format(payload)
if "__raw_data__" not in payload:
# IMPORTANT: serialize first! Else if there is an exception
# the next message will have an extra prepended frame
serialized_payload = serializer.packb(payload, use_bin_type=True)
self.socket.send_string(payload["topic"], flags=zmq.SNDMORE)
self.socket.send(serialized_payload)
else:
extra_frames = payload.pop("__raw_data__")
assert isinstance(extra_frames, (list, tuple))
self.socket.send_string(payload["topic"], flags=zmq.SNDMORE)
serialized_payload = serializer.packb(payload, use_bin_type=True)
self.socket.send(serialized_payload, flags=zmq.SNDMORE)
for frame in extra_frames[:-1]:
self.socket.send(frame, flags=zmq.SNDMORE, copy=True)
self.socket.send(extra_frames[-1], copy=True)
开发者ID:pupil-labs,项目名称:pupil,代码行数:30,代码来源:zmq_tools.py
示例20: test_node_service_bad_on_read
def test_node_service_bad_on_read():
io = CocaineIO.instance()
node = Service("node", host="localhost", port=10053, loop=io)
malformed_message = msgpack.packb([-999, 0])
node.on_read(malformed_message)
message = msgpack.packb([-999, 0, []])
node.on_read(message)
开发者ID:mwf,项目名称:cocaine-framework-python,代码行数:7,代码来源:test_main.py
注:本文中的msgpack.packb函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论