pyconvert 0.3.alpha__tar.gz → 0.4.alpha__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of pyconvert might be problematic. Click here for more details.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 1.0
2
2
  Name: pyconvert
3
- Version: 0.3.alpha
3
+ Version: 0.6.1
4
4
  Summary: UNKNOWN
5
5
  Home-page: UNKNOWN
6
6
  Author: Innovaser
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env python
2
+ #
3
+ # Copyright 2013 Rodrigo Ancavil del Pino
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License. You may obtain
7
+ # a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+ # License for the specific language governing permissions and limitations
15
+ # under the License.
16
+
17
+ # -*- coding: utf-8 -*-
18
+
19
+ from pyconvert.pyconv import convertJSON2OBJ
20
+ import json
21
+
22
+ doc = {'userid':10010, 'username':'homerJ', 'projects' : [ {"seq" : 1, "name" : "API Develop"}, {"seq": 2, "name" : "Java Apps"}]}
23
+
24
+ class Project(object):
25
+ seq = int
26
+ name = str
27
+
28
+ class User(object):
29
+ userid = int
30
+ username = str
31
+ projects = [Project]
32
+
33
+ c = convertJSON2OBJ(User,doc)
34
+ print "JSON original"
35
+ print "*************"
36
+ print json.dumps(doc, sort_keys=True, indent=2, separators=(',',': '))
37
+ print
38
+ print "Python obj "
39
+ print "***************"
40
+ print "User data "
41
+ print "---------------"
42
+ print "userid : %d "%c.userid
43
+ print "username : %s "%c.username
44
+ print
45
+ print "User's projects"
46
+ print "---------------"
47
+ for project in c.projects:
48
+ print "\tprojects.seq : %d "%project.seq
49
+ print "\tprojects.name : %s "%project.name
50
+ print
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env python
2
+ #
3
+ # Copyright 2013 Rodrigo Ancavil del Pino
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License. You may obtain
7
+ # a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+ # License for the specific language governing permissions and limitations
15
+ # under the License.
16
+
17
+ # -*- coding: utf-8 -*-
18
+
19
+ from pyconvert.pyconv import convertJSON2OBJ
20
+ import json
21
+
22
+ doc = {'sender' : { 'userid' : 1220000, 'username' : 'Fred '}, 'receiver' : { 'userid' : 203201, 'username' : 'Kathy' } , "num" : 1, "text" : 'Hey please send me the mail'}
23
+
24
+ class User(object):
25
+ userid = int
26
+ username = str
27
+
28
+ class Message(object):
29
+ num = int
30
+ text = str
31
+ sender = User
32
+ receiver = User
33
+
34
+ c = convertJSON2OBJ(Message,doc)
35
+ print "JSON original"
36
+ print "*************"
37
+ print json.dumps(doc, sort_keys=True, indent=2, separators=(',',': '))
38
+ print
39
+ print "Python obj "
40
+ print "***************"
41
+ print "Message "
42
+ print "---------------"
43
+ print "num : %d "%c.num
44
+ print "text : %s "%c.text
45
+ print
46
+ print "Sender "
47
+ print "---------------"
48
+ print "c.sender.userid : %d "%c.sender.userid
49
+ print "c.sender.username : %s "%c.sender.username
50
+ print "Receiver "
51
+ print "---------------"
52
+ print "c.receiver.userid : %d "%c.receiver.userid
53
+ print "c.receiver.username : %s "%c.receiver.username
54
+ print
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env python
2
+ #
3
+ # Copyright 2013 Rodrigo Ancavil del Pino
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License. You may obtain
7
+ # a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+ # License for the specific language governing permissions and limitations
15
+ # under the License.
16
+
17
+ # -*- coding: utf-8 -*-
18
+
19
+ from pyconvert.pyconv import convertJSON2OBJ
20
+ import json
21
+
22
+ doc = [{'username' : 'fred', 'age' : 20} , {'username' : 'barney', 'age' : 20}]
23
+
24
+ class User(object):
25
+ username = str
26
+ age = int
27
+
28
+ users = convertJSON2OBJ(User,doc)
29
+ print "JSON original"
30
+ print "*************"
31
+ print json.dumps(doc, sort_keys=True, indent=2, separators=(',',': '))
32
+ print
33
+ print "Python obj "
34
+ print "***************"
35
+ print "Users "
36
+ print "---------------"
37
+ for user in users:
38
+ print "\tuser.username : %s "%user.username
39
+ print "\tuser.age : %s "%user.age
40
+ print
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env python
2
+ #
3
+ # Copyright 2013 Rodrigo Ancavil del Pino
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License. You may obtain
7
+ # a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+ # License for the specific language governing permissions and limitations
15
+ # under the License.
16
+
17
+ # -*- coding: utf-8 -*-
18
+
19
+ from pyconvert.pyconv import convertXML2OBJ
20
+ from xml.dom.minidom import parseString
21
+
22
+ """ This example convert an xml document in a python object """
23
+
24
+ person_xml = "<Person>\
25
+ <name>Steve</name>\
26
+ <age>24</age>\
27
+ </Person>"
28
+
29
+ class Person(object):
30
+ name = str
31
+ age = int
32
+
33
+ xml_doc = parseString(person_xml)
34
+
35
+ person_obj = convertXML2OBJ(Person, xml_doc)
36
+
37
+ print "XML original"
38
+ print "============"
39
+ print xml_doc.toprettyxml()
40
+ print
41
+ print "Python object"
42
+ print "============="
43
+ print "person_obj.name = %s"%person_obj.name
44
+ print "person_obj.age = %d"%person_obj.age
@@ -0,0 +1,72 @@
1
+ #!/usr/bin/env python
2
+ #
3
+ # Copyright 2013 Rodrigo Ancavil del Pino
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License. You may obtain
7
+ # a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+ # License for the specific language governing permissions and limitations
15
+ # under the License.
16
+
17
+ # -*- coding: utf-8 -*-
18
+
19
+ from pyconvert.pyconv import convertXML2OBJ
20
+ from xml.dom.minidom import parseString
21
+
22
+ class Band(object):
23
+ name = str
24
+ genre = str
25
+
26
+ class Album(object):
27
+ name = str
28
+ year = int
29
+
30
+ class Music(object):
31
+ Band = Band
32
+ Albums = [Album]
33
+
34
+ doc = """
35
+ <Music>
36
+ <Band>
37
+ <name>Herbie Hancock</name>
38
+ <genre>Jazz</genre>
39
+ </Band>
40
+ <Albums>
41
+ <Album>
42
+ <name>HeadHunters</name>
43
+ <year>1973</year>
44
+ </Album>
45
+ <Album>
46
+ <name>Sextant</name>
47
+ <year>1973</year>
48
+ </Album>
49
+ </Albums>
50
+ </Music>
51
+ """
52
+ if __name__ == '__main__':
53
+ xml = parseString(doc)
54
+ c = convertXML2OBJ(Music,xml.documentElement)
55
+
56
+ print "XML original"
57
+ print "************"
58
+ print xml.toxml()
59
+ print
60
+ print "Python OBJ"
61
+ print "*************"
62
+ print "Band "
63
+ print "------------------------"
64
+ print "Name : %s"%c.Band.name
65
+ print "Genre : %s"%c.Band.genre
66
+ print
67
+ print "Albums "
68
+ print "------------------------"
69
+ for a in c.Albums:
70
+ print "\tAlbum name : %s"%a.name
71
+ print "\tYear : %d"%a.year
72
+ print
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env python
2
+ #
3
+ # Copyright 2013 Rodrigo Ancavil del Pino
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License. You may obtain
7
+ # a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+ # License for the specific language governing permissions and limitations
15
+ # under the License.
16
+
17
+ # -*- coding: utf-8 -*-
18
+
19
+ from pyconvert.pyconv import convertXML2OBJ
20
+ from xml.dom.minidom import parseString
21
+
22
+ xmlDoc = """
23
+ <Book>
24
+ <isbn>0596001282</isbn>
25
+ <language>English</language>
26
+ <title>Python and XML</title>
27
+ <authors>
28
+ <author>Christopher A. Jones</author>
29
+ <author>Fred L.Drake, Jr.</author>
30
+ </authors>
31
+ <url>http://www.amazon.com/Python-XML-Christopher-A-Jones/dp/0596001282</url>
32
+ </Book>
33
+ """
34
+
35
+ class Book(object):
36
+ isbn = long
37
+ language = str
38
+ title = str
39
+ authors = [str]
40
+ url = str
41
+
42
+ xml = parseString(xmlDoc)
43
+ obj = convertXML2OBJ(Book,xml.documentElement)
44
+
45
+ print "XML original"
46
+ print "************"
47
+ print xml.toxml()
48
+ print
49
+ print "Python Object"
50
+ print "*************"
51
+ print "isbn : %ld "%obj.isbn
52
+ print "language : %s "%obj.language
53
+ print "title : %s "%obj.title
54
+ print "url : %s "%obj.url
55
+ print "Authors"
56
+ for author in obj.authors:
57
+ print "\t %s "%author
58
+ print
@@ -18,13 +18,16 @@
18
18
 
19
19
  import inspect
20
20
  import json
21
- import pymongo
22
21
  from xml.dom.minidom import parseString
23
- from bson.objectid import ObjectId
24
22
 
25
23
  class Encoder(json.JSONEncoder):
26
24
  """ class to handle ObjectId on a json document """
27
25
  def default(self,obj):
26
+ try:
27
+ from bson.objectid import ObjectId
28
+ except ImportError:
29
+ raise Exception("You must have bson installed")
30
+
28
31
  if isinstance(obj, ObjectId):
29
32
  return unicode(obj)
30
33
  else:
@@ -43,6 +46,8 @@ def check_type(obj):
43
46
  return True
44
47
  elif isinstance(obj,str):
45
48
  return True
49
+ elif isinstance(obj,unicode):
50
+ return True
46
51
 
47
52
  def convert(class_to_convert,type_to_convert):
48
53
  """ function to convert an python object in a str or dict (with a representation of xml or json)
@@ -61,7 +66,7 @@ def convert(class_to_convert,type_to_convert):
61
66
  data = "<"+class_name+">"
62
67
  for v in filter_attr:
63
68
  d = getattr(class_to_convert,v)
64
- if type(d).__name__ == "instance":
69
+ if not check_type(d) and not isinstance(d,list):
65
70
  data += convert(d,type_to_convert)
66
71
  elif isinstance(d,list):
67
72
  data += "<"+v+"s>"
@@ -83,7 +88,7 @@ def convert(class_to_convert,type_to_convert):
83
88
  data = dict()
84
89
  for v in filter_attr:
85
90
  d = getattr(class_to_convert,v)
86
- if type(d).__name__ == "instance":
91
+ if not check_type(d) and not isinstance(d,list):
87
92
  data[v] = convert(d,type_to_convert)
88
93
  elif isinstance(d,list):
89
94
  list_of_element = list()
@@ -93,7 +98,7 @@ def convert(class_to_convert,type_to_convert):
93
98
  elif check_type(a):
94
99
  list_of_element.append(a)
95
100
 
96
- data[v+"s"] = list_of_element
101
+ data[v+"s"] = list_of_element
97
102
  else:
98
103
  data[v] = d
99
104
 
@@ -166,6 +171,20 @@ def convertJSON2XML(root_element, json_doc):
166
171
  xml_document = convertJSON2STR(root_element, json_doc)
167
172
  return parseString(xml_document.encode('ascii', 'xmlcharrefreplace').encode("utf-8").replace("\n","").replace("&",""))
168
173
 
174
+ def convertList2JSON(list_of_classes):
175
+ """ function to convert a list of classes in a json """
176
+ return json.dumps([convert2JSON(x) for x in list_of_classes])
177
+
178
+ def convertList2XML(list_of_classes, root_element="list"):
179
+ """ function to convert a list of classes in xml """
180
+ xml_docs = [convert(x,"xml") for x in list_of_classes]
181
+ xml_doc = "<"+root_element+">\n"
182
+ for d in xml_docs:
183
+ xml_doc += d
184
+ xml_doc += "</"+root_element+">"
185
+
186
+ return parseString(xml_doc.encode('ascii', 'xmlcharrefreplace').encode("utf-8").replace("\n","").replace("&",""))
187
+
169
188
  def convertMongo2XML(root_element, data):
170
189
  """ function to convert a document or documents recovered from mongoDB in a xml document
171
190
  parameters:
@@ -174,6 +193,11 @@ def convertMongo2XML(root_element, data):
174
193
  returns:
175
194
  xml.dom.minidom.Document
176
195
  """
196
+ try:
197
+ import pymongo
198
+ except ImportError:
199
+ raise Exception("You must install pymongo")
200
+
177
201
  if isinstance(data, pymongo.cursor.Cursor):
178
202
  data_list = list(data)
179
203
  return convertJSON2XML(root_element,data_list)
@@ -189,10 +213,107 @@ def convertMongo2JSON(data):
189
213
  returns:
190
214
  json (python dictionary)
191
215
  """
216
+ try:
217
+ import pymongo
218
+ except ImportError:
219
+ raise Exception("You must install pymongo")
220
+
192
221
  if isinstance(data, pymongo.cursor.Cursor):
193
222
  l = list()
194
223
  for d in list(data):
195
224
  l.append(json.loads(json.dumps(d, cls=Encoder)))
196
225
  return l
197
226
  elif isinstance(data,dict):
198
- return json.loads(json.dumps(data, cls=Encoder))
227
+ return json.loads(json.dumps(data, cls=Encoder))
228
+
229
+ def getValue(e):
230
+ """ function that returns the value of a text node from xml element
231
+ """
232
+ if e[0].childNodes[0].nodeType == e[0].TEXT_NODE:
233
+ return e[0].childNodes[0].nodeValue
234
+ else:
235
+ return e
236
+
237
+ def convertXML2OBJ(cls, xml):
238
+ """ function to convert xml to python object
239
+ parameters:
240
+ cls, is the class that represents to the xml.
241
+ xml, is the xml element to convert into a python object
242
+
243
+ example:
244
+ class Person:
245
+ name = str
246
+ age = int
247
+
248
+ <Person>
249
+ <name>Steve</name>
250
+ <age>41</age>
251
+ <Person>
252
+ returns:
253
+ python object
254
+ """
255
+ cls_dict = {}
256
+ for attr in filter(lambda x : x not in dir(object),dir(cls)):
257
+ attr_type = cls.__dict__[attr]
258
+ xml_value = xml.getElementsByTagName(attr)
259
+ if len(xml_value)>0:
260
+ if isinstance(attr_type,list) and attr_type[0] in [int, float, long, str]:
261
+ cls_dict[attr] = [x.childNodes[0].nodeValue for x in xml_value[0].childNodes if x.nodeType == x.ELEMENT_NODE]
262
+ elif attr_type not in [int, float, long, str] and not hasattr(attr_type,'__module__'):
263
+ l = []
264
+ for xelem in xml.getElementsByTagName(attr_type[0].__name__):
265
+ l.append(convertXML2OBJ(attr_type[0],xelem))
266
+ cls_dict[attr] = l
267
+ elif attr_type not in [int, float, long, str] and hasattr(attr_type,'__module__'):
268
+ cls_dict[attr] = convertXML2OBJ(attr_type,xml_value[0])
269
+ else:
270
+ type_conv = cls.__dict__[attr]
271
+ cls_dict[attr] = type_conv(getValue(xml_value))
272
+
273
+ c = cls()
274
+ c.__dict__ = cls_dict
275
+ return c
276
+
277
+ def convertJSON2OBJ(cls, json_doc):
278
+ """ function that convert an json in a python object
279
+ parameters:
280
+ cls, is the class that represents to the json.
281
+ doc, is the json documment
282
+
283
+ example:
284
+ class Person:
285
+ name = str
286
+ age = int
287
+
288
+ {
289
+ "name" : "Steve"
290
+ "age" : 41
291
+ }
292
+
293
+ returns:
294
+ python oject
295
+ """
296
+ attrs = {}
297
+ if isinstance(json_doc,list):
298
+ l = []
299
+ for a in json_doc:
300
+ b = convertJSON2OBJ(cls, a)
301
+ l.append(b)
302
+ return l
303
+ else:
304
+ for key in json_doc.keys():
305
+ value = json_doc[key]
306
+ if not isinstance(value,list) and not isinstance(value,dict):
307
+ type_conv = type(value)
308
+ attrs[key] = type_conv(value)
309
+ elif isinstance(value,dict) and not isinstance(cls.__dict__[key],list):
310
+ attrs[key] = convertJSON2OBJ(cls.__dict__[key],value)
311
+ else:
312
+ l = []
313
+ for a in value:
314
+ b = convertJSON2OBJ(cls.__dict__[key][0], a)
315
+ l.append(b)
316
+ attrs[key] = l
317
+ c = cls()
318
+ c.__dict__ = attrs
319
+ return c
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 1.0
2
2
  Name: pyconvert
3
- Version: 0.3.alpha
3
+ Version: 0.6.1
4
4
  Summary: UNKNOWN
5
5
  Home-page: UNKNOWN
6
6
  Author: Innovaser
@@ -1,7 +1,13 @@
1
1
  setup.py
2
2
  demos/__init__.py
3
+ demos/json_2_obj_v1.py
4
+ demos/json_2_obj_v2.py
5
+ demos/json_2_obj_v3.py
3
6
  demos/object_2_json.py
4
7
  demos/object_2_xml.py
8
+ demos/xml_2_object_v1.py
9
+ demos/xml_2_object_v2.py
10
+ demos/xml_2_object_v3.py
5
11
  pyconvert/__init__.py
6
12
  pyconvert/pyconv.py
7
13
  pyconvert.egg-info/PKG-INFO
@@ -23,7 +23,7 @@ except ImportError:
23
23
 
24
24
  distutils.core.setup(
25
25
  name='pyconvert',
26
- version = '0.3.alpha',
26
+ version = '0.6.1',
27
27
  packages=['pyconvert','demos'],
28
28
  author='Innovaser',
29
29
  author_email='rancavil@innovaser.cl',
File without changes