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)
| 1013 | return out |
| 1014 | |
| 1015 | def _cast(self, out, peek=None): |
| 1016 | """ Try to convert the parameter into something WSGI compatible and set |
| 1017 | correct HTTP headers when possible. |
| 1018 | Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like, |
| 1019 | iterable of strings and iterable of unicodes |
| 1020 | """ |
| 1021 | |
| 1022 | # Empty output is done here |
| 1023 | if not out: |
| 1024 | if 'Content-Length' not in response: |
| 1025 | response['Content-Length'] = 0 |
| 1026 | return [] |
| 1027 | # Join lists of byte or unicode strings. Mixed lists are NOT supported |
| 1028 | if isinstance(out, (tuple, list))\ |
| 1029 | and isinstance(out[0], (bytes, unicode)): |
| 1030 | out = out[0][0:0].join(out) # b'abc'[0:0] -> b'' |
| 1031 | # Encode unicode strings |
| 1032 | if isinstance(out, unicode): |
| 1033 | out = out.encode(response.charset) |
| 1034 | # Byte Strings are just returned |
| 1035 | if isinstance(out, bytes): |
| 1036 | if 'Content-Length' not in response: |
| 1037 | response['Content-Length'] = len(out) |
| 1038 | return [out] |
| 1039 | # HTTPError or HTTPException (recursive, because they may wrap anything) |
| 1040 | # TODO: Handle these explicitly in handle() or make them iterable. |
| 1041 | if isinstance(out, HTTPError): |
| 1042 | out.apply(response) |
| 1043 | out = self.error_handler.get(out.status_code, |
| 1044 | self.default_error_handler)(out) |
| 1045 | return self._cast(out) |
| 1046 | if isinstance(out, HTTPResponse): |
| 1047 | out.apply(response) |
| 1048 | return self._cast(out.body) |
| 1049 | |
| 1050 | # File-like objects. |
| 1051 | if hasattr(out, 'read'): |
| 1052 | if 'wsgi.file_wrapper' in request.environ: |
| 1053 | return request.environ['wsgi.file_wrapper'](out) |
| 1054 | elif hasattr(out, 'close') or not hasattr(out, '__iter__'): |
| 1055 | return WSGIFileWrapper(out) |
| 1056 | |
| 1057 | # Handle Iterables. We peek into them to detect their inner type. |
| 1058 | try: |
| 1059 | iout = iter(out) |
| 1060 | first = next(iout) |
| 1061 | while not first: |
| 1062 | first = next(iout) |
| 1063 | except StopIteration: |
| 1064 | return self._cast('') |
| 1065 | except HTTPResponse as E: |
| 1066 | first = E |
| 1067 | except (KeyboardInterrupt, SystemExit, MemoryError): |
| 1068 | raise |
| 1069 | except Exception as error: |
| 1070 | if not self.catchall: raise |
| 1071 | first = HTTPError(500, 'Unhandled exception', error, format_exc()) |
| 1072 |
no test coverage detected