This repository has been archived by the owner on Mar 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 57
/
http.py
388 lines (315 loc) · 12.3 KB
/
http.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
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# coding: utf-8
from __future__ import unicode_literals
from collections import OrderedDict
from coreapi import exceptions, utils
from coreapi.compat import cookiejar, urlparse
from coreapi.document import Document, Object, Link, Array, Error
from coreapi.transports.base import BaseTransport
from coreapi.utils import guess_filename, is_file, File
import collections
import requests
import itypes
import mimetypes
import uritemplate
import warnings
Params = collections.namedtuple('Params', ['path', 'query', 'data', 'files'])
empty_params = Params({}, {}, {}, {})
class ForceMultiPartDict(dict):
"""
A dictionary that always evaluates as True.
Allows us to force requests to use multipart encoding, even when no
file parameters are passed.
"""
def __bool__(self):
return True
def __nonzero__(self):
return True
class BlockAll(cookiejar.CookiePolicy):
"""
A cookie policy that rejects all cookies.
Used to override the default `requests` behavior.
"""
return_ok = set_ok = domain_return_ok = path_return_ok = lambda self, *args, **kwargs: False
netscape = True
rfc2965 = hide_cookie2 = False
class DomainCredentials(requests.auth.AuthBase):
"""
Custom auth class to support deprecated 'credentials' argument.
"""
allow_cookies = False
credentials = None
def __init__(self, credentials=None):
self.credentials = credentials
def __call__(self, request):
if not self.credentials:
return request
# Include any authorization credentials relevant to this domain.
url_components = urlparse.urlparse(request.url)
host = url_components.hostname
if host in self.credentials:
request.headers['Authorization'] = self.credentials[host]
return request
class CallbackAdapter(requests.adapters.HTTPAdapter):
"""
Custom requests HTTP adapter, to support deprecated callback arguments.
"""
def __init__(self, request_callback=None, response_callback=None):
self.request_callback = request_callback
self.response_callback = response_callback
def send(self, request, **kwargs):
if self.request_callback is not None:
self.request_callback(request)
response = super(CallbackAdapter, self).send(request, **kwargs)
if self.response_callback is not None:
self.response_callback(response)
return response
def _get_method(action):
if not action:
return 'GET'
return action.upper()
def _get_encoding(encoding):
if not encoding:
return 'application/json'
return encoding
def _get_params(method, encoding, fields, params=None):
"""
Separate the params into the various types.
"""
if params is None:
return empty_params
field_map = {field.name: field for field in fields}
path = {}
query = {}
data = {}
files = {}
errors = {}
# Ensure graceful behavior in edge-case where both location='body' and
# location='form' fields are present.
seen_body = False
for key, value in params.items():
if key not in field_map or not field_map[key].location:
# Default is 'query' for 'GET' and 'DELETE', and 'form' for others.
location = 'query' if method in ('GET', 'DELETE') else 'form'
else:
location = field_map[key].location
if location == 'form' and encoding == 'application/octet-stream':
# Raw uploads should always use 'body', not 'form'.
location = 'body'
try:
if location == 'path':
path[key] = utils.validate_path_param(value)
elif location == 'query':
query[key] = utils.validate_query_param(value)
elif location == 'body':
data = utils.validate_body_param(value, encoding=encoding)
seen_body = True
elif location == 'form':
if not seen_body:
data[key] = utils.validate_form_param(value, encoding=encoding)
except exceptions.ParameterError as exc:
errors[key] = "%s" % exc
if errors:
raise exceptions.ParameterError(errors)
# Move any files from 'data' into 'files'.
if isinstance(data, dict):
for key, value in list(data.items()):
if is_file(data[key]):
files[key] = data.pop(key)
return Params(path, query, data, files)
def _get_url(url, path_params):
"""
Given a templated URL and some parameters that have been provided,
expand the URL.
"""
if path_params:
return uritemplate.expand(url, path_params)
return url
def _get_headers(url, decoders):
"""
Return a dictionary of HTTP headers to use in the outgoing request.
"""
accept_media_types = decoders[0].get_media_types()
if '*/*' not in accept_media_types:
accept_media_types.append('*/*')
headers = {
'accept': ', '.join(accept_media_types),
'user-agent': 'coreapi'
}
return headers
def _get_upload_headers(file_obj):
"""
When a raw file upload is made, determine the Content-Type and
Content-Disposition headers to use with the request.
"""
name = guess_filename(file_obj)
content_type = None
content_disposition = None
# Determine the content type of the upload.
if getattr(file_obj, 'content_type', None):
content_type = file_obj.content_type
elif name:
content_type, encoding = mimetypes.guess_type(name)
# Determine the content disposition of the upload.
if name:
content_disposition = 'attachment; filename="%s"' % name
return {
'Content-Type': content_type or 'application/octet-stream',
'Content-Disposition': content_disposition or 'attachment'
}
def _build_http_request(session, url, method, headers=None, encoding=None, params=empty_params):
"""
Make an HTTP request and return an HTTP response.
"""
opts = {
"headers": headers or {}
}
if params.query:
opts['params'] = params.query
if params.data or params.files:
if encoding == 'application/json':
opts['json'] = params.data
elif encoding == 'multipart/form-data':
opts['data'] = params.data
opts['files'] = ForceMultiPartDict(params.files)
elif encoding == 'application/x-www-form-urlencoded':
opts['data'] = params.data
elif encoding == 'application/octet-stream':
if isinstance(params.data, File):
opts['data'] = params.data.content
else:
opts['data'] = params.data
upload_headers = _get_upload_headers(params.data)
opts['headers'].update(upload_headers)
request = requests.Request(method, url, **opts)
return session.prepare_request(request)
def _coerce_to_error_content(node):
"""
Errors should not contain nested documents or links.
If we get a 4xx or 5xx response with a Document, then coerce
the document content into plain data.
"""
if isinstance(node, (Document, Object)):
# Strip Links from Documents, treat Documents as plain dicts.
return OrderedDict([
(key, _coerce_to_error_content(value))
for key, value in node.data.items()
])
elif isinstance(node, Array):
# Strip Links from Arrays.
return [
_coerce_to_error_content(item)
for item in node
if not isinstance(item, Link)
]
return node
def _coerce_to_error(obj, default_title):
"""
Given an arbitrary return result, coerce it into an Error instance.
"""
if isinstance(obj, Document):
return Error(
title=obj.title or default_title,
content=_coerce_to_error_content(obj)
)
elif isinstance(obj, dict):
return Error(title=default_title, content=obj)
elif isinstance(obj, list):
return Error(title=default_title, content={'messages': obj})
elif obj is None:
return Error(title=default_title)
return Error(title=default_title, content={'message': obj})
def _decode_result(response, decoders, force_codec=False):
"""
Given an HTTP response, return the decoded Core API document.
"""
if response.content:
# Content returned in response. We should decode it.
if force_codec:
codec = decoders[0]
else:
content_type = response.headers.get('content-type')
codec = utils.negotiate_decoder(decoders, content_type)
options = {
'base_url': response.url
}
if 'content-type' in response.headers:
options['content_type'] = response.headers['content-type']
if 'content-disposition' in response.headers:
options['content_disposition'] = response.headers['content-disposition']
result = codec.load(response.content, **options)
else:
# No content returned in response.
result = None
# Coerce 4xx and 5xx codes into errors.
is_error = response.status_code >= 400 and response.status_code <= 599
if is_error and not isinstance(result, Error):
default_title = '%d %s' % (response.status_code, response.reason)
result = _coerce_to_error(result, default_title=default_title)
return result
def _handle_inplace_replacements(document, link, link_ancestors):
"""
Given a new document, and the link/ancestors it was created,
determine if we should:
* Make an inline replacement and then return the modified document tree.
* Return the new document as-is.
"""
if not link.transform:
if link.action.lower() in ('put', 'patch', 'delete'):
transform = 'inplace'
else:
transform = 'new'
else:
transform = link.transform
if transform == 'inplace':
root = link_ancestors[0].document
keys_to_link_parent = link_ancestors[-1].keys
if document is None:
return root.delete_in(keys_to_link_parent)
return root.set_in(keys_to_link_parent, document)
return document
class HTTPTransport(BaseTransport):
schemes = ['http', 'https']
def __init__(self, credentials=None, headers=None, auth=None, session=None, request_callback=None, response_callback=None):
if headers:
headers = {key.lower(): value for key, value in headers.items()}
if session is None:
session = requests.Session()
if auth is not None:
session.auth = auth
if not getattr(session.auth, 'allow_cookies', False):
session.cookies.set_policy(BlockAll())
if credentials is not None:
warnings.warn(
"The 'credentials' argument is now deprecated in favor of 'auth'.",
DeprecationWarning
)
auth = DomainCredentials(credentials)
if request_callback is not None or response_callback is not None:
warnings.warn(
"The 'request_callback' and 'response_callback' arguments are now deprecated. "
"Use a custom 'session' instance instead.",
DeprecationWarning
)
session.mount('https://', CallbackAdapter(request_callback, response_callback))
session.mount('http://', CallbackAdapter(request_callback, response_callback))
self._headers = itypes.Dict(headers or {})
self._session = session
@property
def headers(self):
return self._headers
def transition(self, link, decoders, params=None, link_ancestors=None, force_codec=False):
session = self._session
method = _get_method(link.action)
encoding = _get_encoding(link.encoding)
params = _get_params(method, encoding, link.fields, params)
url = _get_url(link.url, params.path)
headers = _get_headers(url, decoders)
headers.update(self.headers)
request = _build_http_request(session, url, method, headers, encoding, params)
response = session.send(request)
result = _decode_result(response, decoders, force_codec)
if isinstance(result, Document) and link_ancestors:
result = _handle_inplace_replacements(result, link, link_ancestors)
if isinstance(result, Error):
raise exceptions.ErrorMessage(result)
return result