-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtaobao.py
169 lines (141 loc) · 5.58 KB
/
taobao.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# -*- coding: utf-8 -*-
##############################################################################
#
# Python Taobao Open Platform API
# Copyright 2013 wangbuke <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
__version__ = '1.0.0'
import json
import base64
import datetime
from hashlib import md5
import urllib
import urllib2
class TOPException(Exception):
def __init__(self, code, msg):
if type(msg) == unicode:
msg = msg.encode('utf-8')
self.code = code
super(TOPException, self).__init__(msg)
def __str__(self):
return "%s (code=%d)" % (super(TOPException, self).__str__(),
self.code)
__repr__ = __str__
class _O(dict):
"""Makes a dictionary behave like an object."""
def __getattr__(self, name):
try:
return self[name.lower()]
except KeyError:
raise AttributeError(name)
def __setattr__(self, name, value):
self[name.lower] = value
class _Method:
def __init__(self, send, name):
self.__send = send
self.__name = name
def __getattr__(self, name):
return _Method(self.__send, "%s.%s" % (self.__name, name))
def __call__(self, *args, **kwargs):
return self.__send(self.__name, args, **kwargs)
class ServerProxy(object):
def __init__(self,
app_key=None,
app_secret=None,
session=None,
top_url=None):
if not (app_key and app_secret and session):
raise AttributeError(
"app_key and app_secret and session can not be None")
self.app_key = app_key
self.app_secret = app_secret
self.session = session
self.top_url = top_url or "http://gw.api.taobao.com/router/rest"
def _sign(self, params, qhs=False):
'''
Generate API sign code
'''
for k, v in params.iteritems():
if type(v) == int: v = str(v)
elif type(v) == float: v = '%.2f' % v
elif type(v) in (list, set):
v = ','.join([str(i) for i in v])
elif type(v) == bool:
v = 'true' if v else 'false'
elif type(v) == datetime.datetime:
v = v.strftime('%Y-%m-%d %H:%M:%S')
if type(v) == unicode:
params[k] = v.encode('utf-8')
else:
params[k] = v
if qhs:
src = self.app_secret.encode('utf-8') + ''.join(
["%s%s" % (k, v) for k, v in sorted(params.iteritems())
]) + self.app_secret.encode('utf-8')
else:
src = self.app_secret.encode('utf-8') + ''.join(
["%s%s" % (k, v) for k, v in sorted(params.iteritems())])
return md5(src).hexdigest().upper()
def decode_params(top_parameters):
params = {}
param_string = base64.b64decode(top_parameters)
for p in param_string.split('&'):
key, value = p.split('=')
params[key] = value
return params
def _get_timestamp(self):
utc8 = datetime.datetime.utcnow() + datetime.timedelta(hours=8)
strtime = utc8.strftime('%Y-%m-%d %H:%M:%S')
return strtime
def _generate_params(self, method_name, **kwargs):
params = {}
for k, v in kwargs.iteritems():
if v: params[k.lower()] = v
params['app_key'] = self.app_key
params['v'] = '2.0'
params['sign_method'] = 'md5',
params['format'] = 'json'
params['partner_id'] = 'top_%s' % __version__
params['timestamp'] = self._get_timestamp()
params['method'] = method_name
params['session'] = self.session
params['sign'] = self._sign(params)
return params
def execute(self, method_name, **kwargs):
params = self._generate_params(method_name, **kwargs)
urlopen = urllib2.urlopen(self.top_url, urllib.urlencode(params))
rsp = urlopen.read()
rsp = json.loads(rsp, strict=False, object_hook=lambda x: _O(x))
if rsp.has_key('error_response'):
error_code = rsp['error_response']['code']
if 'sub_msg' in rsp['error_response']:
msg = rsp['error_response']['sub_msg']
else:
msg = rsp['error_response']['msg']
raise TOPException(error_code, msg)
else:
rsp = rsp[method_name.replace('.', '_')[7:] + '_response']
return rsp
def __request(self, method_name, *args, **kwargs):
return self.execute(method_name, **kwargs)
def __getattr__(self, name):
return _Method(self.__request, name)
if __name__ == '__main__':
top = taobao.ServerProxy(app_key="xxx", app_secret="xxx", session="xxx")
seller = top.taobao.user.seller.get(fields=['nick', 'sex'])
print seller
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: