Serializing a function in python -
i trying serialize code , send json...
def f(x): return x*x def fi(x): return int(x[0]) code_string = marshal.dumps(fi.func_code) jsn = {"code":code_string) json.dumps(jsn) # doesnt work if code_string fi
so... above code block works if function f(x)
but fails fi(x)
original exception was:
traceback (most recent call last): file "/home/mohitdee/documents/python_scala/rdd.py", line 41, in <module> send_data(json.dumps(jsn)) file "/usr/lib/python2.7/json/__init__.py", line 231, in dumps return _default_encoder.encode(obj) file "/usr/lib/python2.7/json/encoder.py", line 201, in encode chunks = self.iterencode(o, _one_shot=true) file "/usr/lib/python2.7/json/encoder.py", line 264, in iterencode return _iterencode(o, 0) unicodedecodeerror: 'utf8' codec can't decode byte 0x83 in position 32: invalid start byte [48001 refs]
how resolve in python
marshall binary protocol, i.e. bunch of bytes custom interpretation. it's not text, doesn't conform in particular text encoding. is, part, sequence of bits. if absolutely need embed in text protocol json, need escape bytes don't make valid characters in relevant encoding (to safe, assume subset of ascii). canonical solution base64:
import base64 code_string = marshal.dumps(fi.func_code) code_base64 = base64.b64encode(code_string) jsn = {"code": code_base64}
Comments
Post a Comment