Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nderkach master #36

Merged
merged 8 commits into from
Nov 6, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
163 changes: 102 additions & 61 deletions ebaysdk/__init__.py

Large diffs are not rendered by default.

85 changes: 43 additions & 42 deletions ebaysdk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@

import xml.etree.ElementTree as ET
import re
from StringIO import StringIO

import sys

from io import BytesIO

class object_dict(dict):
"""object view of dict, you can
>>> a = object_dict()
Expand Down Expand Up @@ -49,7 +51,7 @@ def getvalue(self, item, value=None):
return self.get(item, {}).get('value', value)

def __getstate__(self):
return self.items()
return list(self.items())

def __setstate__(self, items):
self.update(items)
Expand All @@ -64,7 +66,7 @@ def _parse_node(self, node):
# Save attrs and text, hope there will not be a child with same name
if node.text:
node_tree.value = node.text
for (k,v) in node.attrib.items():
for (k,v) in list(node.attrib.items()):
k,v = self._namespace_split(k, object_dict({'value':v}))
node_tree[k] = v
#Save childrens
Expand Down Expand Up @@ -116,7 +118,7 @@ class Struct(object):
"""Emulate a cross over between a dict() and an object()."""
def __init__(self, entries, default=None, nodefault=False):
# ensure all keys are strings and nothing else
entries = dict([(str(x), y) for x, y in entries.items()])
entries = dict([(str(x), y) for x, y in list(entries.items())])
self.__dict__.update(entries)
self.__default = default
self.__nodefault = nodefault
Expand Down Expand Up @@ -192,9 +194,9 @@ def __contains__(self, item):
"""
return item in self.__dict__

def __nonzero__(self):
def __bool__(self):
"""Returns whether the instance evaluates to False"""
return bool(self.items())
return bool(list(self.items()))

def has_key(self, item):
"""Emulate dict.has_key() functionality.
Expand All @@ -214,7 +216,7 @@ def items(self):
>>> obj.items()
[('a', 'b')]
"""
return [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_Struct__')]
return [(k, v) for (k, v) in list(self.__dict__.items()) if not k.startswith('_Struct__')]

def keys(self):
"""Emulate dict.keys() functionality.
Expand All @@ -223,7 +225,7 @@ def keys(self):
>>> obj.keys()
['a']
"""
return [k for (k, _v) in self.__dict__.items() if not k.startswith('_Struct__')]
return [k for (k, _v) in list(self.__dict__.items()) if not k.startswith('_Struct__')]

def values(self):
"""Emulate dict.values() functionality.
Expand All @@ -232,10 +234,10 @@ def values(self):
>>> obj.values()
['b']
"""
return [v for (k, v) in self.__dict__.items() if not k.startswith('_Struct__')]
return [v for (k, v) in list(self.__dict__.items()) if not k.startswith('_Struct__')]

def __repr__(self):
return "<Struct: %r>" % dict(self.items())
return "<Struct: %r>" % dict(list(self.items()))

def as_dict(self):
"""Return a dict representing the content of this struct."""
Expand Down Expand Up @@ -287,15 +289,13 @@ def make_struct(obj, default=None, nodefault=False):
"""
if type(obj) == type(Struct):
return obj
if (not hasattr(obj, '__dict__')) and hasattr(obj, 'iterkeys'):
# this should be a dict
if type(obj) == dict:
struc = Struct(obj, default, nodefault)
# handle recursive sub-dicts
for key, val in obj.items():
for key, val in list(obj.items()):
setattr(struc, key, make_struct(val, default, nodefault))
return struc
elif hasattr(obj, '__delslice__') and hasattr(obj, '__getitem__'):
#
elif type(obj) == list:
return [make_struct(v, default, nodefault) for v in obj]
else:
return obj
Expand All @@ -308,22 +308,20 @@ def _convert_dict_to_xml_recurse(parent, dictitem, listnames):
assert not isinstance(dictitem, list)

if isinstance(dictitem, dict):
for (tag, child) in sorted(dictitem.iteritems()):
for (tag, child) in sorted(dictitem.items()):
if isinstance(child, list):
# iterate through the array and convert
listelem = ET.Element('')
listelem2 = ET.Element(tag)
parent.append(listelem)
listparent = ET.Element(tag if tag in listnames.keys() else '')
parent.append(listparent)
for listchild in child:
elem = ET.Element(listnames.get(tag, listelem2.tag))
listelem.append(elem)
_convert_dict_to_xml_recurse(elem, listchild, listnames)
item = ET.SubElement(listparent, listnames.get(tag, tag))
_convert_dict_to_xml_recurse(item, listchild, listnames)
else:
elem = ET.Element(tag)
parent.append(elem)
_convert_dict_to_xml_recurse(elem, child, listnames)
elif not dictitem is None:
parent.text = unicode(dictitem)
parent.text = str(dictitem)


def dict2et(xmldict, roottag='data', listnames=None):
Expand All @@ -333,20 +331,20 @@ def dict2et(xmldict, roottag='data', listnames=None):

>>> data = {"nr": "xq12", "positionen": [{"m": 12}, {"m": 2}]}
>>> root = dict2et(data)
>>> ET.tostring(root)
'<data><nr>xq12</nr><positionen><item><m>12</m></item><item><m>2</m></item></positionen></data>'
>>> ET.tostring(root, encoding="unicode").replace('<>', '').replace('</>','')
'<data><nr>xq12</nr><positionen><m>12</m></positionen><positionen><m>2</m></positionen></data>'

Per default ecerything ins put in an enclosing '<data>' element. Also per default lists are converted
to collecitons of `<item>` elements. But by provding a mapping between list names and element names,
you van generate different elements::

>>> data = {"positionen": [{"m": 12}, {"m": 2}]}
>>> root = dict2et(data, roottag='xml')
>>> ET.tostring(root)
'<xml><positionen><item><m>12</m></item><item><m>2</m></item></positionen></xml>'
>>> ET.tostring(root, encoding="unicode").replace('<>', '').replace('</>','')
'<xml><positionen><m>12</m></positionen><positionen><m>2</m></positionen></xml>'

>>> root = dict2et(data, roottag='xml', listnames={'positionen': 'position'})
>>> ET.tostring(root)
>>> ET.tostring(root, encoding="unicode").replace('<>', '').replace('</>','')
'<xml><positionen><position><m>12</m></position><position><m>2</m></position></positionen></xml>'

>>> data = {"kommiauftragsnr":2103839, "anliefertermin":"2009-11-25", "prioritaet": 7,
Expand All @@ -357,7 +355,8 @@ def dict2et(xmldict, roottag='data', listnames=None):
... ]}

>>> print ET.tostring(dict2et(data, 'kommiauftrag',
... listnames={'positionen': 'position', 'versandeinweisungen': 'versandeinweisung'}))
... listnames={'positionen': 'position', 'versandeinweisungen': 'versandeinweisung'}),
... encoding="unicode").replace('<>', '').replace('</>','')
... # doctest: +SKIP
'''<kommiauftrag>
<anliefertermin>2009-11-25</anliefertermin>
Expand Down Expand Up @@ -398,17 +397,17 @@ def list2et(xmllist, root, elementname):
return basexml.find(root)


def dict2xml(datadict, roottag='TRASHME', listnames=None, pretty=False):
def dict2xml(datadict, roottag='', listnames=None, pretty=False):
"""
Converts a dictionary to an UTF-8 encoded XML string.
See also dict2et()
"""
root = dict2et(datadict, roottag, listnames)

xml = to_string(root, pretty=pretty)
xml = xml.replace('<>', '').replace('</>','')
return xml.replace('<%s>' % roottag, '').replace('</%s>' % roottag, '')

return xml


def list2xml(datalist, roottag, elementname, pretty=False):
"""Converts a list to an UTF-8 encoded XML string.

Expand All @@ -418,17 +417,20 @@ def list2xml(datalist, roottag, elementname, pretty=False):
return to_string(root, pretty=pretty)


def to_string(root, encoding='utf-8', pretty=False):
def to_string(root, pretty=False):
"""Converts an ElementTree to a string"""

if pretty:
indent(root)

tree = ET.ElementTree(root)
fileobj = StringIO()
#fileobj.write('<?xml version="1.0" encoding="%s"?>' % encoding)
fileobj = BytesIO()

# asdf fileobj.write('<?xml version="1.0" encoding="%s"?>' % encoding)

if pretty:
fileobj.write('\n')

tree.write(fileobj, 'utf-8')
return fileobj.getvalue()

Expand Down Expand Up @@ -467,7 +469,7 @@ def test():
"artnr": "14695",
"batchnr": "3104247"}
xmlstr = dict2xml(data, roottag='warenzugang')
assert xmlstr == ('<?xml version="1.0" encoding="utf-8"?><warenzugang><artnr>14695</artnr>'
assert xmlstr == ('<warenzugang><artnr>14695</artnr>'
'<batchnr>3104247</batchnr><guid>3104247-7</guid><menge>7</menge></warenzugang>')

data = {"kommiauftragsnr": 2103839,
Expand All @@ -481,10 +483,10 @@ def test():
"name1": "Uwe Zweihaus",
"name2": "400424990",
"name3": "",
u"strasse": u"Bahnhofstr. 2",
"strasse": "Bahnhofstr. 2",
"land": "DE",
"plz": "42499",
"ort": u"Hücksenwagen",
"ort": "Hücksenwagen",
"positionen": [{"menge": 12,
"artnr": "14640/XL",
"posnr": 1},
Expand All @@ -499,7 +501,7 @@ def test():
"anweisung": "48h vor Anlieferung unter 0900-LOGISTIK avisieren"},
{"guid": "2103839-GuTi",
"bezeichner": "abpackern140",
"anweisung": u"Paletten höchstens auf 140 cm Packen"}]
"anweisung": "Paletten höchstens auf 140 cm Packen"}]
}

xmlstr = dict2xml(data, roottag='kommiauftrag')
Expand Down Expand Up @@ -529,7 +531,6 @@ def test():
"art": "paket"}]}

xmlstr = dict2xml(data, roottag='rueckmeldung')
print xmlstr

if __name__ == '__main__':
import doctest
Expand Down
26 changes: 14 additions & 12 deletions ebaysdk/utils2.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
import cElementTree as ET # for 2.4

import re


from io import BytesIO

class object_dict(dict):
"""object view of dict, you can
>>> a = object_dict()
Expand Down Expand Up @@ -50,7 +52,7 @@ def getvalue(self, item, value=None):
return self.get(item, object_dict()).get('value', value)

def __getstate__(self):
return self.items()
return list(self.items())

def __setstate__(self, items):
self.update(items)
Expand All @@ -65,7 +67,7 @@ def _parse_node(self, node):
# Save attrs and text, hope there will not be a child with same name
if node.text:
node_tree.value = node.text
for (k,v) in node.attrib.items():
for (k,v) in list(node.attrib.items()):
k,v = self._namespace_split(k, object_dict({'value':v}))
node_tree[k] = v
#Save childrens
Expand Down Expand Up @@ -130,7 +132,7 @@ def tostring(self,d):

def dict2xml(self,map):
if type(map) == object_dict or type(map) == dict:
for key, value in map.items():
for key, value in list(map.items()):
keyo = key
if self.attributes:
# FIXME: This assumes the attributes do not require encoding
Expand Down Expand Up @@ -161,7 +163,7 @@ def dict2xml(self,map):
return self.xml

def encode(self,str1):
if type(str1) != str and type(str1) != unicode:
if type(str1) != str and type(str1) != str:
str1 = str(str1)
if self.encoding:
str1 = str1.encode(self.encoding)
Expand All @@ -184,15 +186,15 @@ def list_to_xml(name, l, stream):
def dict_to_xml(d, root_node_name, stream):
""" Transform a dict into a XML, writing to a stream """
stream.write('\n<' + root_node_name)
attributes = StringIO()
nodes = StringIO()
for item in d.items():
attributes = BytesIO()
nodes = BytesIO()
for item in list(d.items()):
key, value = item
if isinstance(value, dict):
dict_to_xml(value, key, nodes)
elif isinstance(value, list):
list_to_xml(key, value, nodes)
elif isinstance(value, str) or isinstance(value, unicode):
elif isinstance(value, str) or isinstance(value, str):
attributes.write('\n %s="%s" ' % (key, value))
else:
raise TypeError('sorry, we support only dicts, lists and strings')
Expand Down Expand Up @@ -223,15 +225,15 @@ def list_to_dict(l, ignore_root = True):
# like <list><item/><item/><item/><item/><item/></list>
for x in l[2]:
d = list_to_dict(x, False)
for k, v in d.iteritems():
if not inside_dict.has_key(k):
for k, v in d.items():
if k not in inside_dict:
inside_dict[k] = []

inside_dict[k].append(v)

ret = root_dict
if ignore_root:
ret = root_dict.values()[0]
ret = list(root_dict.values())[0]

return ret

Expand Down
18 changes: 9 additions & 9 deletions samples/finding.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,13 @@ def run(opts):
raise Exception(api.error())

if api.response_content():
print "Call Success: %s in length" % len(api.response_content())
print("Call Success: %s in length" % len(api.response_content()))

print "Response code: %s" % api.response_code()
print "Response DOM: %s" % api.response_dom()
print("Response code: %s" % api.response_code())
print("Response DOM: %s" % api.response_dom())

dictstr = "%s" % api.response_dict()
print "Response dictionary: %s..." % dictstr[:250]
print("Response dictionary: %s..." % dictstr[:250])


def run2(opts):
Expand All @@ -70,16 +70,16 @@ def run2(opts):
raise Exception(api.error())

if api.response_content():
print "Call Success: %s in length" % len(api.response_content())
print("Call Success: %s in length" % len(api.response_content()))

print "Response code: %s" % api.response_code()
print "Response DOM: %s" % api.response_dom()
print("Response code: %s" % api.response_code())
print("Response DOM: %s" % api.response_dom())

dictstr = "%s" % api.response_dict()
print "Response dictionary: %s..." % dictstr[:50]
print("Response dictionary: %s..." % dictstr[:50])

if __name__ == "__main__":
print "Finding samples for SDK version %s" % ebaysdk.get_version()
print("Finding samples for SDK version %s" % ebaysdk.get_version())
(opts, args) = init_options()
run(opts)
run2(opts)
Loading