将python对象序列化成php能读取的格式(即能反序列化到对象)
转载自:http://my.oschina.net/zuoan001/blog/94914
代码如下:
#coding:utf-8
# vim: encoding=utf-8:ft=python:et:sw=4:ts=8:sts=4:
#
# Copyright (c) 2005 Scott Hurring.
# Licensed under the GPL (undefined version). import types, string """
Serialize class for the PHP serialization format. @version v0.4 BETA
@author Scott Hurring; scott at hurring dot com
@copyright Copyright (c) 2005 Scott Hurring
@license http://opensource.org/licenses/gpl-license.php GNU Public License
$Id: PHPSerialize.py,v 1.1 2006/01/08 21:53:19 shurring Exp $ Most recent version can be found at:
http://hurring.com/code/python/phpserialize/ Usage:
# Create an instance of the serialize engine
s = PHPSerialize()
# serialize some python data into a string
serialized_string = s.serialize(string)
# encode a session list (php's session_encode)
serialized_string = s.session_encode(list)
""" class PHPSerialize(object):
"""
Class to serialize data using the PHP Serialize format. Usage:
serialized_string = PHPSerialize().serialize(data)
serialized_string = PHPSerialize().session_encode(list)
""" def __init__(self):
pass def session_encode(self, session):
"""Thanks to Ken Restivo for suggesting the addition
of session_encode
"""
out = ""
for (k,v) in session.items():
out = out + "%s|%s" % (k, self.serialize(v))
return out def serialize(self, data):
return self.serialize_value(data) def is_int(self, data):
"""
Determine if a string var looks like an integer
TODO: Make this do what PHP does, instead of a hack
"""
try:
int(data)
return True
except:
return False def serialize_key(self, data):
"""
Serialize a key, which follows different rules than when
serializing values. Many thanks to Todd DeLuca for pointing
out that keys are serialized differently than values! From http://us2.php.net/manual/en/language.types.array.php
A key may be either an integer or a string.
If a key is the standard representation of an integer, it will be
interpreted as such (i.e. "8" will be interpreted as int 8,
while "08" will be interpreted as "08").
Floats in key are truncated to integer.
"""
# Integer, Long, Float, Boolean => integer
if type(data) is types.IntType or type(data) is types.LongType \
or type(data) is types.FloatType or type(data) is types.BooleanType:
return "i:%s;" % int(data) # String => string or String => int (if string looks like int)
elif type(data) is types.StringType:
if self.is_int(data):
return "i:%s;" % int(data)
else:
return "s:%i:\"%s\";" % (len(data), data); # None / NULL => empty string
elif type(data) is types.NoneType:
return "s:0:\"\";" # I dont know how to serialize this
else:
raise Exception("Unknown / Unhandled key type (%s)!" % type(data)) def serialize_value(self, data):
"""
Serialize a value.
""" # Integer => integer
if type(data) is types.IntType:
return "i:%s;" % data # Float, Long => double
elif type(data) is types.FloatType or type(data) is types.LongType:
return "d:%s;" % data # String => string or String => int (if string looks like int)
# Thanks to Todd DeLuca for noticing that PHP strings that
# look like integers are serialized as ints by PHP
elif type(data) is types.StringType:
if self.is_int(data):
return "i:%s;" % int(data)
else:
return "s:%i:\"%s\";" % (len(data), data); # None / NULL
elif type(data) is types.NoneType:
return "N;"; # Tuple and List => array
# The 'a' array type is the only kind of list supported by PHP.
# array keys are automagically numbered up from 0
elif type(data) is types.ListType or type(data) is types.TupleType:
i = 0
out = []
# All arrays must have keys
for k in data:
out.append(self.serialize_key(i))
out.append(self.serialize_value(k))
i += 1
return "a:%i:{%s}" % (len(data), "".join(out)) # Dict => array
# Dict is the Python analogy of a PHP array
elif type(data) is types.DictType:
out = []
for k in data:
out.append(self.serialize_key(k))
out.append(self.serialize_value(data[k]))
return "a:%i:{%s}" % (len(data), "".join(out)) # Boolean => bool
elif type(data) is types.BooleanType:
return "b:%i;" % (data == 1) # I dont know how to serialize this
else:
raise Exception("Unknown / Unhandled data type (%s)!" % type(data)) #!/usr/bin/env python2.4
# vim: encoding=utf-8:ft=python:et:sw=4:ts=8:sts=4:
#
# Copyright (c) 2005 Scott Hurring.
# Licensed under the GPL (undefined version). import types, string, re """
Unserialize class for the PHP serialization format. @version v0.4 BETA
@author Scott Hurring; scott at hurring dot com
@copyright Copyright (c) 2005 Scott Hurring
@license http://opensource.org/licenses/gpl-license.php GNU Public License
$Id: PHPUnserialize.py,v 1.1 2006/01/08 21:53:19 shurring Exp $ Most recent version can be found at:
http://hurring.com/code/python/phpserialize/ Usage:
# Create an instance of the unserialize engine
u = PHPUnserialize()
# unserialize some string into python data
data = u.unserialize(serialized_string)
""" class PHPUnserialize(object):
"""
Class to unserialize something from the PHP Serialize format. Usage:
u = PHPUnserialize()
data = u.unserialize(serialized_string)
""" def __init__(self):
pass def session_decode(self, data):
"""Thanks to Ken Restivo for suggesting the addition
of session_encode
"""
session = {}
while len(data) > 0:
m = re.match('^(\w+)\|', data)
if m:
key = m.group(1)
offset = len(key)+1
(dtype, dataoffset, value) = self._unserialize(data, offset)
offset = offset + dataoffset
data = data[offset:]
session[key] = value
else:
# No more stuff to decode
return session return session def unserialize(self, data):
return self._unserialize(data, 0)[2] def _unserialize(self, data, offset=0):
"""
Find the next token and unserialize it.
Recurse on array. offset = raw offset from start of data return (type, offset, value)
""" buf = []
dtype = string.lower(data[offset:offset+1]) #print "# dtype =", dtype # 't:' = 2 chars
dataoffset = offset + 2
typeconvert = lambda x : x
chars = datalength = 0 # int => Integer
if dtype == 'i':
typeconvert = lambda x : int(x)
(chars, readdata) = self.read_until(data, dataoffset, ';')
# +1 for end semicolon
dataoffset += chars + 1 # bool => Boolean
elif dtype == 'b':
typeconvert = lambda x : (int(x) == 1)
(chars, readdata) = self.read_until(data, dataoffset, ';')
# +1 for end semicolon
dataoffset += chars + 1 # double => Floating Point
elif dtype == 'd':
typeconvert = lambda x : float(x)
(chars, readdata) = self.read_until(data, dataoffset, ';')
# +1 for end semicolon
dataoffset += chars + 1 # n => None
elif dtype == 'n':
readdata = None # s => String
elif dtype == 's':
(chars, stringlength) = self.read_until(data, dataoffset, ':')
# +2 for colons around length field
dataoffset += chars + 2 # +1 for start quote
(chars, readdata) = self.read_chars(data, dataoffset+1, int(stringlength))
# +2 for endquote semicolon
dataoffset += chars + 2 if chars != int(stringlength) != int(readdata):
raise Exception("String length mismatch") # array => Dict
# If you originally serialized a Tuple or List, it will
# be unserialized as a Dict. PHP doesn't have tuples or lists,
# only arrays - so everything has to get converted into an array
# when serializing and the original type of the array is lost
elif dtype == 'a':
readdata = {} # How many keys does this list have?
(chars, keys) = self.read_until(data, dataoffset, ':')
# +2 for colons around length field
dataoffset += chars + 2 # Loop through and fetch this number of key/value pairs
for i in range(0, int(keys)):
# Read the key
(ktype, kchars, key) = self._unserialize(data, dataoffset)
dataoffset += kchars
#print "Key(%i) = (%s, %i, %s) %i" % (i, ktype, kchars, key, dataoffset) # Read value of the key
(vtype, vchars, value) = self._unserialize(data, dataoffset)
dataoffset += vchars
#print "Value(%i) = (%s, %i, %s) %i" % (i, vtype, vchars, value, dataoffset) # Set the list element
readdata[key] = value # +1 for end semicolon
dataoffset += 1
#chars = int(dataoffset) - start # I don't know how to unserialize this
else:
raise Exception("Unknown / Unhandled data type (%s)!" % dtype) return (dtype, dataoffset-offset, typeconvert(readdata)) def read_until(self, data, offset, stopchar):
"""
Read from data[offset] until you encounter some char 'stopchar'.
"""
buf = []
char = data[offset:offset+1]
i = 2
while char != stopchar:
# Consumed all the characters and havent found ';'
if i+offset > len(data):
raise Exception("Invalid")
buf.append(char)
char = data[offset+(i-1):offset+i]
i += 1 # (chars_read, data)
return (len(buf), "".join(buf)) def read_chars(self, data, offset, length):
"""
Read 'length' number of chars from data[offset].
"""
buf = []
# Account for the starting quote char
#offset += 1
for i in range(0, length):
char = data[offset+(i-1):offset+i]
buf.append(char) # (chars_read, data)
return (len(buf), "".join(buf)) def dumps(data, protocol=None):
return PHPSerialize().serialize(data) def loads(data):
return PHPUnserialize().unserialize(data)
完毕
将python对象序列化成php能读取的格式(即能反序列化到对象)的更多相关文章
- C#对象序列化成XML,以及自定义标签名
C#对象序列化操作: public class XMLHelper { /// <summary> /// 对象序列化成 XML String /// </summary> p ...
- C#将对象序列化成JSON字符串
C#将对象序列化成JSON字符串 public string GetJsonString() { List<Product> products = new List<Product& ...
- 将Java对象序列化成JSON和XML格式
1.先定义一个Java对象Person: public class Person { String name; int age; int number; public String getName() ...
- 在C#中将对象序列化成Json格式
在C#中将对象转换为Json格式的字符串. //匿名对象 var dataObj = new { Number = 1, Name = "Json" }; //将返回的时间格式解析 ...
- .Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程
JSON作为一种轻量级的数据交换格式,简单灵活,被很多系统用来数据交互,作为一名.NET开发人员,JSON.NET无疑是最好的序列化框架,支持XML和JSON序列化,高性能,免费开源,支持LINQ查询 ...
- 对象序列化成Json字符串 及 反序列化成对象
一. public static string JsonSerializer<T>(T t) { DataContractJsonSerializer ...
- ObjC 利用反射和KVC实现嵌套对象序列化成JSON数据
原理: 0.创建一个新的可变字典:NSMutableDictionary 1.采用class_copyPropertyList函数遍历对象的属性 2.property_getName获取属性名,val ...
- C#实体对象序列化成Json并让字段的首字母小写的两种解决方法
引言:最近在工作中遇到与某些API对接的post的数据需要将对象的字段首字母小写.解决办法有两种:第一种:使用对象的字段属性设置JsonProperty来实现(不推荐,因为需要手动的修改每个字段的属性 ...
- XmlSerializer 对象序列化成XML 自定义编码格式(gb2312)
随着面向服务(SOA)的开发方式的兴起,客户端和服务端之间的消息传送,很多采用了XML的格式.但是大家在日常的开发中,应该会有这么种体验,就是组织xml格式的代码太繁琐,这篇随笔也是为了和大家分享下简 ...
随机推荐
- Python与数据结构[3] -> 树/Tree[2] -> AVL 平衡树和树旋转的 Python 实现
AVL 平衡树和树旋转 目录 AVL平衡二叉树 树旋转 代码实现 1 AVL平衡二叉树 AVL(Adelson-Velskii & Landis)树是一种带有平衡条件的二叉树,一棵AVL树其实 ...
- 暴力 【p4092】[HEOI2016/TJOI2016]树
Description 在2016年,佳媛姐姐刚刚学习了树,非常开心.现在他想解决这样一个问题:给定一颗有根树(根为1),有以下两种操作: 标记操作:对某个结点打上标记(在最开始,只有结点1有标记,其 ...
- CSS选择符——分门别类
CSS选择符--分门别类 有时候,老是会对一些CSS选择器模模糊糊,傻傻分不清.今天花了点时间整理了一下,感觉世界清静了不少. 用XMIND做出了思维导图: 主要有11中选择器:元素.类ID.后代.子 ...
- Web应用漏洞评估工具Paros
Web应用漏洞评估工具Paros Paros是Kali Linux集成的一款Web应用漏洞评估工具.该工具提供HTTP会话分析.网络爬虫.漏洞扫描三大功能.首先借助HTTP代理模式,该工具可以实时 ...
- 微信小程序开发教程(五)开发框架:MINA
微信团队为小程序提供的框架命名为MINA应用框架.MINA框架通过封装微信客户端提供的文件系统.网络通信.任务管理.数据安全等基础功能,对上层提供一整套JavaScript API,让开发者能够非常方 ...
- 【AC自动机】【矩阵乘法】poj2778 DNA Sequence
http://blog.csdn.net/morgan_xww/article/details/7834801 讲得很好~可以理解自动机的本质,就是一个用来状态转移的东西~对于确定的输入而言,可以从初 ...
- [CF911C]Three Garlands
题目大意: 给你三个灯,分别以k1秒一次,k2秒一次和k3秒一次的频率闪烁着. 你可以自定义三个灯开启的时间,问是否有一种方案,使得max(k1,k2,k3)秒之后,每秒钟都至少有一盏灯闪烁. 思路: ...
- 1.1(Mybatis学习笔记)初识Mybatis
一.Mybatis下载与使用 下载地址:https://github.com/mybatis/mybatis-3/releases 下载后解压目录: 需要将lib下的jar包和mybatid-x-x- ...
- Looking deeper into SQL Server using Minidumps
https://blogs.msdn.microsoft.com/sqlcat/2009/09/11/looking-deeper-into-sql-server-using-minidumps/ A ...
- python中单星号(*)和双星号(**)的使用
1.单星号*:对元组解包:接收可变参数 2.双星号**:对字典解包:接收可变参数 python函数的五类参数类型及出现顺序:必选参数.默认参数.可变参数.命名关键字参数.关键字参数 参考: https ...