forked from d3v-null/wp-api-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
226 lines (178 loc) · 7.42 KB
/
Copy pathapi.py
File metadata and controls
226 lines (178 loc) · 7.42 KB
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# -*- coding: utf-8 -*-
"""
Wordpress API Class
"""
__title__ = "wordpress-api"
# from requests import request
import logging
from six import text_type, u
from json import dumps as jsonencode
from wordpress.auth import BasicAuth, OAuth, OAuth_3Leg
from wordpress.helpers import StrUtils, UrlUtils
from wordpress.transport import API_Requests_Wrapper
class API(object):
""" API Class """
def __init__(self, url, consumer_key, consumer_secret, **kwargs):
self.logger = logging.getLogger(__name__)
self.requester = API_Requests_Wrapper(url=url, **kwargs)
auth_kwargs = dict(
requester=self.requester,
consumer_key=consumer_key,
consumer_secret=consumer_secret,
)
auth_kwargs.update(kwargs)
auth_class = OAuth
if kwargs.get('basic_auth'):
auth_class = BasicAuth
elif kwargs.get('oauth1a_3leg'):
auth_class = OAuth_3Leg
if kwargs.get('version', '').startswith('wc') and kwargs.get('oauth1a_3leg'):
self.logger.warn("WooCommerce JSON Api does not seem to support 3leg")
self.auth = auth_class(**auth_kwargs)
@property
def url(self):
return self.requester.url
@property
def timeout(self):
return self.requester.timeout
@property
def namespace(self):
return self.requester.api
@property
def version(self):
return self.requester.api_version
@property
def verify_ssl(self):
return self.requester.verify_ssl
@property
def is_ssl(self):
return self.requester.is_ssl
@property
def consumer_key(self):
return self.auth.consumer_key
@property
def consumer_secret(self):
return self.auth.consumer_secret
@property
def callback(self):
return self.auth.callback
def request_post_mortem(self, response=None):
"""
Attempt to diagnose what went wrong in a request
"""
reason = None
remedy = None
response_json = {}
try:
response_json = response.json()
except ValueError:
pass
# import pudb; pudb.set_trace()
request_body = {}
request_url = ""
if hasattr(response, 'request'):
if hasattr(response.request, 'url'):
request_url = response.request.url
if hasattr(response.request, 'body'):
request_body = response.request.body
try_hostname_mismatch = False
if isinstance(response_json, dict) and ('code' in response_json or 'message' in response_json):
reason = u" - ".join([
unicode(response_json.get(key)) for key in ['code', 'message', 'data'] \
if key in response_json
])
code = response_json.get('code')
if code == 'rest_user_invalid_email':
remedy = "Try checking the email %s doesn't already exist" % \
request_body.get('email')
elif code == 'json_oauth1_consumer_mismatch':
remedy = "Try deleting the cached credentials at %s" % \
self.auth.creds_store
elif code == 'woocommerce_rest_cannot_view':
if not self.auth.query_string_auth:
remedy = "Try enabling query_string_auth"
else:
remedy = (
"This error is super generic and can be caused by just "
"about anything. Here are some things to try: \n"
" - Check that the account which as assigned to your "
"oAuth creds has the correct access level\n"
" - Enable logging and check for error messages in "
"wp-content and wp-content/uploads/wc-logs\n"
" - Check that your query string parameters are valid\n"
" - Make sure your server is not messing with authentication headers\n"
" - Try a different endpoint\n"
" - Try enabling HTTPS and using basic authentication\n"
)
elif code == 'woocommerce_rest_authentication_error':
try_hostname_mismatch = True
response_headers = {}
if hasattr(response, 'headers'):
response_headers = response.headers
if not reason or try_hostname_mismatch:
requester_api_url = self.requester.api_url
links = []
if hasattr(response, 'links') and response.links:
links = response.links
elif 'Link' in response_headers:
links = [response_headers['Link']]
if links:
first_link_key = list(links)[0]
header_api_url = links[first_link_key].get('url', '')
if header_api_url:
header_api_url = StrUtils.eviscerate(header_api_url, '/')
if header_api_url and requester_api_url\
and header_api_url != requester_api_url:
reason = "hostname mismatch. %s != %s" % (
header_api_url, requester_api_url
)
header_url = StrUtils.eviscerate(header_api_url, '/')
header_url = StrUtils.eviscerate(header_url, self.requester.api)
header_url = StrUtils.eviscerate(header_url, '/')
remedy = "try changing url to %s" % header_url
msg = u"API call to %s returned \nCODE: %s\nRESPONSE:%s \nHEADERS: %s\nREQ_BODY:%s" % (
request_url,
text_type(response.status_code),
UrlUtils.beautify_response(response),
text_type(response_headers),
repr(request_body)[:1000]
)
if reason:
msg += "\nBecause of %s" % reason
if remedy:
msg += "\n%s" % remedy
raise UserWarning(msg)
def __request(self, method, endpoint, data, **kwargs):
""" Do requests """
endpoint_url = self.requester.endpoint_url(endpoint)
endpoint_url = self.auth.get_auth_url(endpoint_url, method, **kwargs)
auth = self.auth.get_auth()
content_type = kwargs.get('headers', {}).get('content-type', 'application/json')
if data is not None and content_type.startswith('application/json'):
data = jsonencode(data, ensure_ascii=False).encode('utf-8')
response = self.requester.request(
method=method,
url=endpoint_url,
auth=auth,
data=data,
**kwargs
)
if response.status_code not in [200, 201, 202]:
self.request_post_mortem(response)
return response
# TODO add kwargs option for headers
def get(self, endpoint, **kwargs):
""" Get requests """
return self.__request("GET", endpoint, None, **kwargs)
def post(self, endpoint, data, **kwargs):
""" POST requests """
return self.__request("POST", endpoint, data, **kwargs)
def put(self, endpoint, data, **kwargs):
""" PUT requests """
return self.__request("PUT", endpoint, data, **kwargs)
def delete(self, endpoint, **kwargs):
""" DELETE requests """
return self.__request("DELETE", endpoint, None, **kwargs)
def options(self, endpoint, **kwargs):
""" OPTIONS requests """
return self.__request("OPTIONS", endpoint, None, **kwargs)