def __init__(self): """ Create a new Response defaulting to HTML content and "200 OK" status """ self.status = "200 OK" self.headers = HeaderDict({"content-type": "text/html"}) self.cookies = SimpleCookie()
def __init__(self): """ Create a new Response defaulting to HTML content and "200 OK" status """ self.status = "200 OK" self.headers = HeaderDict({"content-type": "text/html"}) # Allow cross-site scripting self.headers["Access-Control-Allow-Origin"] = "*" self.headers[ "Access-Control-Allow-Headers"] = "Content-Type, X-Requested-With, X-Requested-By" self.headers["Access-Control-Allow-Methods"] = "POST, GET" self.cookies = SimpleCookie()
class Response: """ Describes an HTTP response. Currently very simple since the actual body of the request is handled separately. """ def __init__(self): """ Create a new Response defaulting to HTML content and "200 OK" status """ self.status = "200 OK" self.headers = HeaderDict({"content-type": "text/html; charset=UTF-8"}) self.cookies = SimpleCookie() def set_content_type(self, type_): """ Sets the Content-Type header """ self.headers["content-type"] = type_ def get_content_type(self): return self.headers.get("content-type", None) def send_redirect(self, url): """ Send an HTTP redirect response to (target `url`) """ if "\n" in url or "\r" in url: raise webob.exc.HTTPInternalServerError( "Invalid redirect URL encountered.") raise webob.exc.HTTPFound(location=url, headers=self.wsgi_headeritems()) def wsgi_headeritems(self): """ Return headers in format appropriate for WSGI `start_response` """ result = self.headers.headeritems() # Add cookie to header for crumb in self.cookies.values(): header, value = str(crumb).split(': ', 1) result.append((header, value)) return result def wsgi_status(self): """ Return status line in format appropriate for WSGI `start_response` """ if isinstance(self.status, int): exception = webob.exc.status_map.get(self.status) return "%d %s" % (exception.code, exception.title) else: return self.status
class Response(object): """ Describes an HTTP response. Currently very simple since the actual body of the request is handled separately. """ def __init__(self): """ Create a new Response defaulting to HTML content and "200 OK" status """ self.status = "200 OK" self.headers = HeaderDict({"content-type": "text/html"}) self.cookies = SimpleCookie() def set_content_type(self, type_): """ Sets the Content-Type header """ self.headers["content-type"] = type_ def get_content_type(self): return self.headers.get("content-type", None) def send_redirect(self, url): """ Send an HTTP redirect response to (target `url`) """ if "\n" in url or "\r" in url: raise webob.exc.HTTPInternalServerError("Invalid redirect URL encountered.") raise webob.exc.HTTPFound(location=url) def wsgi_headeritems(self): """ Return headers in format appropriate for WSGI `start_response` """ result = self.headers.headeritems() # Add cookie to header for name, crumb in self.cookies.items(): header, value = str(crumb).split(': ', 1) result.append((header, value)) return result def wsgi_status(self): """ Return status line in format appropriate for WSGI `start_response` """ if isinstance(self.status, int): exception = webob.exc.status_map.get(self.status) return "%d %s" % (exception.code, exception.title) else: return self.status
class Response(object): """ Describes an HTTP response. Currently very simple since the actual body of the request is handled separately. """ def __init__(self): """ Create a new Response defaulting to HTML content and "200 OK" status """ self.status = "200 OK" self.headers = HeaderDict({"content-type": "text/html"}) self.cookies = SimpleCookie() def set_content_type(self, type_): """ Sets the Content-Type header """ self.headers["content-type"] = type_ def get_content_type(self): return self.headers.get("content-type", None) def send_redirect(self, url): """ Send an HTTP redirect response to (target `url`) """ raise httpexceptions.HTTPFound(url.encode('utf-8'), headers=self.wsgi_headeritems()) def wsgi_headeritems(self): """ Return headers in format appropriate for WSGI `start_response` """ result = self.headers.headeritems() # Add cookie to header for name, crumb in self.cookies.items(): header, value = str(crumb).split(': ', 1) result.append((header, value)) return result def wsgi_status(self): """ Return status line in format appropriate for WSGI `start_response` """ if isinstance(self.status, int): exception = httpexceptions.get_exception(self.status) return "%d %s" % (exception.code, exception.title) else: return self.status
def __init__( self ): """ Create a new Response defaulting to HTML content and "200 OK" status """ self.status = "200 OK" self.headers = HeaderDict( { "content-type": "text/html" } ) self.cookies = SimpleCookie()
def __init__(self, content=b'', mimetype=None, code=200): self._iter = None self._is_str_iter = True self.content = content self.headers = HeaderDict() self.cookies = SimpleCookie() self.status_code = code defaults = self.defaults._current_obj() if not mimetype: mimetype = defaults.get('content_type', 'text/html') charset = defaults.get('charset') if charset: mimetype = '%s; charset=%s' % (mimetype, charset) self.headers.update(defaults.get('headers', {})) self.headers['Content-Type'] = mimetype self.errors = defaults.get('errors', 'strict')
class Response(object): """ Describes an HTTP response. Currently very simple since the actual body of the request is handled separately. """ def __init__(self): """ Create a new Response defaulting to HTML content and "200 OK" status """ self.status = "200 OK" self.headers = HeaderDict({"content-type": "text/html"}) # Allow cross-site scripting self.headers["Access-Control-Allow-Origin"] = "*" self.headers[ "Access-Control-Allow-Headers"] = "Content-Type, X-Requested-With, X-Requested-By" self.headers["Access-Control-Allow-Methods"] = "POST, GET" self.cookies = SimpleCookie() def set_content_type(self, type): """ Sets the Content-Type header """ self.headers["content-type"] = type def send_redirect(self, url): """ Send an HTTP redirect response to (target `url`) """ raise httpexceptions.HTTPFound(url, headers=self.wsgi_headeritems()) def wsgi_headeritems(self): """ Return headers in format appropriate for WSGI `start_response` """ result = self.headers.headeritems() # Add cookie to header for name in self.cookies.keys(): crumb = self.cookies[name] header, value = str(crumb).split(': ', 1) result.append((header, value)) return result def wsgi_status(self): """ Return status line in format appropriate for WSGI `start_response` """ if isinstance(self.status, int): exception = httpexceptions.get_exception(self.status) return "%d %s" % (exception.code, exception.title) else: return self.status
class Response(object): """ Describes an HTTP response. Currently very simple since the actual body of the request is handled separately. """ def __init__(self): """ Create a new Response defaulting to HTML content and "200 OK" status """ self.status = "200 OK" self.headers = HeaderDict({"content-type": "text/html"}) self.cookies = SimpleCookie() def set_content_type(self, type): """ Sets the Content-Type header """ self.headers["content-type"] = type def get_content_type(self): return self.headers["content-type"] def send_redirect(self, url): """ Send an HTTP redirect response to (target `url`) """ raise httpexceptions.HTTPFound(url.encode("utf-8"), headers=self.wsgi_headeritems()) def wsgi_headeritems(self): """ Return headers in format appropriate for WSGI `start_response` """ result = self.headers.headeritems() # Add cookie to header for name in self.cookies.keys(): crumb = self.cookies[name] header, value = str(crumb).split(": ", 1) result.append((header, value)) return result def wsgi_status(self): """ Return status line in format appropriate for WSGI `start_response` """ if isinstance(self.status, int): exception = httpexceptions.get_exception(self.status) return "%d %s" % (exception.code, exception.title) else: return self.status
def repl_start_response(status, headers, exc_info=None): response = pylons.response._current_obj() start_response_called.append(None) # Copy the headers from the global response # XXX: TODO: This should really be done with a more efficient # header merging function at some point. if log_debug: log.debug("Merging pylons.response headers into " "start_response call, status: %s", status) response.headers.update(HeaderDict.fromlist(headers)) headers = response.headers.headeritems() for c in pylons.response.cookies.values(): headers.append(('Set-Cookie', c.output(header=''))) return start_response(status, headers, exc_info)
def repl_start_response(status, headers, exc_info=None): response = pylons.response._current_obj() start_response_called.append(None) # Copy the headers from the global response # XXX: TODO: This should really be done with a more efficient # header merging function at some point. if log_debug: log.debug( "Merging pylons.response headers into " "start_response call, status: %s", status) response.headers.update(HeaderDict.fromlist(headers)) headers = response.headers.headeritems() for c in pylons.response.cookies.values(): headers.append(('Set-Cookie', c.output(header=''))) return start_response(status, headers, exc_info)
def __init__(self, content='', mimetype=None, code=200): self._iter = None self._is_str_iter = True self.content = content self.headers = HeaderDict() self.cookies = SimpleCookie() self.status_code = code defaults = self.defaults._current_obj() if not mimetype: mimetype = defaults.get('content_type', 'text/html') charset = defaults.get('charset') if charset: mimetype = '%s; charset=%s' % (mimetype, charset) self.headers['Content-Type'] = mimetype self.errors = defaults.get('errors', 'strict')
def __init__(self, *args, **kw): warnings.warn( "The class wsgilib.ResponseHeaderDict has been moved " "to paste.response.HeaderDict", DeprecationWarning, 2) HeaderDict.__init__(self, *args, **kw)
def __init__(self): self.headers = HeaderDict({"content-type": "text/html"})
class WSGIResponse(object): """A basic HTTP response with content, headers, and out-bound cookies The class variable ``defaults`` specifies default values for ``content_type``, ``charset`` and ``errors``. These can be overridden for the current request via the registry. """ defaults = StackedObjectProxy( default=dict(content_type='text/html', charset='utf-8', errors='strict', headers={'Cache-Control': 'no-cache'})) def __init__(self, content=b'', mimetype=None, code=200): self._iter = None self._is_str_iter = True self.content = content self.headers = HeaderDict() self.cookies = SimpleCookie() self.status_code = code defaults = self.defaults._current_obj() if not mimetype: mimetype = defaults.get('content_type', 'text/html') charset = defaults.get('charset') if charset: mimetype = '%s; charset=%s' % (mimetype, charset) self.headers.update(defaults.get('headers', {})) self.headers['Content-Type'] = mimetype self.errors = defaults.get('errors', 'strict') def __str__(self): """Returns a rendition of the full HTTP message, including headers. When the content is an iterator, the actual content is replaced with the output of str(iterator) (to avoid exhausting the iterator). """ if self._is_str_iter: content = ''.join(self.get_content()) else: content = str(self.content) return '\n'.join(['%s: %s' % (key, value) for key, value in self.headers.headeritems()]) \ + '\n\n' + content def __call__(self, environ, start_response): """Convenience call to return output and set status information Conforms to the WSGI interface for calling purposes only. Example usage: .. code-block:: python def wsgi_app(environ, start_response): response = WSGIResponse() response.write("Hello world") response.headers['Content-Type'] = 'latin1' return response(environ, start_response) """ status_text = STATUS_CODE_TEXT[self.status_code] status = '%s %s' % (self.status_code, status_text) response_headers = self.headers.headeritems() for c in self.cookies.values(): response_headers.append(('Set-Cookie', c.output(header=''))) start_response(status, response_headers) is_file = isinstance(self.content, file) if 'wsgi.file_wrapper' in environ and is_file: return environ['wsgi.file_wrapper'](self.content) elif is_file: return iter(lambda: self.content.read(), '') return self.get_content() def determine_charset(self): """ Determine the encoding as specified by the Content-Type's charset parameter, if one is set """ charset_match = _CHARSET_RE.search(self.headers.get( 'Content-Type', '')) if charset_match: return charset_match.group(1) def has_header(self, header): """ Case-insensitive check for a header """ warnings.warn( 'WSGIResponse.has_header is deprecated, use ' 'WSGIResponse.headers.has_key instead', DeprecationWarning, 2) return self.headers.has_key(header) def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=None): """ Define a cookie to be sent via the outgoing HTTP headers """ self.cookies[key] = value for var_name, var_value in [('max_age', max_age), ('path', path), ('domain', domain), ('secure', secure), ('expires', expires), ('httponly', httponly)]: if var_value is not None and var_value is not False: self.cookies[key][var_name.replace('_', '-')] = var_value def delete_cookie(self, key, path='/', domain=None): """ Notify the browser the specified cookie has expired and should be deleted (via the outgoing HTTP headers) """ self.cookies[key] = '' if path is not None: self.cookies[key]['path'] = path if domain is not None: self.cookies[key]['domain'] = domain self.cookies[key]['expires'] = 0 self.cookies[key]['max-age'] = 0 def _set_content(self, content): if not isinstance(content, (six.binary_type, six.text_type)): self._iter = content if isinstance(content, list): self._is_str_iter = True else: self._is_str_iter = False else: self._iter = [content] self._is_str_iter = True content = property(lambda self: self._iter, _set_content, doc='Get/set the specified content, where content can ' 'be: a string, a list of strings, a generator function ' 'that yields strings, or an iterable object that ' 'produces strings.') def get_content(self): """ Returns the content as an iterable of strings, encoding each element of the iterator from a Unicode object if necessary. """ charset = self.determine_charset() if charset: return encode_unicode_app_iter(self.content, charset, self.errors) else: return self.content def wsgi_response(self): """ Return this WSGIResponse as a tuple of WSGI formatted data, including: (status, headers, iterable) """ status_text = STATUS_CODE_TEXT[self.status_code] status = '%s %s' % (self.status_code, status_text) response_headers = self.headers.headeritems() for c in self.cookies.values(): response_headers.append(('Set-Cookie', c.output(header=''))) return status, response_headers, self.get_content() # The remaining methods partially implement the file-like object interface. # See http://docs.python.org/lib/bltin-file-objects.html def write(self, content): if not self._is_str_iter: raise IOError( "This %s instance's content is not writable: (content " 'is an iterator)' % self.__class__.__name__) self.content.append(content) def flush(self): pass def tell(self): if not self._is_str_iter: raise IOError( 'This %s instance cannot tell its position: (content ' 'is an iterator)' % self.__class__.__name__) return sum([len(chunk) for chunk in self._iter]) ######################################## ## Content-type and charset def charset__get(self): """ Get/set the charset (in the Content-Type) """ header = self.headers.get('content-type') if not header: return None match = _CHARSET_RE.search(header) if match: return match.group(1) return None def charset__set(self, charset): if charset is None: del self.charset return try: header = self.headers.pop('content-type') except KeyError: raise AttributeError( "You cannot set the charset when no content-type is defined") match = _CHARSET_RE.search(header) if match: header = header[:match.start()] + header[match.end():] header += '; charset=%s' % charset self.headers['content-type'] = header def charset__del(self): try: header = self.headers.pop('content-type') except KeyError: # Don't need to remove anything return match = _CHARSET_RE.search(header) if match: header = header[:match.start()] + header[match.end():] self.headers['content-type'] = header charset = property(charset__get, charset__set, charset__del, doc=charset__get.__doc__) def content_type__get(self): """ Get/set the Content-Type header (or None), *without* the charset or any parameters. If you include parameters (or ``;`` at all) when setting the content_type, any existing parameters will be deleted; otherwise they will be preserved. """ header = self.headers.get('content-type') if not header: return None return header.split(';', 1)[0] def content_type__set(self, value): if ';' not in value: header = self.headers.get('content-type', '') if ';' in header: params = header.split(';', 1)[1] value += ';' + params self.headers['content-type'] = value def content_type__del(self): try: del self.headers['content-type'] except KeyError: pass content_type = property(content_type__get, content_type__set, content_type__del, doc=content_type__get.__doc__)
def __init__(self): self.headers = HeaderDict({'content-type': 'text/html'})
class WSGIResponse(object): """A basic HTTP response with content, headers, and out-bound cookies The class variable ``defaults`` specifies default values for ``content_type``, ``charset`` and ``errors``. These can be overridden for the current request via the registry. """ defaults = StackedObjectProxy( default=dict(content_type='text/html', charset='utf-8', errors='strict', headers={'Cache-Control':'no-cache'}) ) def __init__(self, content='', mimetype=None, code=200): self._iter = None self._is_str_iter = True self.content = content self.headers = HeaderDict() self.cookies = SimpleCookie() self.status_code = code defaults = self.defaults._current_obj() if not mimetype: mimetype = defaults.get('content_type', 'text/html') charset = defaults.get('charset') if charset: mimetype = '%s; charset=%s' % (mimetype, charset) self.headers.update(defaults.get('headers', {})) self.headers['Content-Type'] = mimetype self.errors = defaults.get('errors', 'strict') def __str__(self): """Returns a rendition of the full HTTP message, including headers. When the content is an iterator, the actual content is replaced with the output of str(iterator) (to avoid exhausting the iterator). """ if self._is_str_iter: content = ''.join(self.get_content()) else: content = str(self.content) return '\n'.join(['%s: %s' % (key, value) for key, value in self.headers.headeritems()]) \ + '\n\n' + content def __call__(self, environ, start_response): """Convenience call to return output and set status information Conforms to the WSGI interface for calling purposes only. Example usage: .. code-block:: Python def wsgi_app(environ, start_response): response = WSGIResponse() response.write("Hello world") response.headers['Content-Type'] = 'latin1' return response(environ, start_response) """ status_text = STATUS_CODE_TEXT[self.status_code] status = '%s %s' % (self.status_code, status_text) response_headers = self.headers.headeritems() for c in self.cookies.values(): response_headers.append(('Set-Cookie', c.output(header=''))) start_response(status, response_headers) is_file = isinstance(self.content, file) if 'wsgi.file_wrapper' in environ and is_file: return environ['wsgi.file_wrapper'](self.content) elif is_file: return iter(lambda: self.content.read(), '') return self.get_content() def determine_charset(self): """ Determine the encoding as specified by the Content-Type's charset parameter, if one is set """ charset_match = _CHARSET_RE.search(self.headers.get('Content-Type', '')) if charset_match: return charset_match.group(1) def has_header(self, header): """ Case-insensitive check for a header """ warnings.warn('WSGIResponse.has_header is deprecated, use ' 'WSGIResponse.headers.has_key instead', DeprecationWarning, 2) return self.headers.has_key(header) def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain=None, secure=None): """ Define a cookie to be sent via the outgoing HTTP headers """ self.cookies[key] = value for var_name, var_value in [ ('max_age', max_age), ('path', path), ('domain', domain), ('secure', secure), ('expires', expires)]: if var_value is not None and var_value is not False: self.cookies[key][var_name.replace('_', '-')] = var_value def delete_cookie(self, key, path='/', domain=None): """ Notify the browser the specified cookie has expired and should be deleted (via the outgoing HTTP headers) """ self.cookies[key] = '' if path is not None: self.cookies[key]['path'] = path if domain is not None: self.cookies[key]['domain'] = path self.cookies[key]['expires'] = 0 self.cookies[key]['max-age'] = 0 def _set_content(self, content): if hasattr(content, '__iter__'): self._iter = content if isinstance(content, list): self._is_str_iter = True else: self._is_str_iter = False else: self._iter = [content] self._is_str_iter = True content = property(lambda self: self._iter, _set_content, doc='Get/set the specified content, where content can ' 'be: a string, a list of strings, a generator function ' 'that yields strings, or an iterable object that ' 'produces strings.') def get_content(self): """ Returns the content as an iterable of strings, encoding each element of the iterator from a Unicode object if necessary. """ charset = self.determine_charset() if charset: return encode_unicode_app_iter(self.content, charset, self.errors) else: return self.content def wsgi_response(self): """ Return this WSGIResponse as a tuple of WSGI formatted data, including: (status, headers, iterable) """ status_text = STATUS_CODE_TEXT[self.status_code] status = '%s %s' % (self.status_code, status_text) response_headers = self.headers.headeritems() for c in self.cookies.values(): response_headers.append(('Set-Cookie', c.output(header=''))) return status, response_headers, self.get_content() # The remaining methods partially implement the file-like object interface. # See http://docs.python.org/lib/bltin-file-objects.html def write(self, content): if not self._is_str_iter: raise IOError, "This %s instance's content is not writable: (content " \ 'is an iterator)' % self.__class__.__name__ self.content.append(content) def flush(self): pass def tell(self): if not self._is_str_iter: raise IOError, 'This %s instance cannot tell its position: (content ' \ 'is an iterator)' % self.__class__.__name__ return sum([len(chunk) for chunk in self._iter]) ######################################## ## Content-type and charset def charset__get(self): """ Get/set the charset (in the Content-Type) """ header = self.headers.get('content-type') if not header: return None match = _CHARSET_RE.search(header) if match: return match.group(1) return None def charset__set(self, charset): if charset is None: del self.charset return try: header = self.headers.pop('content-type') except KeyError: raise AttributeError( "You cannot set the charset when no content-type is defined") match = _CHARSET_RE.search(header) if match: header = header[:match.start()] + header[match.end():] header += '; charset=%s' % charset self.headers['content-type'] = header def charset__del(self): try: header = self.headers.pop('content-type') except KeyError: # Don't need to remove anything return match = _CHARSET_RE.search(header) if match: header = header[:match.start()] + header[match.end():] self.headers['content-type'] = header charset = property(charset__get, charset__set, charset__del, doc=charset__get.__doc__) def content_type__get(self): """ Get/set the Content-Type header (or None), *without* the charset or any parameters. If you include parameters (or ``;`` at all) when setting the content_type, any existing parameters will be deleted; otherwise they will be preserved. """ header = self.headers.get('content-type') if not header: return None return header.split(';', 1)[0] def content_type__set(self, value): if ';' not in value: header = self.headers.get('content-type', '') if ';' in header: params = header.split(';', 1)[1] value += ';' + params self.headers['content-type'] = value def content_type__del(self): try: del self.headers['content-type'] except KeyError: pass content_type = property(content_type__get, content_type__set, content_type__del, doc=content_type__get.__doc__)