Python sanic.Sanic() Examples

The following are 30 code examples of sanic.Sanic(). 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 , or try the search function .
Example #1
Source File: test_initialize.py    From sanic-jwt with MIT License 6 votes vote down vote up
def test_initialize_app_and_bp():

    app = Sanic("sanic-jwt-test")
    bp = Blueprint("bp", url_prefix="/bpapi")
    Initialize(instance=bp, app=app, authenticate=lambda: True)

    app.blueprint(bp)


# print("app", app.router.routes_all.keys())
# print("bp", [x.uri for x in bp.routes])


# Result:

# assert False 
Example #2
Source File: test_authentication_custom.py    From sanic-jwt with MIT License 6 votes vote down vote up
def app2():
    class MyAuthentication(Authentication):
        async def store_refresh_token(self, *args, **kwargs):
            return

        async def retrieve_refresh_token(self, *args, **kwargs):
            return {}

        async def authenticate(self, *args, **kwargs):
            return "foobar"

        async def retrieve_user(self, *args, **kwargs):
            return {}

        def extract_payload(self, request, verify=True, *args, **kwargs):
            return {}

    app = Sanic("sanic-jwt-test")
    Initialize(
        app, authentication_class=MyAuthentication, refresh_token_enabled=True
    )

    yield app 
Example #3
Source File: test_logging.py    From sanic with MIT License 6 votes vote down vote up
def test_logging_pass_customer_logconfig():
    # reset_logging()

    modified_config = LOGGING_CONFIG_DEFAULTS
    modified_config["formatters"]["generic"][
        "format"
    ] = "%(asctime)s - (%(name)s)[%(levelname)s]: %(message)s"
    modified_config["formatters"]["access"][
        "format"
    ] = "%(asctime)s - (%(name)s)[%(levelname)s]: %(message)s"

    app = Sanic("test_logging", log_config=modified_config)

    for fmt in [h.formatter for h in logging.getLogger("sanic.root").handlers]:
        assert fmt._fmt == modified_config["formatters"]["generic"]["format"]

    for fmt in [
        h.formatter for h in logging.getLogger("sanic.error").handlers
    ]:
        assert fmt._fmt == modified_config["formatters"]["generic"]["format"]

    for fmt in [
        h.formatter for h in logging.getLogger("sanic.access").handlers
    ]:
        assert fmt._fmt == modified_config["formatters"]["access"]["format"] 
Example #4
Source File: test_logging.py    From sanic with MIT License 6 votes vote down vote up
def test_logging_defaults():
    # reset_logging()
    app = Sanic("test_logging")

    for fmt in [h.formatter for h in logging.getLogger("sanic.root").handlers]:
        assert (
            fmt._fmt
            == LOGGING_CONFIG_DEFAULTS["formatters"]["generic"]["format"]
        )

    for fmt in [
        h.formatter for h in logging.getLogger("sanic.error").handlers
    ]:
        assert (
            fmt._fmt
            == LOGGING_CONFIG_DEFAULTS["formatters"]["generic"]["format"]
        )

    for fmt in [
        h.formatter for h in logging.getLogger("sanic.access").handlers
    ]:
        assert (
            fmt._fmt
            == LOGGING_CONFIG_DEFAULTS["formatters"]["access"]["format"]
        ) 
Example #5
Source File: test_authentication_custom.py    From sanic-jwt with MIT License 6 votes vote down vote up
def app1():
    class MyAuthentication(Authentication):
        async def store_refresh_token(self, *args, **kwargs):
            return

        async def retrieve_refresh_token(self, *args, **kwargs):
            return

        async def authenticate(self, *args, **kwargs):
            return

        async def retrieve_user(self, *args, **kwargs):
            return

        def extract_payload(self, request, verify=True, *args, **kwargs):
            return

    app = Sanic("sanic-jwt-test")
    Initialize(
        app, authentication_class=MyAuthentication, refresh_token_enabled=True
    )

    yield app 
Example #6
Source File: test_exceptions.py    From sanic with MIT License 6 votes vote down vote up
def test_unauthorized_exception(exception_app):
    """Test the built-in Unauthorized exception"""
    request, response = exception_app.test_client.get("/401")
    assert response.status == 401

    request, response = exception_app.test_client.get("/401/basic")
    assert response.status == 401
    assert response.headers.get("WWW-Authenticate") is not None
    assert response.headers.get("WWW-Authenticate") == 'Basic realm="Sanic"'

    request, response = exception_app.test_client.get("/401/digest")
    assert response.status == 401

    auth_header = response.headers.get("WWW-Authenticate")
    assert auth_header is not None
    assert auth_header.startswith("Digest")
    assert 'qop="auth, auth-int"' in auth_header
    assert 'algorithm="MD5"' in auth_header
    assert 'nonce="abcdef"' in auth_header
    assert 'opaque="zyxwvu"' in auth_header

    request, response = exception_app.test_client.get("/401/bearer")
    assert response.status == 401
    assert response.headers.get("WWW-Authenticate") == "Bearer" 
Example #7
Source File: conftest.py    From sanic-jwt with MIT License 6 votes vote down vote up
def app_with_custom_claims(authenticate):
    class User2Claim(Claim):
        key = "username"

        def setup(self, payload, user):
            return user.username

        def verify(self, value):
            return value == "user2"

    custom_claims = [User2Claim]

    sanic_app = Sanic("sanic-jwt-test")
    sanic_jwt = Initialize(
        sanic_app, authenticate=authenticate, custom_claims=custom_claims
    )

    @sanic_app.route("/protected")
    @protected()
    async def protected_request(request):
        return json({"protected": True})

    yield (sanic_app, sanic_jwt) 
Example #8
Source File: conftest.py    From sanic-jwt with MIT License 6 votes vote down vote up
def app_with_extra_verification(authenticate):
    def user2(payload):
        return payload.get("user_id") == 2

    extra_verifications = [user2]

    sanic_app = Sanic("sanic-jwt-test")
    sanic_jwt = Initialize(
        sanic_app,
        authenticate=authenticate,
        extra_verifications=extra_verifications,
    )

    @sanic_app.route("/protected")
    @protected()
    async def protected_request(request):
        return json({"protected": True})

    yield (sanic_app, sanic_jwt) 
Example #9
Source File: conftest.py    From sanic-jwt with MIT License 6 votes vote down vote up
def app_with_aud(username_table, authenticate):

    sanic_app = Sanic("sanic-jwt-test")
    sanic_jwt = Initialize(
        sanic_app, authenticate=authenticate, claim_aud="clientserver"
    )

    @sanic_app.route("/")
    async def helloworld(request):
        return json({"hello": "world"})

    @sanic_app.route("/protected")
    @protected()
    async def protected_request(request):
        return json({"protected": True})

    yield (sanic_app, sanic_jwt) 
Example #10
Source File: test_reloader.py    From sanic with MIT License 6 votes vote down vote up
def write_app(filename, **runargs):
    text = secrets.token_urlsafe()
    with open(filename, "w") as f:
        f.write(
            dedent(
                f"""\
            import os
            from sanic import Sanic

            app = Sanic(__name__)

            @app.listener("after_server_start")
            def complete(*args):
                print("complete", os.getpid(), {text!r})

            if __name__ == "__main__":
                app.run(**{runargs!r})
            """
            )
        )
    return text 
Example #11
Source File: conftest.py    From sanic-jwt with MIT License 6 votes vote down vote up
def app_with_iss(username_table, authenticate):

    sanic_app = Sanic("sanic-jwt-test")
    sanic_jwt = Initialize(
        sanic_app, authenticate=authenticate, claim_iss="issuingserver"
    )

    @sanic_app.route("/")
    async def helloworld(request):
        return json({"hello": "world"})

    @sanic_app.route("/protected")
    @protected()
    async def protected_request(request):
        return json({"protected": True})

    yield (sanic_app, sanic_jwt) 
Example #12
Source File: conftest.py    From sanic-jwt with MIT License 6 votes vote down vote up
def app_with_iat(username_table, authenticate):

    sanic_app = Sanic("sanic-jwt-test")
    sanic_jwt = Initialize(
        sanic_app, authenticate=authenticate, claim_iat=True
    )

    @sanic_app.route("/")
    async def helloworld(request):
        return json({"hello": "world"})

    @sanic_app.route("/protected")
    @protected()
    async def protected_request(request):
        return json({"protected": True})

    yield (sanic_app, sanic_jwt) 
Example #13
Source File: conftest.py    From sanic-jwt with MIT License 6 votes vote down vote up
def app_with_nbf(username_table, authenticate):

    sanic_app = Sanic("sanic-jwt-test")
    sanic_jwt = Initialize(
        sanic_app,
        authenticate=authenticate,
        claim_nbf=True,
        claim_nbf_delta=(60 * 5),
    )

    @sanic_app.route("/")
    async def helloworld(request):
        return json({"hello": "world"})

    @sanic_app.route("/protected")
    @protected()
    async def protected_request(request):
        return json({"protected": True})

    yield (sanic_app, sanic_jwt) 
Example #14
Source File: conftest.py    From sanic-jwt with MIT License 6 votes vote down vote up
def app_with_bp_setup_without_init(username_table, authenticate):
    sanic_app = Sanic("sanic-jwt-test")

    @sanic_app.route("/")
    async def helloworld(request):
        return json({"hello": "world"})

    @sanic_app.route("/protected")
    @protected()
    async def protected_request(request):
        return json({"protected": True})

    sanic_bp = Blueprint("bp", url_prefix="/bp")

    @sanic_bp.route("/")
    async def bp_helloworld(request):
        return json({"hello": "world"})

    @sanic_bp.route("/protected")
    @protected()
    async def bp_protected_request(request):
        return json({"protected": True})

    yield (sanic_app, sanic_bp) 
Example #15
Source File: test_unix_socket.py    From sanic with MIT License 6 votes vote down vote up
def test_unix_connection():
    app = Sanic(name=__name__)

    @app.get("/")
    def handler(request):
        return text(f"{request.conn_info.server}")

    @app.listener("after_server_start")
    async def client(app, loop):
        try:
            async with httpx.AsyncClient(uds=SOCKPATH) as client:
                r = await client.get("http://myhost.invalid/")
                assert r.status_code == 200
                assert r.text == os.path.abspath(SOCKPATH)
        finally:
            app.stop()

    app.run(host="myhost.invalid", unix=SOCKPATH) 
Example #16
Source File: conftest.py    From sanic-jwt with MIT License 6 votes vote down vote up
def app_with_url_prefix(username_table, authenticate):

    sanic_app = Sanic("sanic-jwt-test")
    sanic_jwt = Initialize(
        sanic_app, authenticate=authenticate, url_prefix="/somethingelse"
    )

    @sanic_app.route("/")
    async def helloworld(request):
        return json({"hello": "world"})

    @sanic_app.route("/protected")
    @protected()
    async def protected_request(request):
        return json({"protected": True})

    yield (sanic_app, sanic_jwt) 
Example #17
Source File: conftest.py    From sanic-jwt with MIT License 6 votes vote down vote up
def app_with_user_secrets(username_table, authenticate, retrieve_user_secret):

    sanic_app = Sanic("sanic-jwt-test")
    sanic_jwt = Initialize(
        sanic_app,
        authenticate=authenticate,
        user_secret_enabled=True,
        retrieve_user_secret=retrieve_user_secret,
    )

    @sanic_app.route("/protected")
    @protected()
    async def protected_request(request):
        return json({"protected": True})

    yield (sanic_app, sanic_jwt) 
Example #18
Source File: conftest.py    From sanic-jwt with MIT License 6 votes vote down vote up
def app_with_leeway(username_table, authenticate):

    sanic_app = Sanic("sanic-jwt-test")
    sanic_jwt = Initialize(
        sanic_app, authenticate=authenticate, leeway=(60 * 5)
    )

    @sanic_app.route("/")
    async def helloworld(request):
        return json({"hello": "world"})

    @sanic_app.route("/protected")
    @protected()
    async def protected_request(request):
        return json({"protected": True})

    yield (sanic_app, sanic_jwt) 
Example #19
Source File: test_endpoints_cookies.py    From sanic-jwt with MIT License 6 votes vote down vote up
def test_config_with_cookie_domain(users, authenticate):
    domain = "cookie.yum"
    sanic_app = Sanic("sanic-jwt-test")
    Initialize(
        sanic_app,
        authenticate=authenticate,
        cookie_set=True,
        cookie_domain=domain,
    )

    _, response = sanic_app.test_client.post(
        "/auth",
        json={"username": "user1", "password": "abcxyz"},
        raw_cookies=True,
    )

    cookie = response.raw_cookies.get("access_token")
    assert cookie.domain == domain 
Example #20
Source File: test_decorators.py    From sanic-jwt with MIT License 6 votes vote down vote up
def test_redirect_with_configured_url():
    sanic_app = Sanic("sanic-jwt-test")
    sanic_jwt = Initialize(
        sanic_app, auth_mode=False, login_redirect_url="/unprotected"
    )

    @sanic_app.route("/protected/static")
    @sanic_jwt.protected(redirect_on_fail=True)
    async def my_protected_static(request):
        return text("", status=200)

    @sanic_app.route("/unprotected")
    async def my_unprotected_goto(request):
        return text("unprotected content", status=200)

    _, response = sanic_app.test_client.get("/protected/static")

    assert response.status == 200 and response.text == "unprotected content" 
Example #21
Source File: test_initialize.py    From sanic-jwt with MIT License 5 votes vote down vote up
def test_initialize_class_on_multiple_blueprints():
    app = Sanic("sanic-jwt-test")
    bp1 = Blueprint("test1")
    app.blueprint(bp1)
    bp2 = Blueprint("test2")
    app.blueprint(bp2)

    sanicjwt1 = Initialize(bp1, app=app, authenticate=lambda: True)
    sanicjwt2 = Initialize(
        bp2, app=app, authenticate=lambda: True, access_token_name="token"
    )

    assert sanicjwt1.config.access_token_name() == "access_token"
    assert sanicjwt2.config.access_token_name() == "token" 
Example #22
Source File: test_initialize.py    From sanic-jwt with MIT License 5 votes vote down vote up
def test_invalid_configuration_object():
    class MyInvalidConfiguration:
        MY_CUSTOM_SETTING = "foo"

    app = Sanic("sanic-jwt-test")
    with pytest.raises(exceptions.InitializationFailure):
        Initialize(app, configuration_class=MyInvalidConfiguration) 
Example #23
Source File: test_initialize.py    From sanic-jwt with MIT License 5 votes vote down vote up
def test_initialize_class_on_blueprint_with_url_prefix_and_config():
    app = Sanic("sanic-jwt-test")
    bp = Blueprint("test", url_prefix="/test")
    app.blueprint(bp)

    init = Initialize(bp, app=app, authenticate=lambda: True, url_prefix="/a")

    assert init._get_url_prefix() == "/test/a" 
Example #24
Source File: test_initialize.py    From sanic-jwt with MIT License 5 votes vote down vote up
def test_initialize_with_custom_endpoint_not_subclassed():
    class SubclassHTTPMethodView(HTTPMethodView):
        async def options(self, request):
            return text("", status=204)

        async def get(self, request):
            return text("ok")

    app = Sanic("sanic-jwt-test")
    with pytest.raises(exceptions.InvalidClassViewsFormat):
        Initialize(
            app,
            authenticate=lambda: True,
            class_views=[("/subclass", SubclassHTTPMethodView)],
        ) 
Example #25
Source File: test_initialize.py    From sanic-jwt with MIT License 5 votes vote down vote up
def test_initialize_class_on_blueprint_with_url_prefix():
    app = Sanic("sanic-jwt-test")
    bp = Blueprint("test", url_prefix="/test")
    app.blueprint(bp)

    init = Initialize(bp, app=app, authenticate=lambda: True)

    assert init._get_url_prefix() == "/test/auth" 
Example #26
Source File: test_decorators.py    From sanic-jwt with MIT License 5 votes vote down vote up
def test_inject_user_with_auth_mode_off(app_with_retrieve_user):
    async def retrieve_user(request, payload, *args, **kwargs):
        return {"user_id": 123}

    microservice_app = Sanic("sanic-jwt-test")
    microservice_sanic_jwt = Initialize(
        microservice_app, auth_mode=False, retrieve_user=retrieve_user
    )

    @microservice_app.route("/protected/user")
    @microservice_sanic_jwt.inject_user()
    @microservice_sanic_jwt.protected()
    async def my_protected_user(request, user):
        return json({"user_id": user.get("user_id")})

    sanic_app, sanic_jwt = app_with_retrieve_user
    _, response = sanic_app.test_client.post(
        "/auth", json={"username": "user1", "password": "abcxyz"}
    )

    access_token = response.json.get(
        sanic_jwt.config.access_token_name(), None
    )

    _, response = microservice_app.test_client.get(
        "/protected/user",
        headers={"Authorization": "Bearer {}".format(access_token)},
    )

    assert response.status == 200
    assert response.json.get("user_id") == 123

    _, response = microservice_app.test_client.get("/protected/user")

    assert response.status == 401 
Example #27
Source File: test_endpoints_cookies.py    From sanic-jwt with MIT License 5 votes vote down vote up
def test_config_with_cookie_path(users, authenticate):
    path = "/auth"
    sanic_app = Sanic("sanic-jwt-test")
    Initialize(
        sanic_app, authenticate=authenticate, cookie_set=True, cookie_path=path
    )

    _, response = sanic_app.test_client.post(
        "/auth",
        json={"username": "user1", "password": "abcxyz"},
        raw_cookies=True,
    )

    cookie = response.raw_cookies.get("access_token")
    assert cookie.path == path 
Example #28
Source File: test_microservices.py    From sanic-jwt with MIT License 5 votes vote down vote up
def test_microservice_simple():
    microservice_app = Sanic("sanic-jwt-test")
    Initialize(microservice_app, auth_mode=False)

    _, response = microservice_app.test_client.post(
        "/auth", json={"username": "user1", "password": "abcxyz"}
    )

    assert response.status == 404 
Example #29
Source File: conftest.py    From sanic-jwt with MIT License 5 votes vote down vote up
def app(username_table, authenticate):

    sanic_app = Sanic("sanic-jwt-test")
    sanic_jwt = Initialize(sanic_app, authenticate=authenticate)

    @sanic_app.route("/")
    async def helloworld(request):
        return json({"hello": "world"})

    @sanic_app.route("/protected")
    @protected()
    async def protected_request(request):
        return json({"protected": True})

    @sanic_app.route("/options", methods=["OPTIONS"])
    @protected()
    async def protected_request_options(request):
        return text("", status=204)

    @sanic_app.route("/protected/<verify:int>")
    @protected()
    def protected_regression_verify(request, verify):
        """
        for regression test see
        https://github.com/ahopkins/sanic-jwt/issues/59#issuecomment-380034269
        """
        return json({"protected": True})

    yield (sanic_app, sanic_jwt) 
Example #30
Source File: conftest.py    From sanic-jwt with MIT License 5 votes vote down vote up
def app_with_refresh_token(username_table, authenticate):

    sanic_app = Sanic("sanic-jwt-test")
    sanic_jwt = Initialize(
        sanic_app,
        authenticate=authenticate,
        refresh_token_enabled=True,
        store_refresh_token=lambda user_id, refresh_token, request: True,
        retrieve_refresh_token=lambda user_id, request: True,
    )

    yield (sanic_app, sanic_jwt)