本文整理汇总了Python中serpent.loads函数的典型用法代码示例。如果您正苦于以下问题:Python loads函数的具体用法?Python loads怎么用?Python loads使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了loads函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_weird_doubles
def test_weird_doubles(self):
values = [float('inf'), float('-inf'), float('nan')]
ser = serpent.dumps(values)
values2 = serpent.loads(ser)
self.assertEqual([float('inf'), float('-inf'), {'__class__':'float','value':'nan'}], values2)
values2 = serpent.loads(b"[1e30000,-1e30000]")
self.assertEqual([float('inf'), float('-inf')], values2)
开发者ID:pombredanne,项目名称:Serpent,代码行数:7,代码来源:test_serpent.py
示例2: test_class
def test_class(self):
class Class1(object):
def __init__(self):
self.attr = 1
class Class2(object):
def __getstate__(self):
return {"attr": 42}
class SlotsClass(object):
__slots__ = ["attr"]
def __init__(self):
self.attr = 1
c = Class1()
ser = serpent.dumps(c)
data = serpent.loads(ser)
self.assertEqual({'__class__': 'Class1', 'attr': 1}, data)
c = Class2()
ser = serpent.dumps(c)
data = serpent.loads(ser)
self.assertEqual({'attr': 42}, data)
c = SlotsClass()
ser = serpent.dumps(c)
data = serpent.loads(ser)
self.assertEqual({'__class__': 'SlotsClass', 'attr': 1}, data)
import pprint
p = pprint.PrettyPrinter(stream="dummy", width=99)
ser = serpent.dumps(p)
data = serpent.loads(ser)
self.assertEqual("PrettyPrinter", data["__class__"])
self.assertEqual(99, data["_width"])
开发者ID:pombredanne,项目名称:Serpent,代码行数:33,代码来源:test_serpent.py
示例3: test_weird_complex
def test_weird_complex(self):
c1 = complex(float('inf'), 4)
ser = serpent.dumps(c1)
c2 = serpent.loads(ser)
self.assertEqual(c1, c2)
c3 = serpent.loads(b"(1e30000+4.0j)")
self.assertEqual(c1, c3)
开发者ID:pombredanne,项目名称:Serpent,代码行数:7,代码来源:test_serpent.py
示例4: test_trailing_commas
def test_trailing_commas(self):
v = serpent.loads(b"[1,2,3,]")
self.assertEqual([1, 2, 3], v)
v = serpent.loads(b"(1,2,3,)")
self.assertEqual((1, 2, 3), v)
v = serpent.loads(b"{'a':1, 'b':2, 'c':3,}")
self.assertEqual({'a': 1, 'b': 2, 'c': 3}, v)
开发者ID:pombredanne,项目名称:Serpent,代码行数:7,代码来源:test_serpent.py
示例5: test_deserialize
def test_deserialize(self):
data = serpent.loads(b"555")
self.assertEqual(555, data)
unicodestring = "euro" + unichr(0x20ac)
encoded = repr(unicodestring).encode("utf-8")
data = serpent.loads(encoded)
self.assertEqual(unicodestring, data)
开发者ID:pombredanne,项目名称:Serpent,代码行数:7,代码来源:test_serpent.py
示例6: test_exception
def test_exception(self):
x = ZeroDivisionError("wrong")
ser = serpent.dumps(x)
data = serpent.loads(ser)
self.assertEqual({
'__class__': 'ZeroDivisionError',
'__exception__': True,
'args': ('wrong',),
'attributes': {}
}, data)
x = ZeroDivisionError("wrong", 42)
ser = serpent.dumps(x)
data = serpent.loads(ser)
self.assertEqual({
'__class__': 'ZeroDivisionError',
'__exception__': True,
'args': ('wrong', 42),
'attributes': {}
}, data)
x.custom_attribute = "custom_attr"
ser = serpent.dumps(x)
data = serpent.loads(ser)
self.assertEqual({
'__class__': 'ZeroDivisionError',
'__exception__': True,
'args': ('wrong', 42),
'attributes': {'custom_attribute': 'custom_attr'}
}, data)
开发者ID:pombredanne,项目名称:Serpent,代码行数:28,代码来源:test_serpent.py
示例7: test_pickle_api
def test_pickle_api(self):
ser = serpent.dumps([1, 2, 3])
serpent.loads(ser)
tmpfn = tempfile.mktemp()
with open(tmpfn, "wb") as outf:
serpent.dump([1, 2, 3], outf, indent=True, set_literals=True)
with open(tmpfn, "rb") as inf:
data = serpent.load(inf)
self.assertEqual([1, 2, 3], data)
os.remove(tmpfn)
开发者ID:pombredanne,项目名称:Serpent,代码行数:10,代码来源:test_serpent.py
示例8: test_bytes
def test_bytes(self):
if sys.version_info >= (3, 0):
ser = serpent.dumps(bytes(b"abcdef"))
data = serpent.loads(ser)
self.assertEqual({'encoding': 'base64', 'data': 'YWJjZGVm'}, data)
ser = serpent.dumps(bytearray(b"abcdef"))
data = serpent.loads(ser)
self.assertEqual({'encoding': 'base64', 'data': 'YWJjZGVm'}, data)
if sys.version_info >= (2, 7):
ser = serpent.dumps(memoryview(b"abcdef"))
data = serpent.loads(ser)
self.assertEqual({'encoding': 'base64', 'data': 'YWJjZGVm'}, data)
开发者ID:pombredanne,项目名称:Serpent,代码行数:12,代码来源:test_serpent.py
示例9: test_comments
def test_comments(self):
ser = b"""# serpent utf-8 python2.7
[ 1, 2,
# some comments here
3, 4] # more here
# and here."""
data = serpent.loads(ser)
self.assertEqual([1, 2, 3, 4], data)
ser = b"[ 1, 2 ]" # no header whatsoever
data = serpent.loads(ser)
self.assertEqual([1, 2], data)
开发者ID:pombredanne,项目名称:Serpent,代码行数:12,代码来源:test_serpent.py
示例10: test_nullbytesunicode
def test_nullbytesunicode(self):
line = unichr(0) + "null"
ser = serpent.dumps(line)
data = strip_header(ser)
self.assertEqual(b"'\\x00null'", data)
data = serpent.loads(ser)
self.assertEqual(line, data)
开发者ID:pombredanne,项目名称:Serpent,代码行数:7,代码来源:test_serpent.py
示例11: testFile
def testFile(self):
if sys.version_info < (3, 2):
self.skipTest("testdatafile contains stuff that is not supported by ast.literal_eval on Python < 3.2")
with open("testserpent.utf8.bin", "rb") as file:
data = file.read()
obj = serpent.loads(data)
self.assertEqual(-3 + 8j, obj["numbers"][3])
开发者ID:pombredanne,项目名称:Serpent,代码行数:7,代码来源:test_serpent.py
示例12: testRegular
def testRegular(self):
import pprint
p = pprint.PrettyPrinter(stream="dummy", width=42)
ser = serpent.dumps(p)
data = serpent.loads(ser)
self.assertEqual(42, data["_width"])
self.assertEqual("PrettyPrinter", data["__class__"])
开发者ID:pombredanne,项目名称:Serpent,代码行数:7,代码来源:test_serpent.py
示例13: testDefaultDict
def testDefaultDict(self):
dd = collections.defaultdict(list)
dd['a'] = 1
dd['b'] = 2
d = serpent.dumps(dd)
dd2 = serpent.loads(d)
self.assertEqual({'a': 1, 'b': 2}, dd2)
开发者ID:pombredanne,项目名称:Serpent,代码行数:7,代码来源:test_serpent.py
示例14: example
def example():
use_set_literals = sys.version_info >= (3, 2) # check if we can use set literals
data = {
"tuple": (1, 2, 3),
"date": datetime.datetime.now(),
"set": {'a', 'b', 'c'},
"class": CustomClass("Sally", 26)
}
# serialize the object
ser = serpent.dumps(data, indent=True, set_literals=use_set_literals)
# print it to the screen, but usually you'd save the bytes to a file or transfer them over a network connection
print("Serialized data:")
print(ser.decode("UTF-8"))
# deserialize the bytes and print the objects
obj = serpent.loads(ser)
print("Deserialized data:")
print("tuple:", obj["tuple"])
print("date:", obj["date"])
print("set:", obj["set"])
clazz = obj["class"]
print("class attributes: type={0} name={1} age={2}".format(
clazz["__class__"], clazz["name"], clazz["age"]))
开发者ID:achernet,项目名称:Serpent,代码行数:25,代码来源:example.py
示例15: testUserDict
def testUserDict(self):
obj = collections.UserDict()
obj['a'] = 1
obj['b'] = 2
d = serpent.dumps(obj)
obj2 = serpent.loads(d)
self.assertEqual({'a': 1, 'b': 2}, obj2)
开发者ID:pombredanne,项目名称:Serpent,代码行数:7,代码来源:test_serpent.py
示例16: test_unicode_with_escapes
def test_unicode_with_escapes(self):
line = "euro"+unichr(0x20ac)+"\nlastline\ttab\\@slash"
ser = serpent.dumps(line)
d = strip_header(ser)
self.assertEqual(b"'euro\xe2\x82\xac\\nlastline\\ttab\\\\@slash'", d)
data = serpent.loads(ser)
self.assertEqual(line, data)
开发者ID:achernet,项目名称:Serpent,代码行数:7,代码来源:test_serpent.py
示例17: _fetch_account
def _fetch_account(self, conn: sqlite3.Connection, account_id: int) -> Account:
acc = conn.execute("SELECT * FROM Account WHERE id=?", (account_id,)).fetchone()
priv_result = conn.execute("SELECT privilege FROM Privilege WHERE account=?", (account_id,)).fetchall()
privileges = {pr["privilege"] for pr in priv_result}
storydata_result = conn.execute("SELECT format, data FROM StoryData WHERE account=?", (account_id,)).fetchone()
if storydata_result:
if storydata_result["format"] == "json":
storydata = json.loads(storydata_result["data"], encoding="utf-8")
elif storydata_result["format"] == "serpent":
storydata = serpent.loads(storydata_result["data"])
else:
raise ValueError("invalid storydata format in database: " + storydata_result["format"])
if not isinstance(storydata, dict):
raise TypeError("storydata should be a dict")
else:
storydata = {}
stats_result = dict(conn.execute("SELECT * FROM CharStat WHERE account=?", (account_id,)).fetchone() or {})
del stats_result["id"]
del stats_result["account"]
stats = base.Stats()
for key, value in stats_result.items():
if hasattr(stats, key):
setattr(stats, key, value)
else:
raise AttributeError("stats doesn't have attribute: " + key)
stats.set_stats_from_race() # initialize static stats from races table
return Account(acc["name"], acc["email"], acc["pw_hash"], acc["pw_salt"], privileges,
acc["created"], acc["logged_in"], bool(acc["banned"]), stats, storydata)
开发者ID:irmen,项目名称:Tale,代码行数:28,代码来源:accounts.py
示例18: mostrarItems
def mostrarItems():
print '-------------- LISTA DE TODOS LOS ITEMS --------------'
c = servicio.getItems()
c = serpent.loads(c)
for x in c:
print str(x['_data']['id'])+' '+x['_data']['nombre']+' '+str(x['_data']['precio'])
print '-------------- ####################### --------------'
print ''
开发者ID:xXcoronaXx,项目名称:servidor-adhoc,代码行数:8,代码来源:clientePyro.py
示例19: testOrderedDict
def testOrderedDict(self):
o = collections.OrderedDict()
o['apple'] = 1
o['banana'] = 2
o['orange'] = 3
d = serpent.dumps(o)
o2 = serpent.loads(d)
self.assertEqual({"__class__": "OrderedDict", "items": [('apple', 1), ('banana', 2), ('orange', 3)]}, o2)
开发者ID:pombredanne,项目名称:Serpent,代码行数:8,代码来源:test_serpent.py
示例20: testIntercept
def testIntercept(self):
ex = ZeroDivisionError("wrong")
ser = serpent.dumps(ex)
data = serpent.loads(ser)
# default behavior is to serialize the exception to a dict
self.assertEqual({'__exception__': True, 'args': ('wrong',), '__class__': 'ZeroDivisionError', 'attributes': {}}, data)
def custom_exception_translate(obj, serializer, stream, indent):
serializer._serialize("custom_exception!", stream, indent)
try:
serpent.register_class(Exception, custom_exception_translate)
ser = serpent.dumps(ex)
data = serpent.loads(ser)
self.assertEqual("custom_exception!", data)
finally:
serpent.unregister_class(Exception)
开发者ID:pombredanne,项目名称:Serpent,代码行数:17,代码来源:test_serpent.py
注:本文中的serpent.loads函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论