Storage class for a response body as well as headers and cookies. This class does support dict-like case-insensitive item-access to headers, but is NOT a dict. Most notably, iterating over a response yields parts of the body and not the headers. :param body: The re
| 1437 | |
| 1438 | |
| 1439 | class BaseResponse(object): |
| 1440 | """ Storage class for a response body as well as headers and cookies. |
| 1441 | |
| 1442 | This class does support dict-like case-insensitive item-access to |
| 1443 | headers, but is NOT a dict. Most notably, iterating over a response |
| 1444 | yields parts of the body and not the headers. |
| 1445 | |
| 1446 | :param body: The response body as one of the supported types. |
| 1447 | :param status: Either an HTTP status code (e.g. 200) or a status line |
| 1448 | including the reason phrase (e.g. '200 OK'). |
| 1449 | :param headers: A dictionary or a list of name-value pairs. |
| 1450 | |
| 1451 | Additional keyword arguments are added to the list of headers. |
| 1452 | Underscores in the header name are replaced with dashes. |
| 1453 | """ |
| 1454 | |
| 1455 | default_status = 200 |
| 1456 | default_content_type = 'text/html; charset=UTF-8' |
| 1457 | |
| 1458 | # Header blacklist for specific response codes |
| 1459 | # (rfc2616 section 10.2.3 and 10.3.5) |
| 1460 | bad_headers = { |
| 1461 | 204: set(('Content-Type',)), |
| 1462 | 304: set(('Allow', 'Content-Encoding', 'Content-Language', |
| 1463 | 'Content-Length', 'Content-Range', 'Content-Type', |
| 1464 | 'Content-Md5', 'Last-Modified'))} |
| 1465 | |
| 1466 | def __init__(self, body='', status=None, headers=None, **more_headers): |
| 1467 | self._cookies = None |
| 1468 | self._headers = {} |
| 1469 | self.body = body |
| 1470 | self.status = status or self.default_status |
| 1471 | if headers: |
| 1472 | if isinstance(headers, dict): |
| 1473 | headers = headers.items() |
| 1474 | for name, value in headers: |
| 1475 | self.add_header(name, value) |
| 1476 | if more_headers: |
| 1477 | for name, value in more_headers.items(): |
| 1478 | self.add_header(name, value) |
| 1479 | |
| 1480 | def copy(self, cls=None): |
| 1481 | ''' Returns a copy of self. ''' |
| 1482 | cls = cls or BaseResponse |
| 1483 | assert issubclass(cls, BaseResponse) |
| 1484 | copy = cls() |
| 1485 | copy.status = self.status |
| 1486 | copy._headers = dict((k, v[:]) for (k, v) in self._headers.items()) |
| 1487 | if self._cookies: |
| 1488 | copy._cookies = SimpleCookie() |
| 1489 | copy._cookies.load(self._cookies.output(header='')) |
| 1490 | return copy |
| 1491 | |
| 1492 | def __iter__(self): |
| 1493 | return iter(self.body) |
| 1494 | |
| 1495 | def close(self): |
| 1496 | if hasattr(self.body, 'close'): |
nothing calls this directly
no test coverage detected