def test_content_length(): r0 = Response('x'*10, content_length=10) req_head = Request.blank('/', method='HEAD') r1 = req_head.get_response(r0) eq_(r1.status_int, 200) eq_(r1.body, '') eq_(r1.content_length, 10) req_get = Request.blank('/') r2 = req_get.get_response(r0) eq_(r2.status_int, 200) eq_(r2.body, 'x'*10) eq_(r2.content_length, 10) r3 = Response(app_iter=['x']*10) eq_(r3.content_length, None) eq_(r3.body, 'x'*10) eq_(r3.content_length, 10) r4 = Response(app_iter=['x']*10, content_length=20) # wrong content_length eq_(r4.content_length, 20) assert_raises(AssertionError, lambda: r4.body) req_range = Request.blank('/', range=(0,5)) r0.conditional_response = True r5 = req_range.get_response(r0) eq_(r5.status_int, 206) eq_(r5.body, 'xxxxx') eq_(r5.content_length, 5)
def __json_response(self, serial_obj): '''Serialize an object into JSON then return as webob Response :param serial_obj: object acceptable by json.dumps() ''' resp = Response(json.dumps(serial_obj)) self.logger.debug( json.dumps(serial_obj)) resp.conditional_response = True return resp
def action_view_GET(self, req, page): if not page.exists: return exc.HTTPTemporaryRedirect(location=req.url + "?action=edit") if req.cookies.get("message"): message = req.cookies["message"] else: message = None text = self.view_template.substitute(page=page, req=req, message=message) resp = Response(text) if message: resp.delete_cookie("message") else: resp.last_modified = page.mtime resp.conditional_response = True return resp
def hello_app_cookie(req): r = Response(charset='UTF-8') if 'name' in req.params: name = req.params['name'] r.set_cookie('name', name) elif 'name' in req.cookies: name = req.cookies['name'] #r.delete_cookie('name') else: return form_app r.unicode_body = u'Hello, %s!' % name r.conditional_response = True r.md5_etag() return r
def action_view_GET(self, req, page): if not page.exists: return exc.HTTPTemporaryRedirect(location=req.url + '?action=edit') if req.cookies.get('message'): message = req.cookies['message'] else: message = None text = self.view_template.substitute(page=page, req=req, message=message) resp = Response(text) if message: resp.delete_cookie('message') else: resp.last_modified = page.mtime resp.conditional_response = True return resp
def __forward(self, method, path, body, headers): '''Send an HTTP request and return its webob Response. :param method: the http request method "GET", "POST" :param path: the path of the request :param body: body data string :param headers: dictionary like object of request headers ''' if 'x-auth-token' in headers: token = headers['x-auth-token'] else: method = headers["x-auth-key"] identifier = headers["x-auth-user"] _, token = self.__authenticate(method, identifier) user_info = self.mc.get(token) if "master_tenantId" not in user_info: user_info["master_tenantId"] = None # iterate through the user_info hitting each host with the # requests and updating the info based on that for key in user_info: if key in AuthProxy.RESERVED_WORDS or not self.__is_openstack_auth( key): continue conn = httplib.HTTPConnection(user_info[key]["host"], user_info[key]["port"], False) if 'x-auth-token' in headers: headers["x-auth-token"] = user_info[key]["access"]["token"]["id"] new_path = path.replace(token, headers["x-auth-token"]) new_body = body.replace(token, headers["x-auth-token"]) if user_info["master_tenantId"] is not None and "tenantId" in user_info[key]: new_body = new_body.replace(user_info["master_tenantId"], user_info[key]["tenantId"]) conn.request(method, new_path, new_body, headers) temp_res = conn.getresponse().read() conn.close() temp_res_object = json.loads(temp_res) # what we need to fetch are the token and the tenantId if "tenants" in temp_res_object: for tenant in temp_res_object["tenants"]: if tenant["enabled"]: user_info[key]["tenantId"] = tenant["id"] if "access" in temp_res_object and "token" in temp_res_object["access"]: token_object = temp_res_object["access"]["token"] if "tenant" in token_object and "id" in token_object["tenant"]: user_info[key]["tokenId"] = token_object["id"] user_info[key]["tenantId"] = token_object["tenant"]["id"] if user_info[key]["host"] == user_info["host"]: if "tenantId" in user_info[key]: user_info["master_tenantId"] = user_info[key]["tenantId"] res_object = temp_res_object res = temp_res if "access" in res_object and "token" in res_object["access"]: new_token = str(res_object["access"]["token"]["id"]) self.mc.set(new_token, user_info, local_settings.AUTH_TOKEN_EXPIRATION) self.mc.set(token, user_info, local_settings.AUTH_TOKEN_EXPIRATION) for old in local_settings.PROXY_REPLACE.keys(): self.logger.debug("REPLACEING %s with %s", old, local_settings.PROXY_REPLACE[old]) res = res.replace(old, local_settings.PROXY_REPLACE[old]) for port in local_settings.PROXY_ENDPOINT_PORTS: # maybe just do a regex and replace any host not just # the keystone host res = res.replace("%s:%d" % (user_info["host"], port), "%s:%d" % (local_settings.API_HOST, port)) self.logger.debug( "Forwarded request") self.logger.debug(res) resp = Response(res) resp.conditional_response = True return resp
def handle_openstack_api(self, req, auth_token, values): ''' Handle against the OpenStack API be translating and aggregating the results of lots of messed up nonsense ''' try: global_values = self.__path_to_params(req.path) global_values[GLOBAL].update(values) global_values[GLOBAL]['auth-token'] = auth_token global_values[GLOBAL]['method'] = req.method if 'x-auth-project-id' in req.headers: global_values[GLOBAL]['auth-project-id'] = req.headers[ 'x-auth-project-id'] global_values[GLOBAL].update(req.params) command = self.__path_to_command(req.path) self.logger.debug("The command is %s", command) name = self.get_name(command, req.method) if req.method == "POST": body_values = json.loads(req.body) if name in body_values: body_values = json.loads(req.body)[name] cloud, body_values['name'] = self.split_cloud_name( body_values['name']) req.body = json.dumps({name: body_values}) global_values[GLOBAL].update(body_values) elif req.method == "DELETE" and name in ['keypairs']: cloud, global_values[GLOBAL]['id'] = self.split_cloud_name( global_values[GLOBAL]['id']) values.update(global_values) if "master_tenantId" in global_values[GLOBAL]: default_tenant = global_values[GLOBAL]["master_tenantId"] else: default_tenant = getattr(global_values[GLOBAL], "project_id", None) cli = TukeyCli(jsonTrans()) try: cli.load_config_dir(local_settings.CONF_DIR + cloud) except NameError: cli.load_config_dir(local_settings.CONF_DIR) return_headers = {"headers": []} result = cli.execute_commands(command, values, object_name=name, single=self.is_single(command, req.method), proxy_method=self.openstack_proxy(req, self.path(req.path, req.method, req.query_string, name), return_headers, default_tenant)) result = self.remove_error(name, result) result = self.apply_os_exceptions(command, result) logger.debug(result) resp = Response(result) resp.conditional_response = True result_object = json.loads(result) if 'message' in result_object[name] \ and 'code' in result_object[name] \ and result_object[name]['code'] in [409,413,402]: resp.status = result_object[name]['code'] resp.headers.add('Content-Type','application/json') if req.method == "HEAD": for header, value in return_headers["headers"]: resp.headers.add(header, value) except exc.HTTPException, e: resp = e