Try to convert the parameter into something WSGI compatible and set correct HTTP headers when possible. Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like, iterable of strings and iterable of unicodes
(self, out, request, response, peek=None)
| 745 | return HTTPError(500, "Internal Server Error", e, stacktrace) |
| 746 | |
| 747 | def _cast(self, out, request, response, peek=None): |
| 748 | """ Try to convert the parameter into something WSGI compatible and set |
| 749 | correct HTTP headers when possible. |
| 750 | Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like, |
| 751 | iterable of strings and iterable of unicodes |
| 752 | """ |
| 753 | |
| 754 | # Empty output is done here |
| 755 | if not out: |
| 756 | response['Content-Length'] = 0 |
| 757 | return [] |
| 758 | # Join lists of byte or unicode strings. Mixed lists are NOT supported |
| 759 | if isinstance(out, (tuple, list))\ |
| 760 | and isinstance(out[0], (bytes, unicode)): |
| 761 | out = out[0][0:0].join(out) # b'abc'[0:0] -> b'' |
| 762 | # Encode unicode strings |
| 763 | if isinstance(out, unicode): |
| 764 | out = out.encode(response.charset) |
| 765 | # Byte Strings are just returned |
| 766 | if isinstance(out, bytes): |
| 767 | response['Content-Length'] = len(out) |
| 768 | return [out] |
| 769 | # HTTPError or HTTPException (recursive, because they may wrap anything) |
| 770 | # TODO: Handle these explicitly in handle() or make them iterable. |
| 771 | if isinstance(out, HTTPError): |
| 772 | out.apply(response) |
| 773 | out = self.error_handler.get(out.status, repr)(out) |
| 774 | if isinstance(out, HTTPResponse): |
| 775 | depr('Error handlers must not return :exc:`HTTPResponse`.') #0.9 |
| 776 | return self._cast(out, request, response) |
| 777 | if isinstance(out, HTTPResponse): |
| 778 | out.apply(response) |
| 779 | return self._cast(out.output, request, response) |
| 780 | |
| 781 | # File-like objects. |
| 782 | if hasattr(out, 'read'): |
| 783 | if 'wsgi.file_wrapper' in request.environ: |
| 784 | return request.environ['wsgi.file_wrapper'](out) |
| 785 | elif hasattr(out, 'close') or not hasattr(out, '__iter__'): |
| 786 | return WSGIFileWrapper(out) |
| 787 | |
| 788 | # Handle Iterables. We peek into them to detect their inner type. |
| 789 | try: |
| 790 | out = iter(out) |
| 791 | first = out.next() |
| 792 | while not first: |
| 793 | first = out.next() |
| 794 | except StopIteration: |
| 795 | return self._cast('', request, response) |
| 796 | except HTTPResponse, e: |
| 797 | first = e |
| 798 | except Exception, e: |
| 799 | first = HTTPError(500, 'Unhandled exception', e, format_exc(10)) |
| 800 | if isinstance(e, (KeyboardInterrupt, SystemExit, MemoryError))\ |
| 801 | or not self.catchall: |
| 802 | raise |
| 803 | # These are the inner types allowed in iterator or generator objects. |
| 804 | if isinstance(first, HTTPResponse): |
no test coverage detected