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, peek=None)
| 883 | return HTTPError(500, "Internal Server Error", _e(), stacktrace) |
| 884 | |
| 885 | def _cast(self, out, peek=None): |
| 886 | """ Try to convert the parameter into something WSGI compatible and set |
| 887 | correct HTTP headers when possible. |
| 888 | Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like, |
| 889 | iterable of strings and iterable of unicodes |
| 890 | """ |
| 891 | |
| 892 | # Empty output is done here |
| 893 | if not out: |
| 894 | if 'Content-Length' not in response: |
| 895 | response['Content-Length'] = 0 |
| 896 | return [] |
| 897 | # Join lists of byte or unicode strings. Mixed lists are NOT supported |
| 898 | if isinstance(out, (tuple, list))\ |
| 899 | and isinstance(out[0], (bytes, unicode)): |
| 900 | out = out[0][0:0].join(out) # b'abc'[0:0] -> b'' |
| 901 | # Encode unicode strings |
| 902 | if isinstance(out, unicode): |
| 903 | out = out.encode(response.charset) |
| 904 | # Byte Strings are just returned |
| 905 | if isinstance(out, bytes): |
| 906 | if 'Content-Length' not in response: |
| 907 | response['Content-Length'] = len(out) |
| 908 | return [out] |
| 909 | # HTTPError or HTTPException (recursive, because they may wrap anything) |
| 910 | # TODO: Handle these explicitly in handle() or make them iterable. |
| 911 | if isinstance(out, HTTPError): |
| 912 | out.apply(response) |
| 913 | out = self.error_handler.get(out.status_code, self.default_error_handler)(out) |
| 914 | return self._cast(out) |
| 915 | if isinstance(out, HTTPResponse): |
| 916 | out.apply(response) |
| 917 | return self._cast(out.body) |
| 918 | |
| 919 | # File-like objects. |
| 920 | if hasattr(out, 'read'): |
| 921 | if 'wsgi.file_wrapper' in request.environ: |
| 922 | return request.environ['wsgi.file_wrapper'](out) |
| 923 | elif hasattr(out, 'close') or not hasattr(out, '__iter__'): |
| 924 | return WSGIFileWrapper(out) |
| 925 | |
| 926 | # Handle Iterables. We peek into them to detect their inner type. |
| 927 | try: |
| 928 | iout = iter(out) |
| 929 | first = next(iout) |
| 930 | while not first: |
| 931 | first = next(iout) |
| 932 | except StopIteration: |
| 933 | return self._cast('') |
| 934 | except HTTPResponse: |
| 935 | first = _e() |
| 936 | except (KeyboardInterrupt, SystemExit, MemoryError): |
| 937 | raise |
| 938 | except Exception: |
| 939 | if not self.catchall: raise |
| 940 | first = HTTPError(500, 'Unhandled exception', _e(), format_exc()) |
| 941 | |
| 942 | # These are the inner types allowed in iterator or generator objects. |
no test coverage detected