def dispatch(self, environ, start_response): try: local.request = Request(environ) local.response = Response() local.session = Session(local.request.cookies.get("session")) try: local.url_adapter = url_adapter = url_map.bind_to_environ( environ) try: endpoint, params = url_adapter.match() except NotFound: endpoint = "notfound" params = {} local.endpoint = endpoint endpoints[endpoint](**params) except: if self.debug: raise responders.error() response = local.response local.session.save() local.session.set_cookie(local.response) except: if self.debug: raise response = Response("Fejlsidens fejlside.") return response(environ, start_response)
def __call__(self, environ, start_response): local.application = self request = Request(environ) self.load_session(request) response = None try: adapter = self.url_map.bind_to_environ(environ) endpoint, vars = adapter.match() if 'userid' not in request.session and endpoint != "general.register": endpoint = 'general.login' response = self.dispatch(request, adapter, endpoint, {}) response.status_code = 401 else: response = self.dispatch(request, adapter, endpoint, vars) except NotFound: b = BaseController(request, adapter) response = b.return_404() except InternalServerError: request.environ['wsgi.errors'].write(traceback.format_exc()) b = BaseController(request, adapter) response = b.return_500() except Forbidden: b = BaseController(request, adapter) response = b.return_403() except HTTPException, e: request.environ['wsgi.errors'].write(traceback.format_exc()) response = e
def application(environ, start_responseonse): request = Request(environ) if request.method == 'POST': response = stats(request) else: response = upload_file(request) return response(environ, start_responseonse)
def __call__(self, environ, start_response): request = Request(environ) lang = request.values.get('_lang') if lang is None: lang = (request.accept_languages.best or 'en').split('-')[0].lower() if not has_language(lang): lang = 'en' request.translations = load_core_translations(lang) request.translations.language = lang response = None if request.path == '/': view = request.values.get('_current', 'start') if request.values.get('_startsetup'): response = self.start_setup(request) elif view in self.views: handler = self.views[view] if handler is not None and \ request.values.get('_next'): ctx = handler(request) if ctx is not None: response = self.handle_view(request, view, ctx) if response is None: if request.values.get('_next'): view = self.next[view] elif request.values.get('_prev'): view = self.prev[view] response = self.handle_view(request, view) if response is None: response = redirect('') return response(environ, start_response)
def __call__(self, environ, start_response): # start_response('200 OK', [('Content-Type', 'text/plain')]) # return [b'hello world'] request = Request(environ) text = 'hellow, %s' % (request.args.get('a', 'i love imooc')) response = Response(text, mimetype="text/plain") return response(environ, start_response)
def test_form(self): """Test for modifying existing entity with ModelForm.""" # first create a new entity f = TestModelForm() params = {"number": "12", "data_field": "data string", "is_active": "False", "string_list_field": "list"} self.assertEqual(f.validate(params), True) f.save() self.assertEqual(TestModel.all().count(), 1) entity = TestModel.all().get() self.assertEqual(entity.number, 12) # modify with TestModelForm f = TestModelForm(instance=entity) params = {"number": "13", "data_field": "modified data", "is_active": "True", "string_list_field": "line 1\nline 2"} self.assertEqual(f.validate(params), True) f.save() # check values self.assertEqual(TestModel.all().count(), 1) entity = TestModel.all().get() self.assertEqual(entity.number, 13) self.assertEqual(entity.data_field, "modified data") self.assertEqual(entity.is_active, True) self.assertEqual(entity.string_list_field, ["line 1", "line 2"]) """Form validation test with ModelForm.""" os.environ['REQUEST_METHOD'] = 'POST' local.request = Request(get_env()) f = TestModelForm() params = {"number": "12"} # In your view, you can validate the form data with: # f.validate(request.form) # or with(If you have FileField): # f.validate(request.form, request.files) self.assertEqual(f.validate(params), False) f.reset() params = {"number": "12", "data_field": "data string longer than 20 characters", "is_active": "False", "string_list_field": "test"} self.assertEqual(f.validate(params), False) f.reset() params = {"number": "12", "data_field": "data string", "is_active": "False", "string_list_field": ""} self.assertEqual(f.validate(params), False) # create a new entity f.reset() params = {"number": "12", "data_field": "data string", "is_active": "False", "string_list_field": "list"} self.assertEqual(f.validate(params), True) f.save() self.assertEqual(TestModel.all().count(), 2)
def _application(self, environ, start_response): request = Request(environ) self.logger.info(request.full_path) status_code = 200 headers = {'Content-Type': 'application/json'} content = '' if request.path == '/': # 接管主页,因为所有请求需要token,主页转发不能正常工作 headers = {'Content-Type': 'text/html'} content = '<h1><a href="https://github.com/xiyaoWong/iotbot-http-transfer">iotbot http tranfer</a><h1>' elif request.path.strip('/') == 'favicon.ico': status_code = 301 del headers['Content-Type'] headers['location'] = 'https://cdn.jsdelivr.net/gh/xiyaowong/FileHost/transfer.png' elif request.path.strip('/') == 'genToken': # 处理token生成请求 key = request.args.get('key') if key == self.key: token = self._genarate_token('ok, it\' funny.') content = json.dumps({'token': token}) else: content = '{"Ret":1111, "Msg":"key错误"}' else: # 处理其他请求 # 鉴权 token = request.args.get('token') or request.headers.get('Authorization') if not self._check_token(token): # 大胆,狗贼 content = '{"Ret":2222, "Msg":"无效的token"}' else: try: resp = requests.request( request.method, '{}{}?{}'.format( 'http://{}:{}'.format(self.iotbot_host, self.iotbot_port), request.path, request.query_string.decode()), headers=request.headers, data=request.data, timeout=self.timeout ) except requests.Timeout as e: self.logger.warning(e) content = '{"Ret":3333, "Msg":"请求响应超时"}' except requests.ConnectionError as e: self.logger.exception(e) content = '{"Ret":4444, "Msg":"连接错误"}' except Exception as e: self.logger.exception(e) content = '{"Ret":5555, "Msg":"请求响应失败"}' else: content = resp.content status_code = resp.status_code headers = resp.headers response = Response(content) response.status = HTTP_STATUS_CODES[status_code] response.status_code = status_code for header_name, header_value in headers.items(): response.headers[header_name] = header_value return response(environ, start_response)
def __call__(self, environ, start_response): request = Request(environ) auth = request.authorization if not auth or not self.check_auth(auth.username, auth.password): response = self.auth_required(request) else: response = self.dispatch_request(request) return response(environ, start_response)
def __call__(self, environ, start_response): request = Request(environ) urls = self.url_map.bind_to_environ(environ) try: endpoint, args = urls.match() except NotFound, exc: args = {} endpoint = '/'
def makeRequest(self, run, tag, host): req = Request({}) req.args = { 'run': run, 'tag': tag, 'host': host, } return req
def _create_request(*, path_info: str = "/path") -> Request: return Request({ "wsgi.url_scheme": "https", "SERVER_NAME": "example.com", "SERVER_PORT": "443", "SCRIPT_NAME": "/base/", "PATH_INFO": path_info, })
def __call__(self, environ, start_response): request = Request(environ) method = request.args.get('METHOD', '').upper() if method in self.allowed_methods: method = method.encode('ascii', 'replace') environ['REQUEST_METHOD'] = method if method in self.bodyless_methods: environ['CONTENT_LENGTH'] = 0 return self.app(environ, start_response)
def dispatch_request(self, environ, start_response): self.bind_to_context() local.request = request = Request(environ, start_response) local.url_adapter = adapter = url_map.bind_to_environ(environ) try: endpoint, values = adapter.match(request.path) response = endpoints[endpoint](request, **values) except HTTPException, e: response = e
def test_digest_challenge_response(): request = Request(environ={'REMOTE_ADDR': "example.com"}) result = digest_challenge_response(request, None, None) assert '''qop="auth, auth-int"''' in result.headers["WWW-Authenticate"] assert '''algorithm=''' not in result.headers["WWW-Authenticate"] result = digest_challenge_response(request, "flibble", "flamble") assert '''qop="flibble"''' in result.headers["WWW-Authenticate"] assert '''algorithm=flamble''' in result.headers["WWW-Authenticate"]
def __call__(self, environ, start_response): request = Request(environ) urls = self.url_map.bind_to_environ(environ) try: endpoint, args = urls.match() except NotFound, exc: # Convert unknown /path/names into endpoints named path_names endpoint = request.path.lstrip('/').replace('/', '_') args = {}
def __call__(self, environ, start_response): request = None try: request = Request(environ, self.mapping) response = self.dispatch(request) return response(environ, start_response) except RequestRedirect as e: return Response(status=e.code, headers={'Location': e.new_url})(environ, start_response) except Exception as e: return self.error_handler(e, request)(environ, start_response)
def __call__(self, environ, start_response): request = Request(environ) if self.input_name in request.form: method = request.form[self.input_name].upper() if method in ['GET', 'POST', 'PUT', 'DELETE']: environ['REQUEST_METHOD'] = method return self.app(environ, start_response)
def __call__(self, environ, start_response): request = Request(environ) adapter = self.urlmap.bind_to_environ(environ) try: entrypoint, pvalues = adapter.match() request.path_values = pvalues response = entrypoint.handle_request(request) except werkzeug.exceptions.HTTPException as e: response = e return response(environ, start_response)
def dispatch(self, environ, start_response): local.application = self request = Request(environ) local.url_adapter = adapter = url_map.bind_to_environ(environ) try: endpoint, values = adapter.match() endpoint, module = endpoint.split(' ') handler = getattr(views, endpoint) response = handler(request, **values) except HTTPException, e: response = e
def __call__(self, environ, start_response): request = Request(environ) if request.method == 'GET': log.debug('No CSRF check for GET') else: if 'CsrfCheck' in request.headers: log.debug('Found CsrfCheck') else: log.error(f'No CsrfCheck header for {request.method}') raise BadRequest() return self.app(environ, start_response)
def dispatch(self, environ, start_response): local.application = self request = Request(environ) local.url_adapter = adapter = url_map.bind_to_environ(environ) try: endpoint, values = adapter.match() handler = getattr(views, endpoint) response = handler(request, **values) except NotFound, e: response = views.not_found(request) response.status_code = 404
def test_appstats_middleware(self): request = Request({}) middleware = AppStatsMiddleware() r = middleware.process_request(request) self.assertTrue(r is None) r = middleware.process_response(request, BaseResponse("", 200)) self.assertTrue(isinstance(r, BaseResponse)) summary = recording.load_summary_protos() self.assert_(summary)
def _verify_user(environ) -> RFC7662: verified: List[RFC7662] = [] auth_header = environ.get("HTTP_AUTHORIZATION", "") basic_user = None if auth_header: auth_type, _ = auth_header.split(None, 1) if auth_type == "Bearer": user_id, secret = user_from_bearer_header(auth_header) automation_user = automation_auth(user_id, secret) if automation_user: verified.append(automation_user) else: # GUI user and Automation users are mutually exclusive. Checking only once is less # work for the system. gui_user = gui_user_auth(user_id, secret) if gui_user: verified.append(gui_user) elif auth_type == "Basic": # We store this for sanity checking below, once we get a REMOTE_USER key. # If we don't get a REMOTE_USER key, this value will be ignored. basic_user = user_from_basic_header(auth_header) else: raise MKAuthException(f"Unsupported Auth Type: {auth_type}") remote_user = environ.get("REMOTE_USER", "") if remote_user and userdb.user_exists(UserId(remote_user)): if basic_user and basic_user[0] != remote_user: raise MKAuthException("Mismatch in authentication headers.") verified.append(rfc7662_subject(UserId(remote_user), "webserver")) cookie = Request(environ).cookies.get(f"auth_{omd_site()}") if cookie: user_id, session_id, cookie_hash = user_from_cookie(cookie) check_parsed_auth_cookie(user_id, session_id, cookie_hash) verified.append(rfc7662_subject(user_id, "cookie")) if not verified: raise MKAuthException( "You need to be authenticated to use the REST API.") # We pick the first successful authentication method, which means the precedence is the same # as the oder in the code. final_candidate = verified[0] if not userdb.is_customer_user_allowed_to_login(final_candidate["sub"]): raise MKAuthException(f"{final_candidate['sub']} may not log in here.") if userdb.user_locked(final_candidate["sub"]): raise MKAuthException(f"{final_candidate['sub']} not authorized.") return final_candidate
def __call__(self, environ, start_response): request = Request(environ) if request.method != "POST": raise exceptions.MethodNotAllowed if not request.content_type.startswith('application/json'): raise exceptions.BadRequest try: data = json.loads(request.data) except ValueError, e: resdata = {'jsonrpc':'2.0', 'id':None, 'error':{'code':PARSE_ERROR, 'message':errors[PARSE_ERROR]}}
def eko_app(environ, start_response): """Dispatch the request to either client forwarding or request storage. This is solely based on the User-Agent, which must start with 'eko/' for eko clients. """ request = Request(environ) if request.user_agent.string.startswith("eko/"): app = client_fwd_app else: app = request_fwd_app try: return app(environ, start_response) except HTTPException, e: return e(environ, start_response)
def _verify_request(environ) -> RFC7662: auth_header = environ.get('HTTP_AUTHORIZATION', '') if auth_header: return bearer_auth(auth_header) cookie = Request(environ).cookies.get(f"auth_{omd_site()}") if cookie: try: username, session_id, cookie_hash = cookie.split(':', 2) except ValueError: raise MKAuthException("Invalid auth cookie.") check_parsed_auth_cookie(UserId(username), session_id, cookie_hash) return rfc7662_subject(username, 'cookie') raise MKAuthException("You need to be authenticated to use the REST API.")
def application(environ, start_response): """ """ req = Request(environ) if req.path in views: resp = views[req.path](req) elif req.path.startswith(ROOT_URL): resp = query( req, req.path.replace(ROOT_URL + '/', '').replace(ROOT_URL, '')) elif req.path.startswith('/static'): resp = static_serve(req, req.path.replace('/static/', '')) else: resp = not_found() return resp(environ, start_response)
def __call__(self, environ, start_response): urls = self.url_map.bind_to_environ(environ) try: endpoint, args = urls.match() request = Request(environ) args['req'] = request response = endpoint(**args) except NotFound: # kill tracebacks if browser is looking for js map files if environ['PATH_INFO'].endswith('.js.map'): response = Response('', status=404) else: raise return response(environ, start_response)
def make_data_request(run, tool, host=None): """Creates a werkzeug.Request to pass as argument to ProfilePlugin.data_impl. Args: run: Front-end run name. tool: ProfilePlugin tool, e.g., 'trace_viewer'. host: Host that generated the profile data, e.g., 'localhost'. Returns: A werkzeug.Request to pass to ProfilePlugin.data_impl. """ req = Request({}) req.args = {'run': run, 'tag': tool} if host: req.args['host'] = host return req
def _verify_user(environ) -> RFC7662: verified: List[RFC7662] = [] auth_header = environ.get('HTTP_AUTHORIZATION', '') if auth_header: user_id, secret = user_from_bearer_header(auth_header) automation_user = automation_auth(user_id, secret) gui_user = gui_user_auth(user_id, secret) if not (automation_user or gui_user): raise MKAuthException(f"{user_id} not authorized.") if automation_user: verified.append(automation_user) if gui_user: verified.append(gui_user) remote_user = environ.get('REMOTE_USER', '') if remote_user and userdb.user_exists(UserId(remote_user)): verified.append(rfc7662_subject(UserId(remote_user), 'webserver')) cookie = Request(environ).cookies.get(f"auth_{omd_site()}") if cookie: user_id, session_id, cookie_hash = user_from_cookie(cookie) check_parsed_auth_cookie(user_id, session_id, cookie_hash) verified.append(rfc7662_subject(user_id, 'cookie')) if not verified: raise MKAuthException( "You need to be authenticated to use the REST API.") # We pick the first successful authentication method, which means the precedence is the same # as the oder in the code. final_candidate = verified[0] if not userdb.is_customer_user_allowed_to_login(final_candidate['sub']): raise MKAuthException(f"{final_candidate['sub']} may not log in here.") if userdb.user_locked(final_candidate['sub']): raise MKAuthException(f"{final_candidate['sub']} not authorized.") return final_candidate