Python flask.Request() Examples

The following are 30 code examples of flask.Request(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask , or try the search function .
Example #1
Source File: test_api_lib_policy.py    From privacyidea with GNU Affero General Public License v3.0 7 votes vote down vote up
def test_19_papertoken_count(self):
        g.logged_in_user = {"username": "admin1",
                            "realm": "",
                            "role": "admin"}
        builder = EnvironBuilder(method='POST',
                                 headers={})
        env = builder.get_environ()
        # Set the remote address so that we can filter for it
        env["REMOTE_ADDR"] = "10.0.0.1"
        g.client_ip = env["REMOTE_ADDR"]
        req = Request(env)
        set_policy(name="paperpol",
                   scope=SCOPE.ENROLL,
                   action="{0!s}=10".format(PAPERACTION.PAPERTOKEN_COUNT))
        g.policy_object = PolicyClass()

        # request, that matches the policy
        req.all_data = {}
        req.User = User()
        papertoken_count(req)
        # Check if the papertoken count is set
        self.assertEqual(req.all_data.get("papertoken_count"), "10")

        # finally delete policy
        delete_policy("paperpol") 
Example #2
Source File: dataframe_input.py    From BentoML with Apache License 2.0 6 votes vote down vote up
def handle_request(self, request: flask.Request, func):
        if request.content_type == "text/csv":
            csv_string = StringIO(request.get_data(as_text=True))
            df = pd.read_csv(csv_string)
        else:
            # Optimistically assuming Content-Type to be "application/json"
            try:
                df = pd.read_json(
                    request.get_data(as_text=True),
                    orient=self.orient,
                    typ=self.typ,
                    dtype=False,
                )
            except ValueError:
                raise BadInput(
                    "Failed parsing request data, only Content-Type application/json "
                    "and text/csv are supported in BentoML DataframeInput"
                )

        if self.typ == "frame" and self.input_dtypes is not None:
            check_dataframe_column_contains(self.input_dtypes, df)

        result = func(df)
        return self.output_adapter.to_response(result, request) 
Example #3
Source File: test_lib_eventhandler_usernotification.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_08_check_conditions_serial(self):
        uhandler = UserNotificationEventHandler()
        # check a serial with regexp
        builder = EnvironBuilder(method='POST',
                                 data={'user': "cornelius@realm1"},
                                 headers={})

        env = builder.get_environ()
        req = Request(env)
        req.all_data = {"user": "cornelius@realm1",
                        "serial": "OATH123456"}
        req.User = User("cornelius", "realm1")
        resp = Response()
        resp.data = """{"result": {"value": true}}"""
        r = uhandler.check_condition(
            {"g": {},
             "handler_def": {"conditions": {"serial": "^OATH.*"}},
             "request": req,
             "response": resp
             }
        )
        # Serial matches the regexp
        self.assertEqual(r, True) 
Example #4
Source File: test_lib_eventhandler_logging.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_02_loggingevent_default(self, capture):
        # simple logging event with default values
        g = FakeFlaskG()
        g.audit_object = FakeAudit()
        env = EnvironBuilder(method='POST', headers={}, path='/auth').get_environ()
        req = Request(env)
        req.all_data = {}
        resp = Response(response="""{"result": {"value": true}}""")
        options = {
            "g": g,
            "request": req,
            "response": resp,
            "handler_def": {
            }
        }
        log_handler = LoggingEventHandler()
        res = log_handler.do("logging", options=options)
        self.assertTrue(res)
        capture.check(
            ('pi-eventlogger', 'INFO', 'event=/auth triggered')
        ) 
Example #5
Source File: flask.py    From keycloak-client with GNU General Public License v3.0 6 votes vote down vote up
def __call__(self, environ: Dict, start_response: Callable) -> Callable:
        response = None
        request = Request(environ)
        session = self.session_interface.open_session(  # type: ignore
            self.proxy_app, request
        )

        # callback request
        if request.base_url == self.callback_url:
            response = self.callback(session, request)
            return self._response(environ, start_response, session, response)

        # logout request
        elif request.path == self.logout_uri:
            self.logout(session)
            return self.app(environ, start_response)

        # unauthorized request
        elif "user" not in session:
            response = self.login(session)
            return self._response(environ, start_response, session, response)

        # authorized request
        else:
            return self.app(environ, start_response) 
Example #6
Source File: flask.py    From keycloak-client with GNU General Public License v3.0 6 votes vote down vote up
def callback(self, session: Dict, request: Request) -> Response:
        """ Authentication callback handler """

        # validate state
        state = request.args.get("state", "unknown")
        _state = session.pop("state", None)
        if state != _state:
            return Response("Invalid state", status=403)

        # fetch user tokens
        code: str = request.args.get("code", "unknown")
        tokens = self.kc.callback(code)
        session["tokens"] = json.dumps(tokens)

        # fetch user info
        access_token = tokens["access_token"]
        user = self.kc.fetch_userinfo(access_token)
        session["user"] = json.dumps(user)

        return redirect(self.redirect_uri) 
Example #7
Source File: service.py    From BentoML with Apache License 2.0 6 votes vote down vote up
def __init__(
        self, service, name, doc, handler, func, mb_max_latency, mb_max_batch_size
    ):
        """
        :param service: ref to service containing this API
        :param name: API name
        :param handler: A InputAdapter that transforms HTTP Request and/or
            CLI options into parameters for API func
        :param func: API func contains the actual API callback, this is
            typically the 'predict' method on a model
        :param mb_max_latency: The latency goal of your service in milliseconds.
            Default: 300.
        :param mb_max_batch_size: The maximum size of any batch. This parameter
            governs the throughput/latency tradeoff, and also avoids having
            batches that are so large they exceed some resource constraint (e.g.
            GPU memory to hold a batch's data). Default: 1000.
        """
        self._service = service
        self._name = name
        self._doc = doc
        self._handler = handler
        self._func = func
        self._wrapped_func = None
        self.mb_max_latency = mb_max_latency
        self.mb_max_batch_size = mb_max_batch_size 
Example #8
Source File: test_api_lib_policy.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_34_application_tokentype(self):
        builder = EnvironBuilder(method='POST',
                                 data={'user': "cornelius"},
                                 headers={})
        env = builder.get_environ()
        # Set the remote address so that we can filter for it
        env["REMOTE_ADDR"] = "10.0.0.1"
        g.client_ip = env["REMOTE_ADDR"]
        req = Request(env)

        # Set a policy, that the application is allowed to specify tokentype
        set_policy(name="pol1",
                   scope=SCOPE.AUTHZ,
                   action=ACTION.APPLICATION_TOKENTYPE)
        g.policy_object = PolicyClass()

        # check for
        req.all_data = {"type": "tokentype"}
        req.User = User("cornelius", self.realm1)
        check_application_tokentype(req)
        # Check for the tokentype
        self.assertEqual(req.all_data.get("type"), "tokentype")

        # delete the policy, then the application is not allowed to specify the tokentype
        delete_policy("pol1")
        g.policy_object = PolicyClass()

        check_application_tokentype(req)
        # Check that the tokentype was removed
        self.assertEqual(req.all_data.get("type"), None) 
Example #9
Source File: test_api_lib_policy.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_01_check_undetermined_tokentype(self):
        # If there is a tokentype policy but the type can not be
        # determined, authentication fails.
        builder = EnvironBuilder(method='POST',
                                 data={'serial': "OATH123456"},
                                 headers={})
        env = builder.get_environ()
        # Set the remote address so that we can filter for it
        env["REMOTE_ADDR"] = "10.0.0.1"
        g.client_ip = env["REMOTE_ADDR"]
        req = Request(env)
        req.User = User()
        # The response contains the token type SPASS
        res = {"jsonrpc": "2.0",
               "result": {"status": True,
                          "value": True},
               "version": "privacyIDEA test",
               "id": 1,
               "detail": {"message": "matching 2 tokens",
                          "type": "undetermined"}}
        resp = jsonify(res)

        # Set a policy, that does not allow the tokentype
        set_policy(name="pol1",
                   scope=SCOPE.AUTHZ,
                   action="tokentype=hotp", client="10.0.0.0/8")
        g.policy_object = PolicyClass()

        # The token type can not be determined, so an exception
        #  is raised.
        self.assertRaises(PolicyError,
                          check_tokentype,
                          req, resp) 
Example #10
Source File: test_api_lib_policy.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_03_no_detail_on_success(self):
        builder = EnvironBuilder(method='POST',
                                 data={'serial': "HOTP123435"},
                                 headers={})
        env = builder.get_environ()
        # Set the remote address so that we can filter for it
        env["REMOTE_ADDR"] = "10.0.0.1"
        g.client_ip = env["REMOTE_ADDR"]
        req = Request(env)
        # The response contains the token type SPASS
        res = {"jsonrpc": "2.0",
               "result": {"status": True,
                          "value": True},
               "version": "privacyIDEA test",
               "id": 1,
               "detail": {"message": "matching 1 tokens",
                          "serial": "HOTP123456",
                          "type": "hotp"}}
        resp = jsonify(res)

        # Set a policy, that does not allow the detail on success
        set_policy(name="pol2",
                   scope=SCOPE.AUTHZ,
                   action="no_detail_on_success", client="10.0.0.0/8")
        g.policy_object = PolicyClass()

        new_response = no_detail_on_success(req, resp)
        jresult = new_response.json
        self.assertTrue("detail" not in jresult, jresult)
        delete_policy("pol2") 
Example #11
Source File: test_api_lib_policy.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_15_reset_password(self):
        builder = EnvironBuilder(method='POST',
                                 data={'user': "cornelius",
                                       "realm": self.realm1},
                                 headers={})
        env = builder.get_environ()
        # Set the remote address so that we can filter for it
        env["REMOTE_ADDR"] = "10.0.0.1"
        g.client_ip = env["REMOTE_ADDR"]
        req = Request(env)
        # Set a mangle policy to change the username
        # and only use the last 4 characters of the username
        set_policy(name="recover",
                   scope=SCOPE.USER,
                   action="{0!s}".format(ACTION.RESYNC))
        g.policy_object = PolicyClass()
        req.all_data = {"user": "cornelius", "realm": self.realm1}
        # There is a user policy without password reset, so an exception is
        # raised
        self.assertRaises(PolicyError, check_anonymous_user, req,
                          ACTION.PASSWORDRESET)

        # The password reset is allowed
        set_policy(name="recover",
                   scope=SCOPE.USER,
                   action="{0!s}".format(ACTION.PASSWORDRESET))
        g.policy_object = PolicyClass()
        r = check_anonymous_user(req, ACTION.PASSWORDRESET)
        self.assertEqual(r, True) 
Example #12
Source File: test_api_lib_policy.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_26_indexedsecret_force_set(self):

        # We send a fake push_wait, that is not in the policies
        builder = EnvironBuilder(method='POST',
                                 data={'user': "cornelius",
                                       'realm': self.realm1,
                                       'type': "indexedsecret"},
                                 headers={})
        env = builder.get_environ()
        # Set the remote address so that we can filter for it
        env["REMOTE_ADDR"] = "10.0.0.1"
        g.client_ip = env["REMOTE_ADDR"]
        req = Request(env)
        req.User = User("cornelius", self.realm1)
        g.logged_in_user = {"username": "cornelius",
                            "realm": self.realm1,
                            "role": ROLE.USER}
        req.all_data = {"type": "indexedsecret"}
        g.policy_object = PolicyClass()
        indexedsecret_force_attribute(req, None)
        # request.all_data is unchanged
        self.assertNotIn("otpkey", req.all_data)

        # Now we use the policy, to set the otpkey
        set_policy(name="Indexed", scope=SCOPE.USER,
                   action="indexedsecret_{0!s}=username".format(PIIXACTION.FORCE_ATTRIBUTE))
        req.all_data = {"type": "indexedsecret"}
        g.policy_object = PolicyClass()
        indexedsecret_force_attribute(req, None)
        # Now the request.all_data contains the otpkey from the user attributes.
        self.assertIn("otpkey", req.all_data)
        self.assertEqual("cornelius", req.all_data.get("otpkey"))

        delete_policy("Indexed") 
Example #13
Source File: test_api_lib_policy.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_24_push_wait_policy(self):

        # We send a fake push_wait, that is not in the policies
        builder = EnvironBuilder(method='POST',
                                 data={'user': "hans",
                                       'pass': "pin",
                                       'push_wait': "120"},
                                 headers={})
        env = builder.get_environ()
        # Set the remote address so that we can filter for it
        env["REMOTE_ADDR"] = "10.0.0.1"
        g.client_ip = env["REMOTE_ADDR"]
        req = Request(env)
        req.User = User()
        req.all_data = {"push_wait": "120"}
        g.policy_object = PolicyClass()
        pushtoken_wait(req, None)
        self.assertEqual(req.all_data.get(PUSH_ACTION.WAIT), False)

        # Now we use the policy, to set the push_wait seconds
        set_policy(name="push1", scope=SCOPE.AUTH, action="{0!s}=10".format(PUSH_ACTION.WAIT))
        req.all_data = {}
        g.policy_object = PolicyClass()
        pushtoken_wait(req, None)
        self.assertEqual(req.all_data.get(PUSH_ACTION.WAIT), 10)

        delete_policy("push1") 
Example #14
Source File: test_api_lib_policy.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_10_get_webui_settings(self):
        # Test admin_dashboard
        self.setUp_user_realms()

        # The request with an OTP value and a PIN of a user, who has not
        # token assigned
        builder = EnvironBuilder(method='POST',
                                 data={},
                                 headers={})
        env = builder.get_environ()
        env["REMOTE_ADDR"] = "192.168.0.1"
        g.client_ip = env["REMOTE_ADDR"]
        req = Request(env)
        req.all_data = {}

        res = {"jsonrpc": "2.0",
               "result": {"status": True,
                          "value": {"role": "admin",
                                    "username": "cornelius"}},
               "version": "privacyIDEA test",
               "id": 1}
        resp = jsonify(res)

        new_response = get_webui_settings(req, resp)
        jresult = new_response.json
        self.assertEqual(jresult.get("result").get("value").get(
            "admin_dashboard"), False)

        # Set a policy. Admin can see the dashboard
        set_policy(name="pol_dashboard",
                   scope=SCOPE.WEBUI,
                   action=ACTION.ADMIN_DASHBOARD)
        g.policy_object = PolicyClass()
        new_response = get_webui_settings(req, resp)
        jresult = new_response.json
        self.assertTrue(jresult.get("result").get("value").get(ACTION.ADMIN_DASHBOARD))

        delete_policy("pol_dashboard") 
Example #15
Source File: test_lib_eventhandler_usernotification.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_06_check_conditions_realm(self):
        uhandler = UserNotificationEventHandler()
        # check a locked token with maxfail = failcount
        builder = EnvironBuilder(method='POST',
                                 data={'user': "cornelius@realm1"},
                                 headers={})

        env = builder.get_environ()
        req = Request(env)
        req.all_data = {"user": "cornelius@realm1"}
        req.User = User("cornelius", "realm1")
        resp = Response()
        resp.data = """{"result": {"value": false}}"""
        r = uhandler.check_condition(
            {"g": {},
             "handler_def": {"conditions": {"realm": "realm2"}},
             "request": req,
             "response": resp
             }
        )
        # wrong realm
        self.assertEqual(r, False)

        # Check condition resolver
        r = uhandler.check_condition(
            {"g": {},
             "handler_def": {"conditions": {"resolver": "resolver1"}},
             "request": req,
             "response": resp
             }
        )
        self.assertTrue(r)
        r = uhandler.check_condition(
            {"g": {},
             "handler_def": {"conditions": {"resolver": "resolver2"}},
             "request": req,
             "response": resp
             }
        )
        self.assertFalse(r) 
Example #16
Source File: test_api_lib_policy.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_14_required_email(self):
        g.logged_in_user = {"username": "admin1",
                            "realm": "",
                            "role": "admin"}
        builder = EnvironBuilder(method='POST',
                                 data={'serial': "OATH123456"},
                                 headers={})
        env = builder.get_environ()
        # Set the remote address so that we can filter for it
        env["REMOTE_ADDR"] = "10.0.0.1"
        g.client_ip = env["REMOTE_ADDR"]
        req = Request(env)
        # Set a mangle policy to change the username
        # and only use the last 4 characters of the username
        set_policy(name="email1",
                   scope=SCOPE.REGISTER,
                   action="{0!s}=/.*@mydomain\..*".format(ACTION.REQUIREDEMAIL))
        g.policy_object = PolicyClass()
        # request, that matches the policy
        req.all_data = {"email": "user@mydomain.net"}
        # This emails is allowed
        r = required_email(req)
        self.assertTrue(r)

        # This email is not allowed
        req.all_data = {"email": "user@otherdomain.net"}
        # This emails is allowed
        self.assertRaises(RegistrationError, required_email, req)

        delete_policy("email1")
        g.policy_object = PolicyClass()
        # Without a policy, this email can register
        req.all_data = {"email": "user@otherdomain.net"}
        # This emails is allowed
        r = required_email(req)
        self.assertTrue(r) 
Example #17
Source File: test_lib_eventhandler_usernotification.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_07_locked_token_wrong_pin(self):
        tok = init_token({"serial": "lock2", "type": "spass",
                          "pin": "pin"}, user=User("cornelius", "realm1"))
        # lock it
        tok.set_failcount(10)

        uhandler = UserNotificationEventHandler()
        resp = Response()
        resp.data = """{"result": {"value": false}}"""
        builder = EnvironBuilder(method='POST')
        env = builder.get_environ()
        req = Request(env)
        req.all_data = {"user": "cornelius", "pass": "wrong"}
        req.User = User("cornelius", self.realm1)
        # check the do action.
        g = FakeFlaskG()
        audit_object = FakeAudit()
        audit_object.audit_data["serial"] = None
        g.audit_object = audit_object
        g.client_ip = "127.0.0.1"
        options = {"g": g,
                   "handler_def": {"conditions": {"token_locked": "True"},
                                   "options": {"emailconfig": "myserver"}},
                   "response": resp,
                   "request": req
                   }

        r = add_smtpserver(identifier="myserver", server="1.2.3.4", tls=False)
        self.assertTrue(r > 0)

        smtpmock.setdata(response={"recp@example.com": (200, "OK")},
                         support_tls=False)

        r = uhandler.check_condition(options)
        self.assertEqual(r, True)

        r = uhandler.do("sendmail", options=options)
        self.assertEqual(r, True) 
Example #18
Source File: oauth_models.py    From app with MIT License 5 votes vote down vote up
def get_response_types(request: flask.Request) -> Set[ResponseType]:
    response_type_strs = _split_arg(request.args.getlist("response_type"))

    return set([ResponseType(r) for r in response_type_strs if r]) 
Example #19
Source File: test_lib_eventhandler_usernotification.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_10_check_conditions_tokentype(self):
        uhandler = UserNotificationEventHandler()
        # check if tokenrealm is contained
        builder = EnvironBuilder(method='POST',
                                 data={'user': "cornelius@realm1"},
                                 headers={})

        tok = init_token({"serial": "oath1234", "type": "spass"},
                         user=User("cornelius", "realm1"))

        env = builder.get_environ()
        req = Request(env)
        req.all_data = {"user": "cornelius@realm1",
                        "serial": "oath1234"}
        req.User = User("cornelius", "realm1")
        resp = Response()
        resp.data = """{"result": {"value": true}}"""
        r = uhandler.check_condition(
            {"g": {},
             "handler_def": {"conditions": {"tokentype": "totp,spass,oath,"}},
             "request": req,
             "response": resp
             }
        )
        # Serial matches the regexp
        self.assertEqual(r, True) 
Example #20
Source File: test_lib_eventhandler_usernotification.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_16_check_conditions_user_num_tokens(self):
        # prepare
        user = User("cornelius", "realm1")
        remove_token(user=user)
        uhandler = UserNotificationEventHandler()
        builder = EnvironBuilder(method='POST',
                                 data={'user': "cornelius@realm1"},
                                 headers={})

        tok = init_token({"serial": "oath1234", "type": "spass"},
                         user=user)

        env = builder.get_environ()
        req = Request(env)
        req.all_data = {"user": "cornelius@realm1",
                        "serial": "oath1234"}
        req.User = User("cornelius", "realm1")
        resp = Response()
        resp.data = """{"result": {"value": true}}"""
        # Do checking
        r = uhandler.check_condition(
            {"g": {},
             "handler_def": {"conditions": {CONDITION.USER_TOKEN_NUMBER: "1"}},
             "request": req,
             "response": resp
             }
        )
        # The user has one token
        self.assertEqual(r, True)

        r = uhandler.check_condition(
            {"g": {},
             "handler_def": {"conditions": {CONDITION.USER_TOKEN_NUMBER: "2"}},
             "request": req,
             "response": resp
             }
        )
        # The user has not two tokens!
        self.assertEqual(r, False)

        remove_token("oath1234") 
Example #21
Source File: test_lib_eventhandler_logging.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_03_loggingevent_parameter(self, capture):
        # simple logging event with user defined values
        self.setUp_user_realms()
        g = FakeFlaskG()
        g.audit_object = FakeAudit()
        env = EnvironBuilder(method='POST', headers={}, path='/auth').get_environ()
        req = Request(env)
        req.all_data = {}
        req.User = User("cornelius", self.realm1)
        resp = Response(response="""{"result": {"value": true}}""")
        options = {
            "g": g,
            "request": req,
            "response": resp,
            "handler_def": {
                'options': {
                    'name': 'eventlogger-privacyidea',
                    'level': 'WARN',
                    'message': 'Hello {username}!'
                }
            }
        }
        log_handler = LoggingEventHandler()
        res = log_handler.do("logging", options=options)
        self.assertTrue(res)
        capture.check_present(
            ('eventlogger-privacyidea', 'WARNING', 'Hello cornelius!')
        ) 
Example #22
Source File: test_lib_eventhandler_logging.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_04_loggingevent_broken_parameter(self, capture):
        # simple logging event with faulty parameters
        self.setUp_user_realms()
        g = FakeFlaskG()
        g.audit_object = FakeAudit()
        env = EnvironBuilder(method='POST', headers={}, path='/auth').get_environ()
        req = Request(env)
        req.all_data = {}
        req.User = User("cornelius", self.realm1)
        resp = Response(response="""{"result": {"value": true}}""")
        options = {
            "g": g,
            "request": req,
            "response": resp,
            "handler_def": {
                'options': {
                    'name': None,
                    'level': 'some_level',
                    'message': None
                }
            }
        }
        log_handler = LoggingEventHandler()
        res = log_handler.do("logging", options=options)
        self.assertTrue(res)
        capture.check_present(
            ('root', 'INFO', 'event=/auth triggered')
        ) 
Example #23
Source File: test_lib_events.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_02_check_conditions_only_one_token_no_serial(self):
        # In case there is no token serial in the request (like in a failed
        # auth request of a user with no token) we check if the user has only
        #  one token then this token is used in the conditions

        # prepare
        # setup realms
        self.setUp_user_realms()
        serial = "pw01"
        user = User("cornelius", "realm1")
        remove_token(user=user)
        tok = init_token({"serial": serial,
                          "type": "pw", "otppin": "test", "otpkey": "secret"},
                         user=user)
        self.assertEqual(tok.type, "pw")

        uhandler = BaseEventHandler()
        builder = EnvironBuilder(method='POST',
                                 data={'user': "cornelius@realm1",
                                       "pass": "wrongvalue"},
                                 headers={})
        env = builder.get_environ()
        req = Request(env)
        # This is a kind of authentication request
        req.all_data = {"user": "cornelius@realm1",
                        "pass": "wrongvalue"}
        req.User = User("cornelius", "realm1")
        resp = Response()
        resp.data = """{"result": {"value": false}}"""
        # Do checking
        r = uhandler.check_condition(
            {"g": {},
             "handler_def": {"conditions": {CONDITION.TOKENTYPE: "pw"}},
             "request": req,
             "response": resp
             }
        )
        # The only token of the user is of type "pw".
        self.assertEqual(r, True)

        remove_token(serial) 
Example #24
Source File: legacy_json_input.py    From BentoML with Apache License 2.0 5 votes vote down vote up
def handle_request(self, request: flask.Request, func):
        if request.content_type.lower() == "application/json":
            parsed_json = json.loads(request.get_data(as_text=True))
        else:
            raise BadInput(
                "Request content-type must be 'application/json' for this "
                "BentoService API lambda endpoint"
            )

        result = func(parsed_json)
        return self.output_adapter.to_response(result, request) 
Example #25
Source File: legacy_json_input.py    From BentoML with Apache License 2.0 5 votes vote down vote up
def handle_aws_lambda_event(self, event, func):
        if event["headers"]["Content-Type"] == "application/json":
            parsed_json = json.loads(event["body"])
        else:
            raise BadInput(
                "Request content-type must be 'application/json' for this "
                "BentoService API lambda endpoint"
            )

        result = func(parsed_json)
        return self.output_adapter.to_aws_lambda_event(result, event) 
Example #26
Source File: json_input.py    From BentoML with Apache License 2.0 5 votes vote down vote up
def handle_request(self, request: flask.Request, func):
        if request.content_type != "application/json":
            raise BadInput(
                "Request content-type must be 'application/json' for this "
                "BentoService API"
            )
        resps = self.handle_batch_request(
            [SimpleRequest.from_flask_request(request)], func
        )
        return resps[0].to_flask_response() 
Example #27
Source File: json_input.py    From BentoML with Apache License 2.0 5 votes vote down vote up
def handle_aws_lambda_event(self, event, func):
        if event["headers"]["Content-Type"] == "application/json":
            parsed_json = json.loads(event["body"])
        else:
            raise BadInput(
                "Request content-type must be 'application/json' for this "
                "BentoService API lambda endpoint"
            )

        result = func([parsed_json])[0]
        return self.output_adapter.to_aws_lambda_event(result, event) 
Example #28
Source File: instruments.py    From BentoML with Apache License 2.0 5 votes vote down vote up
def __call__(self, environ, start_response):
        req = Request(environ)
        endpoint = req.path
        start_time = default_timer()

        def start_response_wrapper(status, headers):
            ret = start_response(status, headers)
            status_code = int(status.split()[0])

            # instrument request total count
            self.metrics_request_total.labels(
                endpoint=endpoint,
                service_version=self.bento_service.version,
                http_response_code=status_code,
            ).inc()

            # instrument request duration
            total_time = max(default_timer() - start_time, 0)
            self.metrics_request_duration.labels(
                endpoint=endpoint,
                service_version=self.bento_service.version,
                http_response_code=status_code,
            ).observe(total_time)

            return ret

        with self.metrics_request_in_progress.labels(
            endpoint=endpoint, service_version=self.bento_service.version
        ).track_inprogress():
            return self.app(environ, start_response_wrapper) 
Example #29
Source File: service.py    From BentoML with Apache License 2.0 5 votes vote down vote up
def handle_request(self, request: flask.Request):
        return self.handler.handle_request(request, self.func) 
Example #30
Source File: service.py    From BentoML with Apache License 2.0 5 votes vote down vote up
def handle_batch_request(self, request: flask.Request):
        requests = DataLoader.split_requests(request.get_data())
        with trace(
            ZIPKIN_API_URL,
            service_name=self.__class__.__name__,
            span_name=f"call `{self.handler.__class__.__name__}`",
        ):
            responses = self.handler.handle_batch_request(requests, self.func)
        return DataLoader.merge_responses(responses)