def get_response(self): return Response(self.render_template(), mimetype="text/html")
def __call__(self, environ, start_response): request = Request(environ) if request.content_length is not None and request.content_length > self.max_length: res = Response(dumps({"message": "Payload Too Large"}), content_type="application/json", status=413) return res(environ, start_response) return self.app(environ, start_response)
def view_func(endpoint, values): if raise_this is not None: raise raise_this return Response(repr((endpoint, values)))
def dispatch_request(self, request): # 去掉 URl 中域名部分,即从 http://xxx.com/path/file?xx=xx 中提取 path/file 部分 url = "/" + "/".join(request.url.split("/")[3:]).split("?")[0] # 通过URL 寻找节点名 if url.find(self.static_folder) == 1 and url.index( self.static_folder) == 1: # 如果 URL 以静态资源文件夹名为首目录,则资源为静态资源 endpoint = 'static' url = url[1:] else: # 若不以static 为首,则从 URL 与节点的映射表中获取节点 endpoint = self.url_map.get(url, None) # 定义响应报头的, Server 参数的值表示运行的服务名,通常有 IIS, Apache, Tomact, Nginx等,这里自定义为SYL Web 0.1 headers = {'Server': 'SYL Web 0.1'} # 如果节点为空 返回404 if endpoint is None: return ERROR_MAP['404'] # 获取节点对应的执行函数 exec_function = self.function_map[endpoint] # 判断执行函数类型 if exec_function.func_type == 'route': """路由处理""" # 判断请求方法是否支持 if request.method in exec_function.options.get('methods'): """路由处理结果""" # 判断路由的执行函数是否需要请求体进行内部处理 argcount = exec_function.func.__code__.co_argcount if argcount > 0: # 需要附带请求体进行结果处理 rep = exec_function.func(request) else: # 不需要附带请求体进行结果处理 rep = exec_function.func() else: """未知请求方法""" # 返回401 错钱响应体 return ERROR_MAP['401'] elif exec_function.func_type == 'view': """ 视图处理结果 """ # 所有视图处理函数都需要附带请求体来获取处理结果 rep = exec_function.func(request) elif exec_function.func_type == 'static': """ 静态逻辑处理 """ # 静态资源返回的是一个预先封装好的响应体,所以直接返回 return exec_function.func(url) else: """ 未知类型处理 """ # 返回 503错误响应体 return ERROR_MAP['503'] # 定义 200 状态码表示成功 status = 200 # 定义响应体类型 content_type = 'text/html' # 返回响应体 return Response(rep, content_type='%s; charset=UTF-8' % content_type, headers=headers, status=status)
def oidc_config(self) -> Union[str, Response]: return Response(self.provider.provider_configuration.to_json(), mimetype="application/json")
def render_template(self, template_name, **context): t = self.jinja_env.get_template(template_name) return Response(t.render(**context), mimetype='text/html')
def paste_traceback(self, request, traceback): """Paste the traceback and return a JSON response.""" rv = traceback.paste() return Response(json.dumps(rv), mimetype='application/json')
def send_mail(): cleaned_data = clean_data(request.form) v_data = validate_data(cleaned_data) sendemail = sendEmail() response = sendemail.send(v_data) return Response(response)
def test_expected_request_response(httpserver: HTTPServer): httpserver.expect_request("/foobar").respond_with_response( Response(JSON_STRING)) assert requests.get(httpserver.url_for("/foobar")).json() == {'foo': 'bar'}
def on_upload(self, request): def find_param(data): pos = data.find(to_bytes(';', 'utf-8')) return data[:pos], pos + 1 def read_user_info(data): info_len, pos = find_param(data) info_len = int(info_len) user_info = data[pos:pos+info_len] task_ID, p = find_param(user_info) task_name = user_info[p:] pos = pos + info_len + 1 return task_name, int(task_ID), pos if request.method == 'POST': try: data = request.get_data() header = [] header_str = to_bytes('', 'utf-8') length = 0 string = to_bytes('', 'utf-8') task_name, task_id, pos = read_user_info(data) if task_id == 0: task = self.admin else: task = self.get_task() if self.admin.safe_mode: if not request.get_session(task).get('info'): return Response() for i in range(len(data)): s = data[pos + i:pos+i+1] header_str += s if s == to_bytes(';', 'utf-8'): if len(header) == 0: length = int(string) header.append(int(string)) if len(header) == 2 * (length + 1): break; string = to_bytes('', 'utf-8') else: string += s start = len(header_str) + pos path = os.path.join(os.getcwd(), os.path.normpath(to_unicode(data[start: start + header[1]], 'utf-8'))) if not os.path.exists(path): os.makedirs(path) start = start + header[1] for i in range(length): index = 2 * i + 2 file_name = to_unicode(data[start: start + header[index]], 'utf-8') start = start + header[index] index += 1 content = data[start: start + header[index]] file_name = os.path.join(path, file_name) with open(file_name, 'wb') as f: f.write(content) os.chmod(file_name, 0o666) start = start + header[index] except: traceback.print_exc() return Response()
def root_app(environ, start_response): resources = {"resources": list(dispatch_appmap.keys())} response = Response(json.dumps(resources), mimetype='application/json') return response(environ, start_response)
def dispatch_request(self, environ): request = environ['leanengine.request'] app_params = environ['_app_params'] adapter = self.url_map.bind_to_environ(request.environ) try: endpoint, values = adapter.match() except HTTPException as e: return e params = to_native(request.get_data()) values['params'] = json.loads(params) if params != '' else {} try: if endpoint == 'cloud_function': result = { 'result': dispatch_cloud_func(self.cloud_codes, app_params, decode_object=False, **values) } elif endpoint == 'rpc_function': result = { 'result': dispatch_cloud_func(self.cloud_codes, app_params, decode_object=True, **values) } elif endpoint == 'cloud_hook': result = dispatch_cloud_hook(self.cloud_codes, app_params, **values) elif endpoint == 'on_verified': result = { 'result': dispatch_on_verified(self.cloud_codes, app_params, **values) } elif endpoint == 'on_login': result = { 'result': dispatch_on_login(self.cloud_codes, app_params, **values) } elif endpoint == 'ops_meta_data': from .authorization import MASTER_KEY if request.environ.get('_app_params', {}).get('master_key') != MASTER_KEY: raise LeanEngineError(code=401, message='Unauthorized.') result = {'result': dispatch_ops_meta_data(self.cloud_codes)} elif endpoint == 'on_bigquery': result = { 'result': dispatch_on_bigquery(self.cloud_codes, app_params, **values) } else: raise ValueError # impossible return Response(json.dumps(result), mimetype='application/json') except LeanEngineError as e: return Response(json.dumps({ 'code': e.code, 'error': e.message }), status=e.code if e.code else 400, mimetype='application/json') except Exception: print(traceback.format_exc(), file=sys.stderr) return Response(json.dumps({ 'code': 141, 'error': 'Cloud Code script had an error.' }), status=500, mimetype='application/json')
def create_response(content, status_code): return Response(json.dumps(content), status_code, mimetype='application/json')
def application(env, start_response): request = Request(env) try: with map_errors_to_http(), cursor_for_request(request) as cursor: rowcount = 0 # Text resource cursor.execute( ''' select r.content, m.mimetype from endpoint.resource r join endpoint.mimetype m on r.mimetype_id = m.id where path = %s and active = true ''', (request.path, )) text_resources = cursor.fetchall() rowcount += cursor.rowcount # Binary resource cursor.execute( ''' select r.content, m.mimetype from endpoint.resource_binary r join endpoint.mimetype m on r.mimetype_id = m.id where path = %s and active = true ''', (request.path, )) binary_resources = cursor.fetchall() rowcount += cursor.rowcount # Template resource # check for matching route cursor.execute( ''' select array_to_json(regexp_matches(%s, r.url_pattern)) as match from endpoint.template_route r ''', (request.path, )) routes = cursor.fetchall() rowcount += cursor.rowcount # render template if we found one ^^. only if we don't have other rows template_resources = None if routes != None: cursor.execute( ''' select endpoint.template_render( t.id, r.args::json, array_to_json( regexp_matches(%s, r.url_pattern) ) ) as content, m.mimetype from endpoint.template_route r join endpoint.template t on r.template_id = t.id join endpoint.mimetype m on t.mimetype_id = m.id ''', (request.path, )) template_resources = cursor.fetchall() # else: # logging.info('HEEEEYYYYYYYY NO WE DID NOT GET a row') # cursor.execute(''' # select # id, regex_matches(%s, r.url_pattern), # endpoint.render_template(t.id, r.args::json) as content, 'text/html' as mimetype, r.args # from template.template t # join template.template_route r on r.template_id = t.id # where ''', (request.path,)) # template_resources = cursor.fetchall() # rowcount += cursor.rowcount # detect path collisions if rowcount > 1: raise MultipleChoices row = None if len(text_resources) == 1: row = text_resources[0] if len(binary_resources) == 1: row = binary_resources[0] if len(template_resources) == 1: row = template_resources[0] ### Commenting out until security can be audited... ### # File resource ### if row is None: ### cursor.execute(''' ### select f.content, m.mimetype ### from filesystem.file f ### left join endpoint.mimetype_extension e on e.extension = regexp_replace(f.name, '^.*\.', '') ### left join endpoint.mimetype m on m.id = e.mimetype_id ### where f.path = (select file_id from endpoint.resource_file where path=%s and active=true) ### ''', (request.path,)) ### row = cursor.fetchone() ### ### ### # Directory resource ### # Question: only directories where indexes = true? ### if row is None: ### cursor.execute(''' ### with dir as ( ### select directory_id as dir_id ### from endpoint.resource_directory ### where path=%s and indexes=true ### ) ### select path, name, last_mod, size, endpoint.is_indexed(path) as show from filesystem.directory where parent_id=(select dir_id from dir) ### union ### select path, name, last_mod, size, endpoint.is_indexed(path) as show from filesystem.file where directory_id=(select dir_id from dir) ### ''', (request.path,)) ### rows = cursor.fetchall() ### ### if len(rows): ### return Response(build_directory_index(request.path, rows), content_type='text/html') ### ### # File-in-Directory resource ### if row is None: ### cursor.execute(''' ### with dir as ( ### select directory_id as dir_id, path, char_length(path) as path_length ### from endpoint.resource_directory ### where %s like path || '%%' ### ) ### select f.content, m.mimetype ### from filesystem.file f ### left join endpoint.mimetype_extension e on e.extension = regexp_replace(f.name, '^.*\.', '') ### left join endpoint.mimetype m on m.id = e.mimetype_id ### where path = (select dir_id from dir) || substring(%s from (select path_length + 1 from dir)) ### ''', (request.path,request.path)) ### row = cursor.fetchone() # Should this redirect to /login? # That would mean: Resource Not Found = Resource Not Authorized # Which is accurate considering RLS hides unauthorized data # No because auth should occur in widgets, no redirecting if row is None: # Is this returning a 404? raise NotFound return Response(row.content, content_type='text/plain' if row.mimetype is None else row.mimetype) except HTTPException as e: return e
def empty(request): fp = file_open('marketing_automation/empty.gif', mode='rb') return Response(fp, 200, content_type='image/gif', direct_passthrough=True)
def application(request): return Response("", headers=[('X-Foo', 'bar')])
def handler(request): # pylint: disable=unused-argument return Response(response_data, status, headers, mimetype, content_type)
def path_check_app(request): return Response('PATH_INFO: %s\nSCRIPT_NAME: %s' % (request.environ.get( 'PATH_INFO', ''), request.environ.get('SCRIPT_NAME', '')))
def execute_command(self, request, command, frame): """Execute a command in a console.""" return Response(frame.console.eval(command), mimetype='text/html')
def app(request): return Response('%s|%s' % ( request.remote_addr, # do not use request.host as this fixes too :) request.environ['HTTP_HOST']))
from werkzeug.serving import run_simple from werkzeug.wrappers import Response from sylfk.wsgi_adapter import wsgi_app import sylfk.exceptions as exceptions from sylfk.helper import parse_static_key from sylfk.route import Route import os # 定义常见服务异常的响应体 ERROR_MAP = { '401': Response('<h1>401 Unknown or unsupported method</h1>', content_type='text/html; charset=UTF-8', status=401), '404': Response('<h1>404 Source Not Found</h1>', content_type='text/html; charset=UTF-8', status=404), '503': Response('<h1>503 Unknown Function Type</h1>', content_type='text/html; charset=UTF-8', status=503), } # 定义文件类型 TYPE_MAP = { 'css': 'text/css', 'js': 'text/js', 'png': 'image/png', 'jpg': 'image/jpg',
def app(request): return Response(request.remote_addr)
def get_answer(self): """ Wraps messages in an XML Response compatible with 939 API. :return: werkzeug.Response object """ return Response(self.xml_message, content_type="text/xml")
def hello_world(): return Response("Hello, World!")
def dispatch_request(self, request): # get rid of the domain part from the URL # extract 'path/file' from http://aaa.com/path/file?xx=xx # url will be '/path/file' url = '/' + '/'.join(request.url.split('/')[3:]).split('?')[0] if url.find(self.static_folder) == 1 and url.index( self.satic_folder) == 1: endpoint = 'static' url = url[1:] else: endpoint = self.url_map.get(url, None) # define response headers # usually "Server" would be IIS, Apache, Nginx and so on cookies = request.cookies headers = {'Server': 'Asura'} if 'session_id' not in cookies: headers = { 'Set-Cookie': 'session_id={}'.format(create_session_id()), 'Server': 'Asura', } if endpoint is None: raise exceptions.PageNotFoundError # return ERROR_MAP['404'] # get the execution function from function_map exec_function = self.function_map[endpoint] # judging exec func type if exec_function.func_type == 'route': ''' solving route request ''' if request.method in exec_function.options.get('methods'): # whether the route exec function need to run with Request argcount = exec_function.func.__code__.co_argcount if argcount > 0: rep = exec_function.func(request) else: rep = exec_function.func() else: ''' Unknown Request Methods''' raise exceptions.InvalidRequestMethodError # return ERROR_MAP[401] elif exec_function.func_type == 'view': ''' solving view ''' # definitely needs Request rep = exec_function.func(request) elif exec_function.func_type == 'static': # satic exec_function is dispatch_staic return exec_function.func(url) else: ''' Unknown ''' raise exceptions.UnknownFuncError # return ERROR_MAP['503'] # status 200 means request succeeded status = 200 content_type = 'text/html' if isinstance(rep, Response): return rep # return a Response return Response( rep, content_type='{}; charset=UTF-8'.format(content_type), headers=headers, status=status, )
def main(): return Response('<html><body><a href="/login">login</a></body></html>')
def to_response(self): if "r" not in self.data: self.data["r"] = 0 return Response( json.dumps(self.data), mimetype="application/json", status=self.status )
from werkzeug.wrappers import Response content_type = 'text/html; charset=UTF-8' ERROR_MAP = { '2': Response('<h1>E2 File not found</h1>', content_type=content_type, status=500), '13': Response('<h1>E13 No read permission</h1>', content_type=content_type, status=500), '401': Response('<h1>401 Unknown or Unsupport Method</h1>', content_type=content_type, status=401), '404': Response('<h1>404 Source Not Found </h1>', content_type=content_type, status=404), '503': Response('<h1>503 Unknown Function Type </h1>', content_type=content_type, status=503), } class AsuraException(Exception): def __init__(self, code='', message='Error'): self.code = code
def test_app(request): response = Response(repr(sorted(request.cookies.items()))) response.set_cookie('test1', 'foo') response.set_cookie('test2', 'bar') return response
def on_iam_list_user_policies(self, req, **kwargs): account = self._get_item_id(req, key='account', what='account') user = self._get_item_id(req, key='user', what='user') policies = self.iam.list_user_policies(account, user) res = {'PolicyNames': policies} return Response(json.dumps(res), mimetype=HTTP_CONTENT_TYPE_JSON)