Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

import re 

 

import msgpack 

 

from .exceptions import * 

 

SN_MSG_REGEXP = "^([a-z0-9_]+/)*[a-z0-9_]+$" 

SN_MSG = re.compile(SN_MSG_REGEXP) 

 

def parse_msg(data): 

""" Gets a Sentinel-type ZMQ message and parses message type and its 

payload. 

""" 

try: 

msg_type = str(data[0], encoding="UTF-8") 

if not SN_MSG.match(msg_type): 

raise InvalidMsgTypeError("Bad message type definition") 

payload = msgpack.unpackb(data[1], encoding="UTF-8") 

 

except IndexError: 

raise InvalidMsgError("Not enough parts in message") 

 

except (TypeError, msgpack.exceptions.UnpackException, UnicodeDecodeError): 

raise InvalidMsgError("Broken message") 

 

 

return msg_type, payload 

 

 

def encode_msg(msg_type, data): 

""" Gets string message type and its's string data. Then, both of them are 

packed to be prepared for zmg.send_multipart(). 

""" 

 

if not SN_MSG.match(msg_type or ""): 

raise InvalidMsgTypeError("Bad message type definition") 

 

if not data or type(data) != dict: 

raise InvalidMsgError("Empty payload parameter") 

 

b = bytes(msg_type, encoding="UTF-8") 

msg = msgpack.packb(data) 

 

return (b, msg)