def build_response(request, status_code=200, headers={}, content='(none)'): """ Build a :class:`requests.Response` object on the basis of the passed parameters. """ response = Response() response.status_code = status_code response.reason = responses[status_code] response.headers = CaseInsensitiveDict(headers) # Pretend that we've already read from the socket response._content = content response.encoding = get_encoding_from_headers(response.headers) response.url = request.url response.raw = MockRawResponse() # Give the Response some context. response.request = request response.connection = MockConnection() return response
def build_response(self, req, resp): response = Response() response.status_code = resp.status_code response.headers = CaseInsensitiveDict((k, v) for k, v in resp.items()) response.encoding = get_encoding_from_headers(response.headers) response.raw = StringIO(resp.content) response.reason = None if isinstance(req.url, bytes): response.url = req.url.decode('utf-8') else: response.url = req.url # Convert from django's SimpleCookie to request's CookieJar cookiejar_from_dict(resp.cookies, response.cookies) # context response.request = req response.connection = self response = dispatch_hook('response', req.hooks, response) return response
def send(self, request, stream=False, verify=None, cert=None, proxies=None, timeout=None): """issue request""" data = url_unquote(request.url[len('data:'):]) if ',' not in data: raise InvalidURL('data URL missing comma') mime, content = data.split(',', 1) content = content.strip() base64 = False charset = None while ';' in mime: mime, encoding_spec = mime.rsplit(';', 1) encoding_spec = encoding_spec.strip() if encoding_spec == 'base64': base64 = True elif not encoding_spec.startswith('charset='): raise InvalidURL( 'unrecognized encoding parameter: %r' % encoding_spec ) else: charset = encoding_spec[len('charset='):] try: if base64: content = a2b_base64(content) content_type = mime.strip() if charset: content_type += "; charset=" + charset response = Response() response.url = request.url response.headers['Date'] = formatdate(timeval=None, localtime=True) if request.method in ('GET', 'HEAD'): response.status_code = 200 response.headers['Content-Length'] = len(content) response.headers['Last-Modified'] = formatdate() response.headers['Content-Type'] = content_type if charset: response.encoding = charset response.raw = StringIO(str(content)) else: response.status_code = 405 response.headers['Status'] = '405 Method Not Allowed' except Exception: response.status_code = 500 response.headers['Status'] = '500 Internal Server Error' response.raw = StringIO(format_exc()) # context response.request = request response.connection = self # hooks response = dispatch_hook('response', request.hooks, response) # streaming if not stream: response.content return response
def send(self, request, stream=False, verify=None, cert=None, proxies=None, timeout=None): """issue request""" data = url_unquote(request.url[len('data:'):]) if ',' not in data: raise InvalidURL('data URL missing comma') mime, content = data.split(',', 1) content = content.strip() base64 = False charset = None while ';' in mime: mime, encoding_spec = mime.rsplit(';', 1) encoding_spec = encoding_spec.strip() if encoding_spec == 'base64': base64 = True elif not encoding_spec.startswith('charset='): raise InvalidURL('unrecognized encoding parameter: %r' % encoding_spec) else: charset = encoding_spec[len('charset='):] try: if base64: content = a2b_base64(content) content_type = mime.strip() if charset: content_type += "; charset=" + charset response = Response() response.url = request.url response.headers['Date'] = formatdate(timeval=None, localtime=True) if request.method in ('GET', 'HEAD'): response.status_code = 200 response.headers['Content-Length'] = len(content) response.headers['Last-Modified'] = formatdate() response.headers['Content-Type'] = content_type if charset: response.encoding = charset response.raw = StringIO(str(content)) else: response.status_code = 405 response.headers['Status'] = '405 Method Not Allowed' except Exception: response.status_code = 500 response.headers['Status'] = '500 Internal Server Error' response.raw = StringIO(format_exc()) # context response.request = request response.connection = self # hooks response = dispatch_hook('response', request.hooks, response) # streaming if not stream: response.content return response
def send( self, request, stream=False, verify=None, cert=None, proxies=None, timeout=None ): """issue request""" fname = url_unquote(request.url[len('file://'):]) if not fname: raise InvalidURL('missing file name') if '/' not in fname: raise InvalidURL( 'hostname without filename (perhaps missing a /?)' ) host, fname = fname.split('/', 1) fname = self.resolve_host(host, fname) response = Response() response.url = request.url response.headers['Date'] = formatdate(timeval=None, localtime=True) try: if request.method in ('GET', 'HEAD'): statdata = stat(fname) etag = '"%s/%s/%s' \ % (statdata.st_dev, statdata.st_ino, statdata.st_mtime) if S_ISLNK(statdata.st_mode): # handle relative symlinks! target_file = abspath(readlink(fname)) response.status_code = 302 response.headers['Status'] = '302 Found' response.headers['Location'] = \ url_quote('file://' + target_file) elif S_ISDIR(statdata.st_mode): response.status_code = 200 response.headers['Status'] = '200 Ok' body = \ """<html><head><title>%s</title></head><body><ul>""" \ % fname for subfname in sorted(listdir(fname)): body += '<li><a href="file://' + \ url_quote(subfname) + '">' + \ html_escape(fname) + '</a></li>' body += '</body></html>' response.headers['ETag'] = 'W/' + etag response.raw = StringIO(body) elif S_ISREG(statdata.st_mode): response.status_code = 200 response.headers['Content-Length'] = statdata.st_size response.headers['Last-Modified'] = formatdate( timeval=statdata.st_mtime, localtime=True ) mt, enc = guess_mime_type(request.url, strict=False) if mt is None: mt = 'application/octet-stream' if enc is not None: response.headers['Content-Encoding'] = enc response.headers['Content-Type'] = mt response.headers['ETag'] = etag if request.method == 'GET': response.raw = open(fname, 'r') else: response.status_code = 500 response.headers['Status'] = '500 Internal Server Error' elif request.method == 'PUT': open(fname, 'w').write(request.body) # FIXME: Is this right? response.status_code = 200 response.headers['Status'] = '200 Ok' elif request.method == 'POST': if exists(fname): # FIXME: Is this right? response.status_code = 409 response.headers['Status'] = '409 Conflict' else: open(fname, 'w').write(request.body) elif request.method == 'DELETE': unlink(fname) response.status_code = 200 response.headers['Status'] = '200 Ok' else: response.status_code = 405 response.headers['Status'] = '405 Method Not Allowed' except OSError as e: if e.errno == errno.ENOENT: if request.method == 'DELETE': response.status_code = 410 response.headers['Status'] = '410 Gone' else: response.status_code = 404 response.headers['Status'] = '404 Not Found' elif e.errno == errno.EISDIR: response.status_code = 405 response.headers['Status'] = '405 Method Not Allowed' response.raw = StringIO('Cannot %r a directory...' % request.method) elif e.errno == errno.EACCES: response.status_code = 403 response.headers['Status'] = '403 Forbidden' else: response.status_code = 500 response.headers['Status'] = '500 Internal Server Error' response.raw = StringIO('OSError: ' + strerror(e.errno)) except Exception: response.status_code = 500 response.headers['Status'] = '500 Internal Server Error' response.raw = StringIO(format_exc()) # context response.request = request response.connection = self # hooks response = dispatch_hook('response', request.hooks, response) # streaming if not stream: response.content return response