def make_response(obj, _content_type='application/json'): res = Response(content_type=_content_type) if _content_type == "application/json": res.body = dumps(obj) else: res.body = obj return res
def static(request): response = Response() extension = os.path.splitext(request.path_url)[1].replace('.', '') mime = settings.mime_types.get(extension, 'text/html') file_path = os.path.join(settings.STATIC, request.path_info.replace('/static/', '')) try: file = open(file_path, 'rb') response.body = file.read() except Exception: try: file_path = os.path.join(settings.MEDIA, request.path_info.replace('/media/', '')) file = open(file_path, 'rb') response.body = file.read() except Exception: return view_404(request) else: response.content_type = mime else: response.content_type = mime return response
def __call__(self, environ, start_response): req = Request(environ) path_info = req.path_info.lstrip('/') if path_info.startswith('json'): resp = self.json(req) elif path_info.startswith('stats'): resp = Response() alias = [p for p in path_info.split('/')[1:] if p] if alias: alias = '/'.join(alias) resp.body = self.stats.render(c=get_stats(alias)) elif path_info and path_info != 'new': resp = self.redirect(req) elif not path_info and self.redirect_url: resp = exc.HTTPFound(location=self.redirect_url) else: resp = Response() resp.content_type = 'text/html' resp.charset = 'utf-8' if req.GET.get('url'): # save alias = req.GET.get('alias') alias = alias and alias or None url = req.GET.get('url') if url: c = self.add(req, url, alias) else: c = Params(error='You must provide an url !') else: c = Params(url=req.GET.get('post','')) c.title = req.params.get('title', '') c.plugin = req.params.get('p', False) resp.body = self.index.render(c=c) return resp(environ, start_response)
def json(self, req): resp = Response() resp.content_type = 'text/javascript' resp.charset = 'utf-8' alias = req.params.get('alias') url = req.params.get('url') path_info = req.path_info.lstrip('/') if path_info.startswith('json/stats'): if alias: c = get_stats(alias) else: c = Params(error='You must provide an alias !') else: if url: c = self.add(req, url, alias) else: c = Params(error='You must provide an url !') callback =req.params.get('callback') if callback: callback = str(callback) arg = req.params.get('arg') if arg: resp.body = '%s(%s, %s);' % (callback, json.dumps(arg), json.dumps(c)) else: resp.body = '%s(%s);' % (callback, json.dumps(c)) else: resp.body = json.dumps(c) return resp
def application(environ, start_response): """Determine the user's country based on their IP address.""" request = Request(environ) response = Response( status=200, cache_control=('no-store, no-cache, must-revalidate, post-check=0, ' 'pre-check=0, max-age=0'), pragma='no-cache', expires='02 Jan 2010 00:00:00 GMT', ) client_ip = request.headers.get('HTTP_X_CLUSTER_CLIENT_IP', request.client_addr) geo_data = { 'country_code': geoip.country_code_by_addr(client_ip), 'country_name': geoip.country_name_by_addr(client_ip), } # Users can request either a JavaScript file or a JSON file for the output. path = request.path_info_peek() if path == 'country.js': response.content_type = 'text/javascript' response.body = """ function geoip_country_code() {{ return '{country_code}'; }} function geoip_country_name() {{ return '{country_name}'; }} """.format(**geo_data) elif path == 'country.json': response.content_type = 'application/json' response.body = json.dumps(geo_data) else: response.status = 404 response.content_type = 'application/json' response.body = json.dumps({'error': 'Function not supported.'}) return response(environ, start_response)
def app(environ, start_response): tmpl = '''<DOCTYPE !html> <html><body><form method="POST" action="" enctype="multipart/form-data"> %s <input type="submit" id="submit" name="submit" /> </form></body></html>''' req = Request(environ) resp = Response() if fieldset is None: fs = FieldSet(model) else: fs = fieldset.bind(model) if req.method == 'POST': if fieldset is None: fs = fs.bind(request=req) else: fs = fs.bind(model=model, request=req) if fs.validate(): fs.sync() fs.readonly = True resp.body = tmpl % ('<b>OK<b>' + fs.render(),) else: resp.body = tmpl % fs.render() else: resp.body = tmpl % fs.render() return resp(environ, start_response)
def reply_log(self, log_file, log_http_max_bytes, req, req_match): max_len = log_http_max_bytes try: all = strutils.bool_from_string(req.params['all']) if all: max_len = -1 except KeyError: pass try: with open(log_file, 'rb') as fh: if max_len > 0: _left_am, contents = utils.read_backwards_up_to( fh, max_len) elif max_len == 0: contents = '' else: contents = fh.read() except IOError as e: if e.errno == errno.ENOENT: # Likely not made yet, just send back nothing... contents = '' else: raise resp = Response() resp.status = 200 resp.content_type = 'text/plain' try: contents_nl = contents.index("\n") resp.body = contents[contents_nl + 1:] except ValueError: resp.body = contents return resp
def make_response(obj, _content_type='application/json'): res = Response(content_type=_content_type) if _content_type=="application/json": res.body = dumps(obj) else: res.body = obj return res
def application(environ, start_response): req = Request(environ) resp = Response() resp.content_type = 'text/plain' resp.body = 'anonymous' if req.path_info == '/auth' and not environ.get('repoze.what.credentials'): return exc.HTTPUnauthorized()(environ, start_response) if req.path_info == '/secure': ident = environ.get('repoze.who.identity', {}) body = 'repoze.who.identity = {\n' for k, v in ident.items(): if k.lower() != 'password': body += ' %r: %r,\n' % (k, v) body += '}\n\n' cred = environ.get('repoze.what.credentials', {}) body += 'repoze.what.credentials = {\n' for k, v in cred.items(): body += ' %r: %r,\n' % (k, v) body += '}\n\n' for group in ('svn', 'bureau', 'other'): body += 'in_group(%r) == %s\n' % (group, in_group(group).is_met(environ)) for perm in ('read', 'write'): body += 'has_permision(%r) == %s\n' % ( perm, has_permission(perm).is_met(environ)) resp.body = body return resp(environ, start_response)
def get_err_response(code): """ Given an HTTP response code, create a properly formatted xml error response :param code: error code :returns: webob.response object """ error_table = { 'AccessDenied': (403, 'Access denied'), 'BucketAlreadyExists': (409, 'The requested bucket name is not available'), 'BucketNotEmpty': (409, 'The bucket you tried to delete is not empty'), 'InvalidArgument': (400, 'Invalid Argument'), 'InvalidBucketName': (400, 'The specified bucket is not valid'), 'InvalidURI': (400, 'Could not parse the specified URI'), 'NoSuchBucket': (404, 'The specified bucket does not exist'), 'SignatureDoesNotMatch': (403, 'The calculated request signature does not match '\ 'your provided one'), 'NoSuchKey': (404, 'The resource you requested does not exist')} resp = Response(content_type='text/xml') resp.status = error_table[code][0] resp.body = error_table[code][1] resp.body = '<?xml version="1.0" encoding="UTF-8"?>\r\n<Error>\r\n ' \ '<Code>%s</Code>\r\n <Message>%s</Message>\r\n</Error>\r\n' \ % (code, error_table[code][1]) return resp
def app(environ, start_response): tmpl = '''<DOCTYPE !html> <html><body><form method="POST" action="" enctype="multipart/form-data"> %s <input type="submit" id="submit" name="submit" /> </form></body></html>''' req = Request(environ) resp = Response() if fieldset is None: fs = FieldSet(model) else: fs = fieldset.bind(model) if req.method == 'POST': if fieldset is None: fs = fs.bind(request=req) else: fs = fs.bind(model=model, request=req) if fs.validate(): fs.sync() fs.readonly = True resp.body = tmpl % ('<b>OK<b>' + fs.render(), ) else: resp.body = tmpl % fs.render() else: resp.body = tmpl % fs.render() return resp(environ, start_response)
def handle_request(self, req): if (req.method == 'GET'): resp = Response(request=req) resp.body = 'you send GET method' pprint(req.environ) print req.body return resp if (req.method == 'POST'): CHUNKSIZE = 4096000 filename = req.environ.get('QUERY_STRING') fname=filename.split('=')[1] print fname #time.sleep(5) f = open(fname, "w") chunk = req.environ["wsgi.input"].read(CHUNKSIZE) # ---------- write files ---------------- print 'bbbb' #print chunk count=1 while chunk: f.write(chunk) chunk = req.environ["wsgi.input"].read(CHUNKSIZE) #print chunk print '--------------------' count=count+1 print count f.close() resp = Response(request=req) resp.body = 'you send GET method' pprint(req.environ) print req.body return resp
def get_err_response(code): """ Given an HTTP response code, create a properly formatted xml error response :param code: error code :returns: webob.response object """ error_table = { 'AccessDenied': (HTTP_FORBIDDEN, 'Access denied'), 'BucketAlreadyExists': (HTTP_CONFLICT, 'The requested bucket name is not available'), 'BucketNotEmpty': (HTTP_CONFLICT, 'The bucket you tried to delete is not empty'), 'InvalidArgument': (HTTP_BAD_REQUEST, 'Invalid Argument'), 'InvalidBucketName': (HTTP_BAD_REQUEST, 'The specified bucket is not valid'), 'InvalidURI': (HTTP_BAD_REQUEST, 'Could not parse the specified URI'), 'NoSuchBucket': (HTTP_NOT_FOUND, 'The specified bucket does not exist'), 'SignatureDoesNotMatch': (HTTP_FORBIDDEN, 'The calculated request signature does not '\ 'match your provided one'), 'NoSuchKey': (HTTP_NOT_FOUND, 'The resource you requested does not exist')} resp = Response(content_type='text/xml') resp.status = error_table[code][0] resp.body = error_table[code][1] resp.body = '<?xml version="1.0" encoding="UTF-8"?>\r\n<Error>\r\n ' \ '<Code>%s</Code>\r\n <Message>%s</Message>\r\n</Error>\r\n' \ % (code, error_table[code][1]) return resp
def GET(self, req, *parts): """ Handle GET Container (List Objects) request """ env = self._fresh_env(req) env['SERVER_PORT'] = self.conf.get('volume_endpoint_port') env['SCRIPT_NAME'] = '/v1' env['HTTP_HOST'] = '%s:%s' % \ (self.conf.get('volume_endpoint_host'), self.conf.get('volume_endpoint_port')) env['CONTENT_LENGTH'] = 0 status, headers, body, status_code = access_resource(env, 'GET', '/v1' + self.os_path, True, None, None) if status: data = json.loads(body).get('volume') body = {} body['id'] = '/'.join([self.tenant_id, 'Volume', parts[0]]) match_up(body, data, 'name', 'display_name') match_up(body, data, 'description', 'display_description') match_up(body, data, 'created', 'created_at') match_up(body, data, 'capacity', 'size') body['capacity'] = int(body['capacity']) * 1000000 body['state'] = map_volume_state(data['status']) body['bootable'] = 'false' body['type'] = 'http://schemas.dmtf.org/cimi/1/mapped' operations = [] operations.append(self._create_op('delete', '/'.join([self.tenant_id, 'volume', parts[0]]))) body['operations'] = operations if self.res_content_type == 'application/xml': response_data = {'Volume': body} else: body['resourceURI'] = '/'.join([self.uri_prefix, self.entity_uri]) response_data = body new_content = make_response_data(response_data, self.res_content_type, self.metadata, self.uri_prefix) resp = Response() self._fixup_cimi_header(resp) resp.headers['Content-Type'] = self.res_content_type resp.status = status_code resp.body = new_content return resp else: resp = Response() resp.status = status_code resp.body = 'Volume could not be found' return resp
def make_response(obj, content_type='application/json'): res = Response(content_type=content_type) if(content_type=="application/json"): res.charset = 'utf8' res.body = dumps(obj) else: res.body = obj return res
def app(environ, start_response): req = Request(environ) resp = Response(content_type='application/json') if req.method in ('GET', 'PATCH'): resp.body = json.dumps(dict(id=1, value='value')) else: resp.body = req.body return resp(environ, start_response)
def application(environ, start_response): req = Request(environ) response = Response() if req.method == 'GET': response.body = '<pre>Yeah !</pre>' else: response.body = '<a href="/plop">Yeah !</a>' return response(environ, start_response)
def make_response(obj, content_type='application/json'): res = Response(content_type=content_type) if (content_type == "application/json"): res.charset = 'utf8' res.body = dumps(obj) else: res.body = obj return res
def get_err_response(code): """ Given an HTTP response code, create a properly formatted error response :param code: error code :returns: webob.response object """ error_table = { 'AccessDenied': (403, 'Access denied'), 'ContainerAlreadyExists': (409, 'The requested Container alredy exists'), 'ContainerNotEmpty': (409, 'The container you tried to delete is not empty'), 'InvalidArgument': (400, 'Invalid Argument'), 'InvalidContainerName': (400, 'The specified container is not valid'), 'InvalidURI': (400, 'Required header or the URI formation is not correct.'), 'InvalidHeader': (400, 'CDMI required headers are not present in the request'), 'InvalidContent': (400, 'CDMI request body is not in a correct format'), 'BadRequest': (400, 'Bad request'), 'NotContainer': (400, 'Requested resource is not a CDMI container'), 'BadRequestPath': (400, 'Request url does not confirm with CDMI specification'), 'InconsistantState': (400, 'The storage state is inconsistant.'), 'VersionNotSupported': (400, 'Requested cdmi version is not supported.'), 'InvalidRange': (400, 'Requested Range is not valid.'), 'InvalidBody': (400, 'MIME message or the request body can not be parsed.'), 'NoSuchContainer': (404, 'The specified container does not exist'), 'ResourceIsNotObject': (404, 'The specified resource is not data object'), 'NoParentContainer': (404, 'The parent container does not exist'), 'NoSuchKey': (404, 'The resource you requested does not exist'), 'Conflict': (409, 'The requested name already exists as a different type')} resp = Response() if error_table.get(code): resp.status = error_table[code][0] resp.body = error_table[code][1] else: resp.status = 400 resp.body = 'Unknown Error' return resp
def input_app(environ, start_response): resp = Response() req = Request(environ) if req.path_info == '/': resp.body = '<input name="youyou" type="text" value="" />' elif req.path_info == '/submit': resp.body = '<input type="submit" value="OK" />' else: resp.body = '' return resp(environ, start_response)
def __call__(self, environ, start_response): request = Request(environ) response = Response() try: answer = self.handleRequest(request.body) response.body = answer response.content_type = "application/mobwrite" except Exception, e: log.exception("error in request handling") response.status = "500 Internal Server Error" response.body = str(e)
def input_app(environ, start_response): resp = Response() req = Request(environ) if req.path_info == '/': resp.body = b('<input name="youyou" type="text" value="" />') elif req.path_info == '/submit': resp.body = b('<input type="submit" value="OK" />') elif req.path_info.startswith('/html'): resp.body = b('<html><p>Success</p></html>') else: resp.body = '' return resp(environ, start_response)
def input_app(environ, start_response): resp = Response() req = Request(environ) if req.path_info == '/': resp.body = b'<input name="youyou" type="text" value="" />' elif req.path_info == '/submit': resp.body = b'<input type="submit" value="OK" />' elif req.path_info.startswith('/html'): resp.body = b'<html><p>Success</p></html>' else: resp.body = '' return resp(environ, start_response)
def __call__(self, env, start_response): print "enter call of app Hello, s_r=%s" % start_response req = Request(env) res = Response() res.status = "200 OK" res.content_type = "text/json" if not check_user(self.conf, req.GET): res.status = "413 auth failed!" res.body = json.dumps({'user': req.GET.get('user', None), 'passwd': req.GET.get('passwd', None)}) return res(env, start_response) res.body = json.dumps({"hello": "world"}) return res(env, start_response)
def fake_response2(): global _CPT if _CPT == 0: r = Response() r.status = '400 Bad Request' r.body = str(ERROR_NO_EMAIL_ADDRESS) elif _CPT == 1: r = Response() r.status = '400 Bad Request' r.body = str(ERROR_INVALID_RESET_CODE) _CPT += 1 return r
def fake_response2(): global _CPT if _CPT == 0: r = Response() r.status = '400 Bad Request' r.body = str(WEAVE_NO_EMAIL_ADRESS) elif _CPT == 1: r = Response() r.status = '400 Bad Request' r.body = str(WEAVE_INVALID_RESET_CODE) _CPT += 1 return r
def __call__(self, environ, start_response): match = self._mapper.match(environ['PATH_INFO']) if not match: return self._not_found(environ, start_response) controller_name = match['controller'] action_name = match['action'] controller_action = (controller_name, action_name) del match['controller'] del match['action'] environ['concurrence.application'] = self #the actual request and response instances request = Request(environ) response = Response(content_type = self.default_content_type, charset = self.default_charset) #they will be added to the task local scope here: with self._scoped_request.set(request): with self._scoped_response.set(response): if not controller_action in self._filter_chain: #we still need to setup call chain for this controller:action #calling the controller is the last thing todo in the chain: def last(next, *args, **kwargs): return self.call_controller(controller_name, action_name, *args, **kwargs) #set up call chain filter_chain = [] for i, filter in enumerate(self._filters.get(controller_action, []) + [last, None]): def create_next(_i, _filter): def next(*args, **kwargs): return _filter(filter_chain[_i + 1], *args, **kwargs) return next filter_chain.append(create_next(i, filter)) self._filter_chain[controller_action] = filter_chain #this will call the filter chain and produce the result result = self._filter_chain[controller_action][0](**match) if type(result) == str: response.body = result elif type(result) == unicode: response.unicode_body = result elif result is None: response.body = '' elif type(result) == type(response): response = result else: assert False, "result must be None, str, unicode or response object, found: %s" % type(result) return response(environ, start_response)
def app(request) -> Response: print(request.method) print(request.path) print(request.query_string) print(request.GET) print(request.POST) print(request.params) res = Response() try: if request.path == '/': res.status_code = 200 bid = request.params['id'] res.headers.add('Access-Control-Allow-Origin', '*') res.content_type = 'application/json' res.charset = 'utf-8' n = count_line(bid) doc = { "len": n / 100 } res.body = json.dumps(doc).encode() elif request.path == '/read': bid = request.params['id'] chapter_id = int(request.params['chapter']) res.headers.add('Access-Control-Allow-Origin', '*') res.content_type = 'application/json' res.charset = 'utf-8' chapters = [] for i in range(chapter_id * 100 + 1, chapter_id * 100 + 101): c = linecache.getline(bid, i) if not c: break elif c[-1] == '\n': c = c[:-1] chapters.append(c) title = es.get(index='ebooks', doc_type='book', id=bid)['_source']['title'] doc = { "t": title, "p": chapters } res.body = json.dumps(doc).encode() else: res.status_code = 404 res.body = '<h1>Not found</h1>'.encode() except Exception as e: print(e) res.status_code = 404 res.body = '<h1>Not found</h1>'.encode() return res
def debug_app(environ, start_response): req = Request(environ) if req.path_info == '/form.html' and req.method == 'GET': resp = Response(content_type='text/html') resp.body = six.b('''<html><body> <form action="/form-submit" method="POST"> <input type="text" name="name"> <input type="submit" name="submit" value="Submit!"> </form></body></html>''') return resp(environ, start_response) if 'error' in req.GET: raise Exception('Exception requested') status = str(req.GET.get('status', '200 OK')) parts = [] for name, value in sorted(environ.items()): if name.upper() != name: value = repr(value) parts.append(str('%s: %s\n') % (name, value)) body = ''.join(parts) if not isinstance(body, six.binary_type): body = body.encode('ascii') if req.content_length: body += six.b('-- Body ----------\n') body += req.body if status[:3] in ('204', '304') and not req.content_length: body = '' headers = [ ('Content-Type', str('text/plain')), ('Content-Length', str(len(body)))] for name, value in req.GET.items(): if name.startswith('header-'): header_name = name[len('header-'):] headers.append((header_name, str(value))) resp = Response() resp.status = status resp.headers.update(headers) if req.method != 'HEAD': if isinstance(body, six.text_type): resp.body = body.encode('utf8') else: resp.body = body return resp(environ, start_response)
def __call__(self, environ, start_process): url_list = [] req = Request(environ) url = req.path.strip("/") if not url.startswith("http"): https_url = "https://" + url http_url = "http://" + url url_list.extend([https_url, http_url]) else: url_list.append(url) action = req.method kwargs = dict() data = req.body kwargs["data"] = data headers = req.headers kwargs["headers"] = {} kwargs["headers"].update(headers) if kwargs["headers"].get("User-Agent", None): kwargs["headers"]["User-Agent"] = USER_AGENT if kwargs["headers"].get("Host", None): kwargs["headers"].pop("Host") # set timeout kwargs["timeout"] = 5 # print info print("request url=%s" % url) print(kwargs) response = Response() for req_url in url_list: proxy_res = requests.request(action, req_url, **kwargs) if 200 <= proxy_res.status_code < 300: response.status_code = proxy_res.status_code response.body = proxy_res.content return response(environ, start_process) else: print("error occurred with url:%s" % req_url) continue else: response.status_code = 404 response.body = "class not found" return response(environ, start_process)
def handle_request(wrapper, request): #user_agent = request.environ.get('HTTP_USER_AGENT') response = Response() response.status_code = 200 response.text = "Empty Response" handler, kwargs = wrapper.find_handler(request) compress = True if handler is not None: if (inspect.isclass(handler)): handler = getattr(handler(), request.method.lower(), None) if handler is not None: handler(request, response, **kwargs) else: wrapper.err503(response) else: handler(request, response, **kwargs) if compress: response.body = brotli.compress(response.text.encode()) response.content_encoding = "br" else: try: try: FileType, noText = wrapper.getFileType(request.path) print(FileType, noText) response.content_type = FileType if (noText): print("\n\n****************\n\n") print("loc:", wrapper.root + "/static" + request.path) response.body = open( wrapper.root + "/static" + request.path, "rb").read() else: print("\n\n****************\n\n") print("loc:", wrapper.root + "/static" + request.path) response.text = open(wrapper.root + "/static" + request.path).read() response.cache_control = "max-age=" + str( wrapper.staticCache) except Exception as e: print(e) wrapper.err404(response) except Exception as e: print(e) response.text = "Well My Work Was Not Clean Enough, but...<br><b>Thats A Server Problem</b>" response.status_code = 500 return response
def __call__(self, environ, start_response): req = Request(environ) resp = Response() filename = req.path_info.strip('/') lfilename = filename.lower() if not req.path_info.strip('/') or os.path.isdir(filename): if filename: filename = path(filename, 'index.html') else: filename = 'index.html' body = open(filename, 'rb').read() resp.body = body elif os.path.isfile(filename): if req.method.lower() == 'delete': sh.rm(filename + '*', shell=True) resp = exc.HTTPNoContent() return resp(environ, start_response) if req.path_info.endswith('.metadata'): cfg = ConfigObject(filename=filename) if req.method.lower() == 'get': resp.content_type = 'application/json' elif req.method.lower() == 'put': data = json.loads(req.body) cfg.metadata.update(data) cfg.write() metadata = dict(cfg.metadata.items()) metadata.update(tags=cfg.metadata.tags.as_list()) resp.body = json.dumps(metadata) elif req.path_info.endswith('.js'): resp.content_type = 'text/javascript' elif req.path_info.endswith('.json'): resp.content_type = 'application/json' elif req.path_info.endswith('.css'): resp.content_type = 'text/css' elif lfilename.endswith('.jpg'): resp.charset = None resp.content_type = 'image/jpeg' print(filename) if not resp.content_length: resp.app_iter = fd(filename) elif req.path_info.startswith('/delete/'): filename = req.path_info[8:-1] self.delete(filename) resp.status_int = 302 resp.location = '/' + path.dirname(filename) else: resp.body = str(req.path_info) resp.last_modified = datetime.now() return resp(environ, start_response)
def application(environ, start_response): req = Request(environ) resp = Response() env_input = environ['wsgi.input'] len_body = len(req.body) env_input.input.seek(0) if req.path_info == '/read': resp.body = env_input.read(len_body) elif req.path_info == '/read_line': resp.body = env_input.readline(len_body) elif req.path_info == '/read_lines': resp.body = b'-'.join(env_input.readlines(len_body)) elif req.path_info == '/close': resp.body = env_input.close() return resp(environ, start_response)
def __call__(self, environ, start_response): req = Request(environ) res = Response() if req.body != "": data = json.loads(req.body) result = self.save_to_db(data) res.body = result else: # LOG.info(u"this is {}".format(json.dumps(data))) with open("/root/wsgi_demo/wsgi_demo/firsttry/templates/save.html", 'r') as f: data = f.read().decode("utf8") res.body = data.encode("utf8") res.status = 200 return res(environ, start_response)
def __call__(self, env, start_response): print "enter call of app Hello, s_r=%s" % start_response req = Request(env) res = Response() res.status = "200 OK" res.content_type = "text/json" if not check_user(self.conf, req.GET): res.status = "413 auth failed!" res.body = json.dumps({ 'user': req.GET.get('user', None), 'passwd': req.GET.get('passwd', None) }) return res(env, start_response) res.body = json.dumps({"hello": "world"}) return res(env, start_response)
def post(self): params = self.request.params api = BoruvkaAuthApi(self.dao) request_dict = {} for key, value in params.items(): request_dict[key] = value user_id, token_value = api.login( payload=request_dict, ) if user_id: self.session['user_id'] = user_id response = exc.HTTPMovedPermanently(location=self.request.application_url) response.set_cookie( name='Token', value=token_value, ) self.session.save() self.session.persist() return response else: # TODO: move translations handling to BaseController translation = list(self.request.accept_language)[0] view = BoruvkaAuthLoginView(translation) view.error = "Unauthorized" response = Response() response.body = view.render() #response = exc.HTTPUnauthorized() return response
def notfound(request:Request): res = Response() res.status_code = 404 res.body = 'Not Found!'.encode() res.content_type = 'text/html; charset=utf-8' res.server = 'eysdo/Server_v4' return res
def relay(self, req): """Relay a request to a remote machine for JS proxying""" host = req.GET['host'] conn = httplib.HTTPConnection(host) headers = req.headers # Re-assemble the query string query_str = {} for param, val in req.GET.iteritems(): if param in ['host', 'path']: continue query_str[param] = val query_str = urllib.urlencode(query_str) # Transport a GET or a POST if req.method == 'GET': conn.request("GET", '%s?%s' % (req.GET['path'], query_str), headers=headers) elif req.method == 'POST': conn.request("POST", req.GET['path'], req.body, headers=headers) # Handle the response and pull out the headers to proxy back resp = conn.getresponse() res = Response() for header, value in resp.getheaders(): if header.lower() in ['server', 'date']: continue res.headers[header] = value res.body = resp.read() return res
def downloadData(self, req): CHUNKSIZE = 4096000 filename = req.environ.get("QUERY_STRING") fname = filename.split("=")[1] print fname # time.sleep(5) f = open(fname, "w") chunk = req.environ["wsgi.input"].read(CHUNKSIZE) # ---------- write files ---------------- print "bbbb" # print chunk count = 1 while chunk: f.write(chunk) chunk = req.environ["wsgi.input"].read(CHUNKSIZE) # print chunk print "--------------------" count = count + 1 print count f.close() resp = Response(request=req) resp.body = "save over" pprint(req.environ) print req.body return resp
def source_code(self, req): location = req.params['location'] module_name, lineno = location.split(':', 1) module = sys.modules.get(module_name) if module is None: # Something weird indeed res = Response(content_type='text/html', charset='utf8') res.body = 'The module <code>%s</code> does not have an entry in sys.modules' % module_name return res filename = module.__file__ if filename[-4:] in ('.pyc', '.pyo'): filename = filename[:-1] elif filename.endswith('$py.class'): filename = '%s.py' % filename[:-9] f = open(filename, 'rb') source = f.read() f.close() html = ( ('<div>Module: <b>%s</b> file: %s</div>' '<style type="text/css">%s</style>' % (module_name, filename, formatter.pygments_css)) + formatter.highlight(filename, source, linenos=True)) source_lines = len(source.splitlines()) if source_lines < 60: html += '\n<br>'*(60-source_lines) res = Response(content_type='text/html', charset='utf8') res.unicode_body = html return res
def showall(self, req): dir_name = self.profile_path profiles = [] errors = [] max_cost = 1 # avoid division by zero for profile_file in os.listdir(dir_name): if profile_file.endswith('.pkl'): path = os.path.join(self.profile_path, profile_file) modified = os.stat(path).st_mtime try: with open(path, 'rb') as f: data = cPickle.load(f) except Exception as e: errors.append((modified, '%s: %s' % (e.__class__.__name__, e), profile_file[:-4])) else: environ = data['environ'] top = [x for x in data['profile'].values() if not x.get('callers')] if top: total_cost = max(float(x['cost']) for x in top) else: total_cost = 0 max_cost = max(max_cost, total_cost) profiles.append((modified, environ, total_cost, profile_file[:-4])) profiles.sort(reverse=True, key=itemgetter(0)) errors.sort(reverse=True) res = Response() if profiles: earliest = profiles[-1][0] else: earliest = None res.body = self.render('/list_profiles.mako', profiles=profiles, errors=errors, now=time.time(), earliest=earliest, max_cost=max_cost) return res
def __call__(self, req): if req.headers.get("X-Auth-Token"): # already has auth token pass else: # We expire the token every 10 minutes if time.time() - self.token_timestamp >= 600000: self.token_timestamp = time.time() self.token = None self.access_resource(req) if req.path == self.auth_id: res = Response() res.status = 200 res.headers["Content-Type"] = "text/plain" res.body = str(self.tenant_id) + "\r\n" return res else: if self.sub_tenant_id: parts = req.environ.get("PATH_INFO").split("/") if len(parts) > 1 and self.tenant_id: parts[1] = self.tenant_id req.environ["PATH_INFO"] = "/".join(parts) return self.application
def make_response(self, filename): filetype, encoding = mimetypes.guess_type(filename) if filetype == None: filetype = 'application/octet-stream' res = Response(content_type=filetype) res.body = open(filename, 'rb').read() return res
def getRule(self, req): ''' Get rules from local.rules file :param req: http requests header ''' rule_dict = [] with open(self.file_address) as f: for rule in f: splitRule = rule.split('(') orderedPart = splitRule[0].strip().split() unorderedPart = splitRule[1] jsonRule = { "action": str(orderedPart[0]), "protocol": str(orderedPart[1]), "sourceip": str(orderedPart[2]), "sourceport": str(orderedPart[3]), "direction": str(orderedPart[4]), "destinationip": str(orderedPart[5]), "destinationport": str(orderedPart[6]), "msg": re.search(r'msg:(.*?);', unorderedPart, re.I).group(1), "priority": re.search(r'priority:(.*?);', unorderedPart, re.I).group(1), "sid": re.search(r'sid:(.*?);', unorderedPart, re.I).group(1), "rev": re.search(r'rev:(.*?);', unorderedPart, re.I).group(1) } rule_dict.append(jsonRule) response = Response(request=req, status=200, content_type='application/json') response.body = json.dumps(rule_dict) return response
def _respond_bad_request(self, request, message="Bad Request"): """Generate a "400 Bad Request" error response.""" resp = Response() resp.status = 400 resp.body = message request.environ["repoze.who.application"] = resp return None
def get(self): # TODO: move translations handling to BaseController translation = list(self.request.accept_language)[0] view = BoruvkaAuthLoginView(translation) response = Response() response.body = view.render() return response
def __call__(self, environ, start_response): """Callable method for WSGI applications. Each request to CurryProxy starts here. First, match the incoming request to a configured route. Then pass the request to the matching route. Finally, return the response received from the matching route back to the client. If a route cannot be found to handle the request, return a 403 Forbidden. Args: environ: Dictionary representing the incoming request as specified by PEP 333. start_response: Callable used to begin the HTTP response as specified by PEP 333. """ request = Request(environ) response = None logging.info('Received request: %s', request.url, extra={'request_uuid': environ[ENVIRON_REQUEST_UUID_KEY]}) try: matched_route = self._match_route(request.url) response = matched_route(request) except RequestError as request_error: response = Response() response.status = 403 response.body = json.dumps(str(request_error)).encode() start_response(response.status, response.headerlist) return [response.body]
def get_err_response(code): """ Given an HTTP response code, create a properly formatted error response :param code: error code :returns: webob.response object """ error_table = { 'AccessDenied': (403, 'Access denied'), 'BadRequest': (400, 'Bad request'), 'MalformedBody': (400, 'Request body can not be parsed, malformed request body'), 'NotFound': (404, 'Resource was not found'), 'NotImplemented': (501, 'Not implemented'), 'TestRequest': (200, 'Test request'), 'Conflict': (409, 'The requested name already exists as a different type')} resp = Response() resp.status = error_table[code][0] resp.body = error_table[code][1] return resp
def best_response(self, req, statuses, reasons, bodies, server_type, etag=None): """ Given a list of responses from several servers, choose the best to return to the API. :param req: webob.Request object :param statuses: list of statuses returned :param reasons: list of reasons for each status :param bodies: bodies of each response :param server_type: type of server the responses came from :param etag: etag :returns: webob.Response object with the correct status, body, etc. set """ resp = Response(request=req) if len(statuses): for hundred in (HTTP_OK, HTTP_MULTIPLE_CHOICES, HTTP_BAD_REQUEST): hstatuses = \ [s for s in statuses if hundred <= s < hundred + 100] if len(hstatuses) > len(statuses) / 2: status = max(hstatuses) status_index = statuses.index(status) resp.status = '%s %s' % (status, reasons[status_index]) resp.body = bodies[status_index] resp.content_type = 'text/html' if etag: resp.headers['etag'] = etag.strip('"') return resp self.app.logger.error(_('%(type)s returning 503 for %(statuses)s'), {'type': server_type, 'statuses': statuses}) resp.status = '503 Internal Server Error' return resp
def _exec_shell(self, req): print '_exec_shell is called.' try: cmd = [] cmd.append(self.path) response_body = {'stdout':[], 'stderr':None} response = Response(content_type='application/json', charset='json') script = os.path.join(os.path.join(CURRENT_DIR, 'scripts'), self.script) if not os.path.exists(script): return webob.exc.HTTPInternalServerError(detail='shell script not exist.') cmd.append(script) print cmd parameter = self.get_parameter_values(req) print parameter if isinstance(parameter, list): cmd += parameter else: return parameter fp_out = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if fp_out.stderr != None: response_body['stderr'] = fp_out.stderr.read() if fp_out.stdout != None: for line in fp_out.stdout.readlines(): response_body['stdout'].append(line) response.status = 200 response.body = json.dumps(response_body) return response except Exception, e: return webob.exc.HTTPInternalServerError(detail=str(e))
def simple_app(environ, start_response): # 这两个参数是自动注入的 request = Request(environ) qurey_string = request.query_string method = request.method # print(qurey_string, method) print(request.GET) print(type(request.GET)) # dict 只管理get print(request.POST) # 只管理post print(request.params) # 同时管理get和post print(request.path) print(request.headers) # 请求头 res = Response() print(res.status_code) # 200 print(res.status) # 200 OK print(res.headers) # object print(res.headerlist) # list # status = '200 OK' # headers = [('Content-type', 'text/plain; charset=utf-8')] # start_response(res.status, res.headerlist) # 在返回正文之前首先要返回状态码,报文头 res.body = '<h1>test_text</h1>'.encode('utf-8') return res(environ, start_response) # 这里return的是正文,必须是个可迭代对象,一般是列表,可以是一个字符串元素
def get_merged_containers_with_marker_resp(self, req, location, marker): """ """ if marker.find(self.combinater_char) == -1: return HTTPNotFound(request=req) marker_prefix = self._get_container_prefix(marker) if not self.loc.servers_by_container_prefix_of(location, marker_prefix): return HTTPNotFound(request=req) real_marker = marker.split(marker_prefix + ':')[1] swift_svrs = self.loc.servers_by_container_prefix_of( location, marker_prefix) swift_server_subscript = self._get_servers_subscript_by_prefix( location, marker_prefix) each_tokens = self._get_each_tokens(req) query = parse_qs(urlparse(req.url).query) query['marker'] = real_marker real_path = '/' + '/'.join(self._get_real_path(req)) url = self._combinate_url(req, swift_svrs[0], real_path, query) req.headers['x-auth-token'] = each_tokens[swift_server_subscript] resp = self.relay_req(req, url, self._get_real_path(req), swift_svrs, self.loc.webcache_of(location)) m_headers = self._merge_headers([resp], location) m_body = '' if req.method == 'GET': if self._has_header('content-type', [resp]): content_type = [ v for k, v in m_headers if k == 'content-type' ][0] m_body = self._merge_container_lists(content_type, [resp.body], [marker_prefix]) resp = Response(status='200 OK') resp.headerlist = m_headers resp.body = m_body return resp