Python sanic.exceptions.ServerError() Examples

The following are 30 code examples of sanic.exceptions.ServerError(). 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 sanic.exceptions , or try the search function .
Example #1
Source File: oauth2.py    From aiogoogle with MIT License 6 votes vote down vote up
def callback(request):
    if request.args.get("error"):
        error = {
            "error": request.args.get("error"),
            "error_description": request.args.get("error_description"),
        }
        return response.json(error)
    elif request.args.get("code"):
        returned_state = request.args["state"][0]
        # Check state
        if returned_state != state:
            raise ServerError("NO")
        # Step D & E (D send grant code, E receive token info)
        full_user_creds = await aiogoogle.oauth2.build_user_creds(
            grant=request.args.get("code"), client_creds=CLIENT_CREDS
        )
        return response.json(full_user_creds)
    else:
        # Should either receive a code or an error
        return response.text("Something's probably wrong with your callback") 
Example #2
Source File: openid_connect.py    From aiogoogle with MIT License 5 votes vote down vote up
def callback(request):
    if request.args.get("error"):
        error = {
            "error": request.args.get("error"),
            "error_description": request.args.get("error_description"),
        }
        return response.json(error)
    elif request.args.get("code"):
        returned_state = request.args["state"][0]
        # Check state
        if returned_state != state:
            raise ServerError("NO")
        # Step D & E (D send grant code, E receive token info)
        full_user_creds = await aiogoogle.openid_connect.build_user_creds(
            grant=request.args.get("code"),
            client_creds=CLIENT_CREDS,
            nonce=nonce,
            verify=False,
        )
        full_user_info = await aiogoogle.openid_connect.get_user_info(full_user_creds)
        return response.text(
            f"full_user_creds: {pprint.pformat(full_user_creds)}\n\nfull_user_info: {pprint.pformat(full_user_info)}"
        )
    else:
        # Should either receive a code or an error
        return response.text("Something's probably wrong with your callback") 
Example #3
Source File: mweixin.py    From momo with Apache License 2.0 5 votes vote down vote up
def _get_args(self, request):
        params = request.raw_args
        if not params:
            raise ServerError("invalid params", status_code=400)
        args = {
            'mp_token': Config.WEIXINMP_TOKEN,
            'signature': params.get('signature'),
            'timestamp': params.get('timestamp'),
            'echostr': params.get('echostr'),
            'nonce': params.get('nonce'),
        }
        return args 
Example #4
Source File: try_everything.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def exception(request):
    raise ServerError("It's dead jim") 
Example #5
Source File: test_exceptions_handler.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def handler_2(request):
    raise ServerError("OK") 
Example #6
Source File: varied_server.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def exception(request):
    raise ServerError("yep") 
Example #7
Source File: varied_server.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def test(request):
    raise ServerError("asunk") 
Example #8
Source File: test_requests.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def test_invalid_response():
    app = Sanic('test_invalid_response')

    @app.exception(ServerError)
    def handler_exception(request, exception):
        return text('Internal Server Error.', 500)

    @app.route('/')
    async def handler(request):
        return 'This should fail'

    request, response = sanic_endpoint_test(app)
    assert response.status == 500
    assert response.text == "Internal Server Error." 
Example #9
Source File: test_blueprints.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def test_bp_exception_handler():
    app = Sanic('test_middleware')
    blueprint = Blueprint('test_middleware')

    @blueprint.route('/1')
    def handler_1(request):
        raise InvalidUsage("OK")

    @blueprint.route('/2')
    def handler_2(request):
        raise ServerError("OK")

    @blueprint.route('/3')
    def handler_3(request):
        raise NotFound("OK")

    @blueprint.exception(NotFound, ServerError)
    def handler_exception(request, exception):
        return text("OK")

    app.blueprint(blueprint)

    request, response = sanic_endpoint_test(app, uri='/1')
    assert response.status == 400


    request, response = sanic_endpoint_test(app, uri='/2')
    assert response.status == 200
    assert response.text == 'OK'

    request, response = sanic_endpoint_test(app, uri='/3')
    assert response.status == 200 
Example #10
Source File: openid_connect.py    From aiogoogle with MIT License 5 votes vote down vote up
def authorize(request):
    if aiogoogle.openid_connect.is_ready(CLIENT_CREDS):
        uri = aiogoogle.openid_connect.authorization_url(
            client_creds=CLIENT_CREDS,
            state=state,
            nonce=nonce,
            access_type="offline",
            include_granted_scopes=True,
            login_hint=EMAIL,
            prompt="select_account",
        )
        # Step A
        return response.redirect(uri)
    else:
        raise ServerError("Client doesn't have enough info for Oauth2")


# ----------------------------------------------#
#                                              #
# **Step B (Check OAuth2 figure above)**       #
#                                              #
# ----------------------------------------------#
# NOTE:                                        #
#  you should now be authorizing your app @    #
#   https://accounts.google.com/o/oauth2/      #
# ----------------------------------------------#

# ----------------------------------------------#
#                                              #
# **Step C, D & E (Check OAuth2 figure above)**#
#                                              #
# ----------------------------------------------#

# Step C
# Google should redirect current_user to
# this endpoint with a grant code 
Example #11
Source File: test_exception_interception.py    From sanic-cors with MIT License 5 votes vote down vote up
def test_acl_exception_with_error_handler(self):
        '''
            If a 500 handler is setup by the user, responses should have
            CORS matching rules applied, regardless of whether or not
            intercept_exceptions is enbaled.
        '''
        return_string = "Simple error handler"

        @self.app.exception(ServerError, NotFound, Exception)
        # Note, async error handlers don't work in Sanic yet.
        # async def catch_all_handler(request, exception):
        def catch_all_handler(request, exception):
            '''
                This error handler catches 404s and 500s and returns
                status 200 no matter what. It is not a good handler.
            '''
            return text(return_string, 200)

        acl_paths = [
            '/test_acl_abort_404',
            '/test_acl_abort_500'
        ]
        no_acl_paths = [
            '/test_no_acl_abort_404',
            '/test_no_acl_abort_500',
            '/test_no_acl_uncaught_exception_500',
            '/test_acl_uncaught_exception_500'
        ]
        def get_with_origins(path):
            return self.get(path, origin='www.example.com')

        for resp in map(get_with_origins, acl_paths):
            self.assertEqual(resp.status, 200)
            self.assertTrue(ACL_ORIGIN in resp.headers)

        for resp in map(get_with_origins, no_acl_paths):
            self.assertEqual(resp.status, 200)
            self.assertFalse(ACL_ORIGIN in resp.headers) 
Example #12
Source File: oauth2.py    From aiogoogle with MIT License 5 votes vote down vote up
def authorize(request):
    if aiogoogle.oauth2.is_ready(CLIENT_CREDS):
        uri = aiogoogle.oauth2.authorization_url(
            client_creds=CLIENT_CREDS,
            state=state,
            access_type="offline",
            include_granted_scopes=True,
            login_hint=EMAIL,
            prompt="select_account",
        )
        # Step A
        return response.redirect(uri)
    else:
        raise ServerError("Client doesn't have enough info for Oauth2")


# ----------------------------------------------#
#                                              #
# **Step B (Check OAuth2 figure above)**       #
#                                              #
# ----------------------------------------------#
# NOTE:                                        #
#  you should now be authorizing your app @    #
#   https://accounts.google.com/o/oauth2/      #
# ----------------------------------------------#

# ----------------------------------------------#
#                                              #
# **Step C, D & E (Check OAuth2 figure above)**#
#                                              #
# ----------------------------------------------#

# Step C
# Google should redirect current_user to
# this endpoint with a grant code 
Example #13
Source File: _openid_connect_dev_test.py    From aiogoogle with MIT License 5 votes vote down vote up
def authorize(request):
    if aiogoogle.openid_connect.is_ready(CLIENT_CREDS):
        uri = aiogoogle.openid_connect.authorization_url(
            client_creds=CLIENT_CREDS,
            state=state,
            nonce=nonce,
            access_type="offline",
            include_granted_scopes=True,
            login_hint=EMAIL,
            prompt="select_account",
        )
        # Step A
        return response.redirect(uri)
    else:
        raise ServerError("Client doesn't have enough info for Oauth2") 
Example #14
Source File: _oauth2_flow_dev_test.py    From aiogoogle with MIT License 5 votes vote down vote up
def authorize(request):
    if aiogoogle.oauth2.is_ready(CLIENT_CREDS):
        uri = aiogoogle.oauth2.authorization_url(
            client_creds=CLIENT_CREDS,
            state=state,
            access_type="offline",
            include_granted_scopes=True,
            login_hint=EMAIL,
            prompt="select_account",
        )
        return response.redirect(uri)
    else:
        raise ServerError("Client doesn't have enough info for Oauth2") 
Example #15
Source File: _oauth2_flow_dev_test.py    From aiogoogle with MIT License 5 votes vote down vote up
def callback(request):
    if request.args.get("error"):
        return response.text("whoops!", 401)
    elif request.args.get("code"):
        returned_state = request.args["state"][0]
        if returned_state != state:
            raise ServerError("NO")
        full_user_creds = await aiogoogle.oauth2.build_user_creds(
            grant=request.args.get("code"), client_creds=CLIENT_CREDS
        )
        await refresh(full_user_creds)
        expire_creds_then_refresh(full_user_creds)
        await revoke(full_user_creds)
        return response.text("passed") 
Example #16
Source File: test_plugin_exception.py    From sanicpluginsframework with MIT License 5 votes vote down vote up
def handler_2(request):
    raise ServerError("OK") 
Example #17
Source File: test_plugin_exception.py    From sanicpluginsframework with MIT License 5 votes vote down vote up
def handler_5(request):
    class CustomServerError(ServerError):
        pass
    raise CustomServerError('Custom server error') 
Example #18
Source File: test_plugin_exception.py    From sanicpluginsframework with MIT License 5 votes vote down vote up
def test_exception_handler_lookup():
    class CustomError(Exception):
        pass

    class CustomServerError(ServerError):
        pass

    def custom_error_handler():
        pass

    def server_error_handler():
        pass

    def import_error_handler():
        pass

    try:
        ModuleNotFoundError
    except:
        class ModuleNotFoundError(ImportError):
            pass

    handler = ErrorHandler()
    handler.add(ImportError, import_error_handler)
    handler.add(CustomError, custom_error_handler)
    handler.add(ServerError, server_error_handler)

    assert handler.lookup(ImportError()) == import_error_handler
    assert handler.lookup(ModuleNotFoundError()) == import_error_handler
    assert handler.lookup(CustomError()) == custom_error_handler
    assert handler.lookup(ServerError('Error')) == server_error_handler
    assert handler.lookup(CustomServerError('Error')) == server_error_handler

    # once again to ensure there is no caching bug
    assert handler.lookup(ImportError()) == import_error_handler
    assert handler.lookup(ModuleNotFoundError()) == import_error_handler
    assert handler.lookup(CustomError()) == custom_error_handler
    assert handler.lookup(ServerError('Error')) == server_error_handler
    assert handler.lookup(CustomServerError('Error')) == server_error_handler 
Example #19
Source File: example_attrs_model.py    From sanic-transmute with MIT License 5 votes vote down vote up
def handle_exception(request) -> User:
    """
    API Description: Handle exception. This will show in the swagger page (localhost:8000/api/v1/).
    """
    raise ServerError("Something bad happened", status_code=500) 
Example #20
Source File: test_exceptions_handler.py    From sanic with MIT License 5 votes vote down vote up
def handler_2(request):
    raise ServerError("OK") 
Example #21
Source File: test_exceptions_handler.py    From sanic with MIT License 5 votes vote down vote up
def handler_5(request):
    class CustomServerError(ServerError):
        pass

    raise CustomServerError("Custom server error") 
Example #22
Source File: test_exceptions_handler.py    From sanic with MIT License 5 votes vote down vote up
def test_exception_handler_lookup():
    class CustomError(Exception):
        pass

    class CustomServerError(ServerError):
        pass

    def custom_error_handler():
        pass

    def server_error_handler():
        pass

    def import_error_handler():
        pass

    try:
        ModuleNotFoundError
    except Exception:

        class ModuleNotFoundError(ImportError):
            pass

    handler = ErrorHandler()
    handler.add(ImportError, import_error_handler)
    handler.add(CustomError, custom_error_handler)
    handler.add(ServerError, server_error_handler)

    assert handler.lookup(ImportError()) == import_error_handler
    assert handler.lookup(ModuleNotFoundError()) == import_error_handler
    assert handler.lookup(CustomError()) == custom_error_handler
    assert handler.lookup(ServerError("Error")) == server_error_handler
    assert handler.lookup(CustomServerError("Error")) == server_error_handler

    # once again to ensure there is no caching bug
    assert handler.lookup(ImportError()) == import_error_handler
    assert handler.lookup(ModuleNotFoundError()) == import_error_handler
    assert handler.lookup(CustomError()) == custom_error_handler
    assert handler.lookup(ServerError("Error")) == server_error_handler
    assert handler.lookup(CustomServerError("Error")) == server_error_handler 
Example #23
Source File: varied_server.py    From sanic with MIT License 5 votes vote down vote up
def exception(request):
    raise ServerError("yep") 
Example #24
Source File: test_requests.py    From sanic with MIT License 5 votes vote down vote up
def test_invalid_response(app):
    @app.exception(ServerError)
    def handler_exception(request, exception):
        return text("Internal Server Error.", 500)

    @app.route("/")
    async def handler(request):
        return "This should fail"

    request, response = app.test_client.get("/")
    assert response.status == 500
    assert response.text == "Internal Server Error." 
Example #25
Source File: test_requests.py    From sanic with MIT License 5 votes vote down vote up
def test_invalid_response_asgi(app):
    @app.exception(ServerError)
    def handler_exception(request, exception):
        return text("Internal Server Error.", 500)

    @app.route("/")
    async def handler(request):
        return "This should fail"

    request, response = await app.asgi_client.get("/")
    assert response.status == 500
    assert response.text == "Internal Server Error." 
Example #26
Source File: test_blueprints.py    From sanic with MIT License 5 votes vote down vote up
def test_bp_exception_handler(app):
    blueprint = Blueprint("test_middleware")

    @blueprint.route("/1")
    def handler_1(request):
        raise InvalidUsage("OK")

    @blueprint.route("/2")
    def handler_2(request):
        raise ServerError("OK")

    @blueprint.route("/3")
    def handler_3(request):
        raise NotFound("OK")

    @blueprint.exception(NotFound, ServerError)
    def handler_exception(request, exception):
        return text("OK")

    app.blueprint(blueprint)

    request, response = app.test_client.get("/1")
    assert response.status == 400

    request, response = app.test_client.get("/2")
    assert response.status == 200
    assert response.text == "OK"

    request, response = app.test_client.get("/3")
    assert response.status == 200 
Example #27
Source File: mwechat.py    From rasa_wechat with Apache License 2.0 5 votes vote down vote up
def _get_args(self, request):
        params = request.raw_args
        if not params:
            raise ServerError("invalid params", status_code=400)
        args = {
            'mp_token': Config.WEIXINMP_TOKEN,
            'signature': params.get('signature'),
            'timestamp': params.get('timestamp'),
            'echostr': params.get('echostr'),
            'nonce': params.get('nonce'),
        }
        return args 
Example #28
Source File: try_everything.py    From sanic with MIT License 5 votes vote down vote up
def exception(request):
    raise ServerError("It's dead jim") 
Example #29
Source File: example_schematics_model.py    From sanic-transmute with MIT License 5 votes vote down vote up
def handle_exception(request) -> User:
    """
    API Description: Handle exception. This will show in the swagger page (localhost:8000/api/v1/).
    """
    raise ServerError("Something bad happened", status_code=500) 
Example #30
Source File: validators.py    From Metis with Apache License 2.0 5 votes vote down vote up
def request_validate(view):

    @wraps(view)
    def wrapper(*args, **kwargs):
        request = args[1]
        endpoint = _path_to_endpoint(request.uri_template)
        current.request = request
        # scope
        if (endpoint, request.method) in scopes and not set(
                scopes[(endpoint, request.method)]).issubset(set(security.scopes)):
            raise ServerError('403', status_code=403)
        # data
        method = request.method
        if method == 'HEAD':
            method = 'GET'
        locations = validators.get((endpoint, method), {})
        for location, schema in locations.items():
            value = getattr(request, location, MultiDict())
            if value is None:
                value = MultiDict()
            validator = SanicValidatorAdaptor(schema)
            result, errors = validator.validate(value)
            if errors:
                raise ServerError('Unprocessable Entity', status_code=422)
        return view(*args, **kwargs)

    return wrapper