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