Skip to content

Instantly share code, notes, and snippets.

@zopieux
Created September 27, 2014 19:14
Show Gist options
  • Save zopieux/a6957a80b63f9906afa0 to your computer and use it in GitHub Desktop.
Save zopieux/a6957a80b63f9906afa0 to your computer and use it in GitHub Desktop.
Quizz Fever networking
def messageToBytes(type, body=None):
data = {'type': type}
if body is not None:
data['body'] = body
try:
return json.dumps(data).encode('ascii') + b"\n"
except ValueError:
raise ValueError("message could not be JSON-encoded")
except UnicodeEncodeError:
raise UnicodeEncodeError("JSON could not be converted to bytes")
def bytesToMessage(msg):
try:
data = json.loads(msg.decode('ascii'))
return data['type'], data.get('body', None)
except UnicodeDecodeError:
raise UnicodeEncodeError("Incoming message is not ASCII-encoded")
except ValueError:
raise ValueError("Incoming message is not valid JSON")
except KeyError:
raise ValueError("Incoming message is malformed")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment