• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python serpent.dumps函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中serpent.dumps函数的典型用法代码示例。如果您正苦于以下问题:Python dumps函数的具体用法?Python dumps怎么用?Python dumps使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了dumps函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_dict

    def test_dict(self):
        ser = serpent.dumps({})
        data = strip_header(ser)
        self.assertEqual(b"{}", data)
        ser = serpent.dumps({}, indent=True)
        data = strip_header(ser)
        self.assertEqual(b"{}", data)

        mydict = {
            42: 'fortytwo',
            'status': False,
            'name': 'Sally',
            'sixteen-and-half': 16.5
        }
        ser = serpent.dumps(mydict)
        data = strip_header(ser)
        self.assertEqual(69, len(data))
        if sys.version_info < (3, 0):
            self.assertEqual(b"{", data[0])
            self.assertEqual(b"}", data[-1])
        else:
            self.assertEqual(ord("{"), data[0])
            self.assertEqual(ord("}"), data[-1])
        ser = serpent.dumps(mydict, indent=True)
        data = strip_header(ser)
        self.assertEqual(86, len(data))
        if sys.version_info < (3, 0):
            self.assertEqual(b"{", data[0])
            self.assertEqual(b"}", data[-1])
        else:
            self.assertEqual(ord("{"), data[0])
            self.assertEqual(ord("}"), data[-1])
开发者ID:pombredanne,项目名称:Serpent,代码行数:32,代码来源:test_serpent.py


示例2: test_indent_sorting

    def test_indent_sorting(self):
        # non-indented should not be sorted, indented should
        data = {"ee": 1, "dd": 1, "cc": 1, "bb": 1, "aa": 1, 'ff': 1, 'hh': 1, 'gg': 1}
        ser = serpent.dumps(data, False)
        ser = strip_header(ser)
        self.assertNotEqual(b"{'aa':1,'bb':1,'cc':1,'dd':1,'ee':1,'ff':1,'gg':1,'hh':1}", ser)
        ser = serpent.dumps(data, True)
        ser = strip_header(ser)
        self.assertEqual(b"""{
  'aa': 1,
  'bb': 1,
  'cc': 1,
  'dd': 1,
  'ee': 1,
  'ff': 1,
  'gg': 1,
  'hh': 1
}""", ser)
        data = set("irmen de jong irmen de jong666")
        ser = serpent.dumps(data, False)
        ser = strip_header(ser)
        self.assertNotEqual(b"' ','6','d','e','g','i','j','m','n','o','r'", ser[1:-1])
        ser = serpent.dumps(data, True)
        ser = strip_header(ser)
        self.assertEqual(b"\n  ' ',\n  '6',\n  'd',\n  'e',\n  'g',\n  'i',\n  'j',\n  'm',\n  'n',\n  'o',\n  'r'\n", ser[1:-1])
开发者ID:pombredanne,项目名称:Serpent,代码行数:25,代码来源:test_serpent.py


示例3: 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


示例4: 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


示例5: test_string

 def test_string(self):
     ser = serpent.dumps("hello")
     data = strip_header(ser)
     self.assertEqual(b"'hello'", data)
     ser = serpent.dumps("quotes'\"")
     data = strip_header(ser)
     self.assertEqual(b"'quotes\\'\"'", data)
     ser = serpent.dumps("quotes2'")
     data = strip_header(ser)
     self.assertEqual(b"\"quotes2'\"", data)
开发者ID:pombredanne,项目名称:Serpent,代码行数:10,代码来源:test_serpent.py


示例6: test_timezone

 def test_timezone(self):
     import pytz    # requires pytz library
     tz_nl = pytz.timezone("Europe/Amsterdam")
     dt_tz = tz_nl.localize(datetime.datetime(2013, 1, 20, 23, 59, 45, 999888))
     ser = serpent.dumps(dt_tz)
     data = strip_header(ser)
     self.assertEqual(b"'2013-01-20T23:59:45.999888+01:00'", data)   # normal time
     dt_tz = tz_nl.localize(datetime.datetime(2013, 5, 10, 13, 59, 45, 999888))
     ser = serpent.dumps(dt_tz)
     data = strip_header(ser)
     self.assertEqual(b"'2013-05-10T13:59:45.999888+02:00'", data)   # daylight saving time
开发者ID:pombredanne,项目名称:Serpent,代码行数:11,代码来源:test_serpent.py


示例7: test_array

 def test_array(self):
     ser = serpent.dumps(array.array('u', unicode("unicode")))
     data = strip_header(ser)
     self.assertEqual(b"'unicode'", data)
     ser = serpent.dumps(array.array('i', [44, 45, 46]))
     data = strip_header(ser)
     self.assertEqual(b"[44,45,46]", data)
     if sys.version_info < (3, 0):
         ser = serpent.dumps(array.array('c', "normal"))
         data = strip_header(ser)
         self.assertEqual(b"'normal'", data)
开发者ID:pombredanne,项目名称:Serpent,代码行数:11,代码来源:test_serpent.py


示例8: test_unicode

 def test_unicode(self):
     u = "euro" + unichr(0x20ac)
     self.assertTrue(type(u) is unicode)
     ser = serpent.dumps(u)
     data = serpent.loads(ser)
     self.assertEqual(u, data)
     ser = serpent.dumps(unicode("quotes'\""))
     data = strip_header(ser)
     self.assertEqual(b"'quotes\\'\"'", data)
     ser = serpent.dumps(unicode("quotes2'"))
     data = strip_header(ser)
     self.assertEqual(b"\"quotes2'\"", data)
开发者ID:pombredanne,项目名称:Serpent,代码行数:12,代码来源:test_serpent.py


示例9: 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


示例10: test_indent_containers

    def test_indent_containers(self):
        data = [1, 2, 3]
        ser = serpent.dumps(data, indent=True).decode("utf-8")
        _, _, ser = ser.partition("\n")
        self.assertEqual("""[
  1,
  2,
  3
]""", ser)
        data = (1, 2, 3)
        ser = serpent.dumps(data, indent=True).decode("utf-8")
        _, _, ser = ser.partition("\n")
        self.assertEqual("""(
  1,
  2,
  3
)""", ser)
        data = set([1])
        ser = serpent.dumps(data, indent=True, set_literals=True).decode("utf-8")
        _, _, ser = ser.partition("\n")
        self.assertEqual("""{
  1
}""", ser)
        data = {"one": 1}
        ser = serpent.dumps(data, indent=True, set_literals=True).decode("utf-8")
        _, _, ser = ser.partition("\n")
        self.assertEqual("""{
  'one': 1
}""", ser)

        data = {"first": [1, 2, ("a", "b")], "second": {1: False}, "third": set([1, 2])}
        ser = serpent.dumps(data, indent=True, set_literals=True).decode("utf-8")
        _, _, ser = ser.partition("\n")
        self.assertEqual("""{
  'first': [
    1,
    2,
    (
      'a',
      'b'
    )
  ],
  'second': {
    1: False
  },
  'third': {
    1,
    2
  }
}""", ser)
开发者ID:pombredanne,项目名称:Serpent,代码行数:50,代码来源:test_serpent.py


示例11: test_numbers

 def test_numbers(self):
     ser = serpent.dumps(12345)
     data = strip_header(ser)
     self.assertEqual(b"12345", data)
     ser = serpent.dumps(123456789123456789123456789)
     data = strip_header(ser)
     self.assertEqual(b"123456789123456789123456789", data)
     ser = serpent.dumps(99.1234)
     data = strip_header(ser)
     self.assertEqual(b"99.1234", data)
     ser = serpent.dumps(decimal.Decimal("1234.9999999999"))
     data = strip_header(ser)
     self.assertEqual(b"'1234.9999999999'", data)
     ser = serpent.dumps(2 + 3j)
     data = strip_header(ser)
     self.assertEqual(b"(2+3j)", data)
开发者ID:achernet,项目名称:Serpent,代码行数:16,代码来源:test_serpent.py


示例12: test_time

 def test_time(self):
     ser = serpent.dumps(datetime.datetime(2013, 1, 20, 23, 59, 45, 999888))
     data = strip_header(ser)
     self.assertEqual(b"'2013-01-20T23:59:45.999888'", data)
     ser = serpent.dumps(datetime.time(23, 59, 45, 999888))
     data = strip_header(ser)
     self.assertEqual(b"'23:59:45.999888'", data)
     ser = serpent.dumps(datetime.time(23, 59, 45))
     data = strip_header(ser)
     self.assertEqual(b"'23:59:45'", data)
     ser = serpent.dumps(datetime.timedelta(1, 4000, 999888, minutes=22))
     data = strip_header(ser)
     self.assertEqual(b"91720.999888", data)
     ser = serpent.dumps(datetime.timedelta(seconds=12345))
     data = strip_header(ser)
     self.assertEqual(b"12345.0", data)
开发者ID:pombredanne,项目名称:Serpent,代码行数:16,代码来源:test_serpent.py


示例13: getMenu

	def getMenu(self, menu):
		try:
			print "Menu pyro"
			x = Menu_db.select().where(Menu_db.nombre==menu).get()
			p = [] #primeros
			s = [] #segundos
			d = [] #postres
			m = {}
			m['nombre'] = x.nombre
			m['disponible'] = x.disponible
			m['precio'] = float(x.precio)
			m['descripcion'] = x.descripcion
			m['fecha_ini'] = x.fecha_ini
			m['fecha_fin'] = x.fecha_fin
			m['imagen'] = x.imagen
			for y in Item_db.select().where(Item_db.primeros==x):
				p.append(y)
			for y in Item_db.select().where(Item_db.segundos==x):
				s.append(y)
			for y in Item_db.select().where(Item_db.postres==x):
				d.append(y)
			m['primeros'] = p
			m['segundos'] = s
			m['postres'] = d
			return serpent.dumps(m,indent=False)
		except Exception, e:
			return False
开发者ID:xXcoronaXx,项目名称:servidor-adhoc,代码行数:27,代码来源:admin.py


示例14: 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


示例15: test_unicode_with_escapes_py3

 def test_unicode_with_escapes_py3(self):
     ser = serpent.dumps(unicode("\n"))
     d = strip_header(ser)
     self.assertEqual(b"'\\n'", d)
     ser = serpent.dumps(unicode("\a"))
     d = strip_header(ser)
     self.assertEqual(b"'\\x07'", d)
     ser = serpent.dumps("\a"+unichr(0x20ac))
     d = strip_header(ser)
     self.assertEqual(b"'\\x07\xe2\x82\xac'", d)
     line = "'euro" + unichr(0x20ac) + "\nlastline\ttab\\@slash\a\b\f\n\r\t\v'"
     ser = serpent.dumps(line)
     d = strip_header(ser)
     self.assertEqual(b"\"'euro\xe2\x82\xac\\nlastline\\ttab\\\\@slash\\x07\\x08\\x0c\\n\\r\\t\\x0b'\"", d)
     data = serpent.loads(ser)
     self.assertEqual(line, data)
开发者ID:pombredanne,项目名称:Serpent,代码行数:16,代码来源:test_serpent.py


示例16: 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


示例17: getMenus

	def getMenus(self, fecha):
		try:
			print "Menus pyro"
			fecha = str(fecha).split('-')
			fecha = date(int(fecha[0]),int(fecha[1]),int(fecha[2]))
			menus = []
			for x in Menu_db.select().where( Menu_db.fecha_ini <= fecha  ).where( Menu_db.fecha_fin >= fecha ):
				p = [] #primeros
				s = [] #segundos
				d = [] #postres
				m = {}
				m['nombre'] = x.nombre
				m['disponible'] = x.disponible
				m['precio'] = float(x.precio)
				m['descripcion'] = x.descripcion
				m['fecha_ini'] = x.fecha_ini
				m['fecha_fin'] = x.fecha_fin
				m['imagen'] = x.imagen
				for y in Item_db.select().where(Item_db.primeros==x):
					p.append(y)
				for y in Item_db.select().where(Item_db.segundos==x):
					s.append(y)
				for y in Item_db.select().where(Item_db.postres==x):
					d.append(y)
				m['primeros'] = p
				m['segundos'] = s
				m['postres'] = d
				# agregamos el menu
				menus.append(m)
			return serpent.dumps(menus,indent=False)
		except Exception, e:
			return False
开发者ID:xXcoronaXx,项目名称:servidor-adhoc,代码行数:32,代码来源:admin.py


示例18: 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


示例19: 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


示例20: 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



注:本文中的serpent.dumps函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python serpent.loads函数代码示例发布时间:2022-05-27
下一篇:
Python series.slices函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap