· 8 years ago · Dec 19, 2016, 06:46 AM
1import json
2import logging
3import requests
4import pickle
5
6
7# Non-standard imports
8from requests_oauthlib import OAuth1
9from urlparse import parse_qs
10from urllib import urlencode
11
12
13# Local imports
14# import Etsy-Python
15import Credential_maker
16import decrypt
17
18
19log = logging.getLogger(__name__)
20
21
22class EtsyPasswordError(Exception):
23 """
24 Password error handling
25 """
26
27 def __init__(self, value):
28 self.value = value
29
30 def __str__(self):
31 return repr(self.value)
32
33
34class Etsy(object):
35 """
36 Class creating and making calls for the Etsy API
37 by creating an authorized object with an encrypted
38 credentials file and password for decrypting.
39 """
40
41 def __init__(self, creds_file=None, password=None):
42 """
43 Initializes the object and loads credentials file specified
44 so long as the correct password is supplied.
45
46 Args:
47 creds_file: string. credential file created previously
48 password: string. password used to decrypt file
49
50 Returns:
51 Authorized credentials object to make calls defined
52 in Etsy class
53
54 """
55 if creds_file and password:
56 creds = decrypt.decrypt(creds_file, password)
57 consumer_key = creds['consumer_key']
58 client_secret = creds['client_secret']
59 oauth_token = creds['oauth_token']
60 oauth_token_secret = creds['oauth_token_secret']
61 self.params = {'api_key': consumer_key}
62 self.OAuth_Full = OAuth1(consumer_key,
63 client_secret=client_secret,
64 resource_owner_key=oauth_token,
65 resource_owner_secret=oauth_token_secret)
66
67 # except IOError:
68 # print('Cannot open %s, please check the file.') % creds_file
69
70 def get_user_info(self, user):
71 """
72
73 """
74 URI = '/users/%s' % user
75 Auth = {}
76 if user == '__SELF__':
77 Auth = {'oauth': self.OAuth_Full}
78 response = self.api_call(URI, **Auth)
79 return response
80
81 def getMethodTable(self):
82 """
83 Get a complete list of all of the methods available to the Etsy
84 API
85 """
86 URI = '/'
87 response = self.api_call(URI)
88 return response
89
90 def CompileMethods(self):
91 self.MethodsDict = {}
92 API_Method_Response = self.getMethodTable()
93 for Each_Method in API_Method_Response['results']:
94 self.Method_Dict.update(
95 {Each_Method['name']:
96 {'Name': Each_Method['name'],
97 'URI': Each_Method['uri'],
98 'Visibility': Each_Method['visibility'],
99 'HTTP_Method': Each_Method['http_method'],
100 'Parameters': Each_Method['params'],
101 'Defaults': Each_Method['defaults'],
102 'Type': Each_Method['type'],
103 'Description': Each_Method['description'],
104 }
105 }
106 )
107 return self.MethodsDict
108
109 def findAllShopReceipts(self, shop_id, offset=None):
110 """
111 Method for returning all of the receipts for a given Etsy Shop.
112 Since the Etsy API limits the amount of reciepts you can request in
113 a single call, multiple api calls may be needed to gather the amount
114 of receipts needed. As of this writing the maximum amount of reciepts
115 is capped at 100 per call.
116
117 Args:
118 shop_id: string. Unique shop identifier as indicated from etsy
119 offset: string. Offset the results by a given amount
120
121 Returns:
122 JSON data as recieved from the Etsy API
123 """
124
125 URI = 'shops/%s/receipts/' % shop_id
126 params = {}
127 params['shop_id'] = shop_id
128 oauth = {'oauth': self.OAuth_Full}
129 if offset:
130 params['offset'] = offset
131
132 response = self.api_call(URI, params=params, oauth=oauth)
133 return response
134
135 def api_call(self, URI, method='get', oauth=None,
136 params=None, files=None):
137 """
138 Calls the Etsy API
139
140 Args:
141 URI: Specific url extention to be added to the end of the base url
142 that will change depending on what kind of action requested
143 oauth: passes oauth authentication if needed by the method
144 params: passes parameters if needed
145 files: passes files if needed
146
147 Returns:
148 json data returned from server in response
149
150 """
151 Base_URL = "https://openapi.etsy.com/v2"
152 hooks = {}
153 if oauth:
154 hooks = {'auth': oauth}
155 if params is None:
156 params = {}
157 else:
158 if params is None:
159 params = self.params
160 else:
161 params.update(self.params)
162
163 Full_URL = "%s%s" % (Base_URL, URI)
164 querystr = urlencode(params)
165 if querystr:
166 Full_URL = "%s?%s" % (Full_URL, querystr)
167 response = getattr(requests, method)(Full_URL, files=files, **hooks)
168
169 try:
170 return json.loads(response.text)
171 except (TypeError, ValueError):
172 return response.text