Debian Codegraph @

mechanize/_response.py

raw symbols SCIP
1 """Response classes.
2
3 The seek_wrapper code is not used if you're using UserAgent with
4 .set_seekable_responses(False), or if you're using the urllib2-level interface
5 HTTPEquivProcessor. Class closeable_response is instantiated by some handlers
6 (AbstractHTTPHandler), but the closeable_response interface is only depended
7 upon by Browser-level code. Function upgrade_response is only used if you're
8 using Browser.
9
10
11 Copyright 2006 John J. Lee <[email protected]>
12
13 This code is free software; you can redistribute it and/or modify it
14 under the terms of the BSD or ZPL 2.1 licenses (see the file LICENSE
15 included with the distribution).
16
17 """
18
19 from __future__ import absolute_import
20 from functools import partial
21 import copy
22 from io import BytesIO
23
24 from ._headersutil import normalize_header_name
25 from .polyglot import HTTPError, create_response_info
26
27
28 def len_of_seekable(file_):
29 # this function exists because evaluation of len(file_.getvalue()) on every
30 # .read() from seek_wrapper would be O(N**2) in number of .read()s
31 pos = file_.tell()
32 file_.seek(0, 2) # to end
33 try:
34 return file_.tell()
35 finally:
36 file_.seek(pos)
37
38
39 # XXX Andrew Dalke kindly sent me a similar class in response to my request on
40 # comp.lang.python, which I then proceeded to lose. I wrote this class
41 # instead, but I think he's released his code publicly since, could pinch the
42 # tests from it, at least...
43
44
45 # For testing seek_wrapper invariant (note that
46 # test_urllib2.HandlerTest.test_seekable is expected to fail when this
47 # invariant checking is turned on). The invariant checking is done by module
48 # ipdc, which is available here:
49 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/436834
50 # from ipdbc import ContractBase
51 # class seek_wrapper(ContractBase):
52 class seek_wrapper:
53 """Adds a seek method to a file object.
54
55 This is only designed for seeking on readonly file-like objects.
56
57 Wrapped file-like object must have a read method. The readline method is
58 only supported if that method is present on the wrapped object. The
59 readlines method is always supported. xreadlines and iteration are
60 supported only for Python 2.2 and above.
61
62 Public attributes:
63
64 wrapped: the wrapped file object
65 is_closed: true iff .close() has been called
66
67 WARNING: All other attributes of the wrapped object (ie. those that are not
68 one of wrapped, read, readline, readlines, xreadlines, __iter__ and next)
69 are passed through unaltered, which may or may not make sense for your
70 particular file object.
71
72 """
73
74 # General strategy is to check that cache is full enough, then delegate to
75 # the cache (self.__cache, which is a BytesIO instance). A seek
76 # position (self.__pos) is maintained independently of the cache, in order
77 # that a single cache may be shared between multiple seek_wrapper objects.
78 # Copying using module copy shares the cache in this way.
79
80 def __init__(self, wrapped):
81 self.wrapped = wrapped
82 self.__read_complete_state = [False]
83 self.__is_closed_state = [False]
84 self.__have_readline = hasattr(self.wrapped, "readline")
85 self.__cache = BytesIO()
86 self.__pos = 0 # seek position
87
88 def invariant(self):
89 # The end of the cache is always at the same place as the end of the
90 # wrapped file (though the .tell() method is not required to be present
91 # on wrapped file).
92 return self.wrapped.tell() == len(self.__cache.getvalue())
93
94 def close(self):
95 self.wrapped.close()
96 self.is_closed = True
97
98 def __getattr__(self, name):
99 if name == "is_closed":
100 return self.__is_closed_state[0]
101 elif name == "read_complete":
102 return self.__read_complete_state[0]
103
104 wrapped = self.__dict__.get("wrapped")
105 if wrapped:
106 return getattr(wrapped, name)
107
108 return getattr(self.__class__, name)
109
110 def __setattr__(self, name, value):
111 if name == "is_closed":
112 self.__is_closed_state[0] = bool(value)
113 elif name == "read_complete":
114 if not self.is_closed:
115 self.__read_complete_state[0] = bool(value)
116 else:
117 self.__dict__[name] = value
118
119 def seek(self, offset, whence=0):
120 assert whence in [0, 1, 2]
121
122 # how much data, if any, do we need to read?
123 if whence == 2: # 2: relative to end of *wrapped* file
124 if offset < 0:
125 raise ValueError("negative seek offset")
126 # since we don't know yet where the end of that file is, we must
127 # read everything
128 to_read = None
129 else:
130 if whence == 0: # 0: absolute
131 if offset < 0:
132 raise ValueError("negative seek offset")
133 dest = offset
134 else: # 1: relative to current position
135 pos = self.__pos
136 if pos < offset:
137 raise ValueError("seek to before start of file")
138 dest = pos + offset
139 end = len_of_seekable(self.__cache)
140 to_read = dest - end
141 if to_read < 0:
142 to_read = 0
143
144 if to_read != 0:
145 self.__cache.seek(0, 2)
146 if to_read is None:
147 assert whence == 2
148 self.__cache.write(self.wrapped.read())
149 self.read_complete = True
150 self.__pos = self.__cache.tell() - offset
151 else:
152 data = self.wrapped.read(to_read)
153 if not data:
154 self.read_complete = True
155 else:
156 self.__cache.write(data)
157 # Don't raise an exception even if we've seek()ed past the end
158 # of .wrapped, since fseek() doesn't complain in that case.
159 # Also like fseek(), pretend we have seek()ed past the end,
160 # i.e. not:
161 # self.__pos = self.__cache.tell()
162 # but rather:
163 self.__pos = dest
164 else:
165 self.__pos = dest
166
167 def tell(self):
168 return self.__pos
169
170 def __copy__(self):
171 cpy = self.__class__(self.wrapped)
172 cpy.__cache = self.__cache
173 cpy.__read_complete_state = self.__read_complete_state
174 cpy.__is_closed_state = self.__is_closed_state
175 return cpy
176
177 def get_data(self):
178 pos = self.__pos
179 try:
180 self.seek(0)
181 return self.read(-1)
182 finally:
183 self.__pos = pos
184
185 def read(self, size=-1):
186 pos = self.__pos
187 end = len_of_seekable(self.__cache)
188 available = end - pos
189
190 # enough data already cached?
191 if size <= available and size != -1:
192 self.__cache.seek(pos)
193 self.__pos = pos + size
194 return self.__cache.read(size)
195
196 # no, so read sufficient data from wrapped file and cache it
197 self.__cache.seek(0, 2)
198 if size == -1:
199 self.__cache.write(self.wrapped.read())
200 self.read_complete = True
201 else:
202 to_read = size - available
203 assert to_read > 0
204 data = self.wrapped.read(to_read)
205 if not data:
206 self.read_complete = True
207 else:
208 self.__cache.write(data)
209 self.__cache.seek(pos)
210
211 data = self.__cache.read(size)
212 self.__pos = self.__cache.tell()
213 assert self.__pos == pos + len(data)
214 return data
215
216 def readline(self, size=-1):
217 if not self.__have_readline:
218 raise NotImplementedError("no readline method on wrapped object")
219
220 # line we're about to read might not be complete in the cache, so
221 # read another line first
222 pos = self.__pos
223 self.__cache.seek(0, 2)
224 data = self.wrapped.readline()
225 if not data:
226 self.read_complete = True
227 else:
228 self.__cache.write(data)
229 self.__cache.seek(pos)
230
231 data = self.__cache.readline()
232 if size != -1:
233 r = data[:size]
234 self.__pos = pos + size
235 else:
236 r = data
237 self.__pos = pos + len(data)
238 return r
239
240 def readlines(self, sizehint=-1):
241 pos = self.__pos
242 self.__cache.seek(0, 2)
243 self.__cache.write(self.wrapped.read())
244 self.read_complete = True
245 self.__cache.seek(pos)
246 data = self.__cache.readlines(sizehint)
247 self.__pos = self.__cache.tell()
248 return data
249
250 def __iter__(self):
251 return self
252
253 def __next__(self):
254 line = self.readline()
255 if not line:
256 raise StopIteration
257 return line
258 next = __next__
259
260 xreadlines = __iter__
261
262 def __repr__(self):
263 return ("<%s at %s whose wrapped object = %r>" %
264 (self.__class__.__name__, hex(abs(id(self))), self.wrapped))
265
266
267 class response_seek_wrapper(seek_wrapper):
268 """
269 Supports copying response objects and setting response body data.
270
271 """
272
273 def __init__(self, wrapped):
274 seek_wrapper.__init__(self, wrapped)
275 self._headers = self.wrapped.info()
276
277 def __copy__(self):
278 cpy = seek_wrapper.__copy__(self)
279 # copy headers from delegate
280 cpy._headers = copy.copy(self.info())
281 return cpy
282
283 # Note that .info() and .geturl() (the only two urllib2 response methods
284 # that are not implemented by seek_wrapper) must be here explicitly rather
285 # than by seek_wrapper's __getattr__ delegation) so that the nasty
286 # dynamically-created HTTPError classes in get_seek_wrapper_class() get the
287 # wrapped object's implementation, and not HTTPError's.
288
289 def info(self):
290 return self._headers
291
292 @property
293 def headers(self):
294 return self._headers
295
296 def geturl(self):
297 return self.wrapped.geturl()
298
299 def set_data(self, data):
300 self.seek(0)
301 self.read()
302 self.close()
303 cache = self._seek_wrapper__cache = BytesIO()
304 cache.write(data)
305 self.seek(0)
306
307
308 class eoffile:
309 # file-like object that always claims to be at end-of-file...
310
311 def read(self, size=-1):
312 return b""
313
314 def readline(self, size=-1):
315 return b""
316
317 def __iter__(self):
318 return self
319
320 def __next__(self):
321 return b""
322 next = __next__
323
324 def close(self):
325 pass
326
327
328 class eofresponse(eoffile):
329 def __init__(self, url, headers, code, msg):
330 self._url = url
331 self._headers = headers
332 self.code = code
333 self.msg = msg
334
335 def geturl(self):
336 return self._url
337
338 def info(self):
339 return self._headers
340
341 @property
342 def headers(self):
343 return self._headers
344
345
346 class closeable_response:
347 """Avoids unnecessarily clobbering urllib.addinfourl methods on .close().
348
349 Only supports responses returned by mechanize.HTTPHandler.
350
351 After .close(), the following methods are supported:
352
353 .read()
354 .readline()
355 .info()
356 .geturl()
357 .__iter__()
358 .next()
359 .close()
360
361 and the following attributes are supported:
362
363 .code
364 .msg
365 .http_version
366
367 Also supports pickling (but the stdlib currently does something to prevent
368 it: http://python.org/sf/1144636).
369
370 """
371 # presence of this attr indicates is useable after .close()
372 closeable_response = None
373
374 def __init__(
375 self, fp, headers, url, code=200, msg='OK', http_version=None):
376 self._set_fp(fp)
377 self._headers = headers
378 self._url = url
379 self.code = code
380 self.msg = msg
381 self.http_version = http_version
382
383 def _set_fp(self, fp):
384 self.fp = fp
385 self.read = self.fp.read
386 self.readline = self.fp.readline
387 if hasattr(self.fp, "readlines"):
388 self.readlines = self.fp.readlines
389 if hasattr(self.fp, "fileno"):
390 self.fileno = self.fp.fileno
391 else:
392 self.fileno = lambda: None
393 self.__iter__ = self.fp.__iter__
394 self.next = partial(next, self.fp)
395
396 def __repr__(self):
397 return '<%s at %s whose fp = %r>' % (self.__class__.__name__,
398 hex(abs(id(self))), self.fp)
399
400 def info(self):
401 return self._headers
402
403 @property
404 def headers(self):
405 return self._headers
406
407 def getcode(self):
408 return self.code
409
410 def get_header_values(self, name):
411 return self._headers.get_all(name)
412
413 def get_all_header_names(self, normalize=True):
414 ans = self._headers.keys()
415 if normalize:
416 ans = list(map(normalize_header_name, ans))
417 return ans
418
419 def __getitem__(self, name):
420 return self._headers[name]
421
422 def get(self, name, default):
423 return self._headers.get(name)
424
425 def geturl(self):
426 return self._url
427
428 def close(self):
429 wrapped = self.fp
430 wrapped.close()
431 new_wrapped = eofresponse(self._url, self._headers, self.code,
432 self.msg)
433 self._set_fp(new_wrapped)
434
435
436 def test_response(data='test data',
437 headers=(),
438 url=None,
439 code=200,
440 msg="OK"):
441 return make_response(data, list(headers), url, code, msg)
442
443
444 _html_header = [("Content-type", "text/html")]
445
446
447 def test_html_response(data='test data',
448 headers=(),
449 url=None,
450 code=200,
451 msg="OK"):
452 return make_response(data, list(headers) + _html_header, url, code, msg)
453
454
455 def make_response(data, headers, url=None, code=200, msg="OK"):
456 """Convenient factory for objects implementing response interface.
457
458 data: string containing response body data
459 headers: sequence of (name, value) pairs
460 url: URL of response
461 code: integer response code (e.g. 200)
462 msg: string response code message (e.g. "OK")
463
464 """
465 mime_headers = make_headers(headers)
466 if not isinstance(data, bytes):
467 data = data.encode('utf-8')
468 r = closeable_response(BytesIO(data), mime_headers, url, code, msg)
469 return response_seek_wrapper(r)
470
471
472 def make_headers(headers):
473 """
474 headers: sequence of (name, value) pairs
475 """
476 hdr_text = []
477 for name_value in headers:
478 hdr_text.append("%s: %s" % name_value)
479 ans = "\n".join(hdr_text)
480 if not isinstance(ans, bytes):
481 ans = ans.encode('iso-8859-1')
482 return create_response_info(BytesIO(ans))
483
484
485 # Rest of this module is especially horrible, but needed, at least until fork
486 # urllib2. Even then, may want to preseve urllib2 compatibility.
487
488
489 def get_seek_wrapper_class(response):
490 # in order to wrap response objects that are also exceptions, we must
491 # dynamically subclass the exception :-(((
492 if (
493 isinstance(response, HTTPError) and
494 not isinstance(response, seek_wrapper)
495 ):
496 if response.__class__.__module__ == "__builtin__":
497 exc_class_name = response.__class__.__name__
498 else:
499 exc_class_name = "%s.%s" % (response.__class__.__module__,
500 response.__class__.__name__)
501
502 class httperror_seek_wrapper(response_seek_wrapper,
503 response.__class__):
504 # this only derives from HTTPError in order to be a subclass --
505 # the HTTPError behaviour comes from delegation
506
507 _exc_class_name = exc_class_name
508
509 def __init__(self, wrapped):
510 response_seek_wrapper.__init__(self, wrapped)
511 # be compatible with undocumented HTTPError attributes :-(
512 self.hdrs = wrapped.info()
513 self.filename = wrapped.geturl()
514
515 def __repr__(self):
516 return ("<%s (%s instance) at %s "
517 "whose wrapped object = %r>" %
518 (self.__class__.__name__, self._exc_class_name,
519 hex(abs(id(self))), self.wrapped))
520
521 wrapper_class = httperror_seek_wrapper
522 else:
523 wrapper_class = response_seek_wrapper
524 return wrapper_class
525
526
527 def needs_seek_wrapper(obj):
528 return (
529 not isinstance(obj, seek_wrapper) and (
530 hasattr(obj, 'seek') or isinstance(obj, HTTPError)
531 or not hasattr(obj, 'get_data')
532 )
533 )
534
535
536 def seek_wrapped_response(response):
537 """Return a copy of response that supports seekable response interface.
538
539 Accepts responses from both mechanize and urllib2 handlers.
540
541 Copes with both ordinary response instances and HTTPError instances (which
542 can't be simply wrapped due to the requirement of preserving the exception
543 base class).
544 """
545 if needs_seek_wrapper(response):
546 wrapper_class = get_seek_wrapper_class(response)
547 response = wrapper_class(response)
548 assert hasattr(response, "get_data")
549 return response
550
551
552 def upgrade_response(response):
553 """Return a copy of response that supports Browser response interface.
554
555 Browser response interface is that of "seekable responses"
556 (response_seek_wrapper), plus the requirement that responses must be
557 useable after .close() (closeable_response).
558
559 Accepts responses from both mechanize and urllib2 handlers.
560
561 Copes with both ordinary response instances and HTTPError instances (which
562 can't be simply wrapped due to the requirement of preserving the exception
563 base class).
564 """
565 wrapper_class = get_seek_wrapper_class(response)
566 if hasattr(response, "closeable_response"):
567 if needs_seek_wrapper(response):
568 response = wrapper_class(response)
569 assert hasattr(response, "get_data")
570 return copy.copy(response)
571
572 # a urllib2 handler constructed the response, i.e. the response is an
573 # urllib.addinfourl or a urllib2.HTTPError, instead of a
574 # _Util.closeable_response as returned by e.g. mechanize.HTTPHandler
575 try:
576 code = response.code
577 except AttributeError:
578 code = None
579 try:
580 msg = response.msg
581 except AttributeError:
582 msg = None
583
584 # may have already-.read() data from .seek() cache
585 data = None
586 get_data = getattr(response, "get_data", None)
587 if get_data:
588 data = get_data()
589
590 response = closeable_response(response.fp,
591 response.info(), response.geturl(), code,
592 msg)
593 response = wrapper_class(response)
594 if data:
595 response.set_data(data)
596 return response