Example #1
0
def server(schema, host, port, app_dir):
    sys.path.insert(0, app_dir)

    try:
        schema_symbol = import_module_symbol(schema,
                                             default_symbol_name="schema")
    except (ImportError, AttributeError) as exc:
        message = str(exc)
        raise click.BadArgumentUsage(message)

    if not isinstance(schema_symbol, Schema):
        message = "The `schema` must be an instance of strawberry.Schema"
        raise click.BadArgumentUsage(message)

    reloader = hupper.start_reloader("strawberry.cli.run", verbose=False)
    schema_module = importlib.import_module(schema_symbol.__module__)
    reloader.watch_files([schema_module.__file__])

    app = Starlette(debug=True)
    app.add_middleware(CORSMiddleware,
                       allow_headers=["*"],
                       allow_origins=["*"],
                       allow_methods=["*"])

    graphql_app = GraphQL(schema_symbol, debug=True)

    paths = ["/", "/graphql"]
    for path in paths:
        app.add_route(path, graphql_app)
        app.add_websocket_route(path, graphql_app)

    print(f"Running strawberry on http://{host}:{port}/ 🍓")
    uvicorn.run(app, host=host, port=port, log_level="error")
Example #2
0
def server(module, host, port):
    sys.path.append(os.getcwd())

    reloader = hupper.start_reloader("strawberry.cli.run", verbose=False)

    schema_module = importlib.import_module(module)

    reloader.watch_files([schema_module.__file__])

    app = Starlette(debug=True)

    app.add_middleware(CORSMiddleware,
                       allow_headers=["*"],
                       allow_origins=["*"],
                       allow_methods=["*"])

    graphql_app = GraphQL(schema_module.schema, debug=True)

    paths = ["/", "/graphql"]

    for path in paths:
        app.add_route(path, graphql_app)
        app.add_websocket_route(path, graphql_app)

    print(f"Running strawberry on http://{host}:{port}/ 🍓")

    uvicorn.run(app, host=host, port=port, log_level="error")
Example #3
0
def test_add_graphql_route():
    app = Starlette()
    app.add_route("/", GraphQLApp(schema=schema))
    client = TestClient(app)
    response = client.get("/?query={ hello }")
    assert response.status_code == 200
    assert response.json() == {"data": {"hello": "Hello stranger"}}
Example #4
0
 def compose(self, module_name: str = "models", **kwargs) -> ASGIApp:
     try:
         python_module = importlib.import_module(module_name)
         logger.debug(
             f"Found python module {python_module} for model serving")
     except ModuleNotFoundError as exc:
         err_msg = f"Cannot find Python module named {module_name}: {exc}"
         logger.exception(err_msg)
         raise ModuleNotFoundError(err_msg)
     class_members = inspect.getmembers(sys.modules[module_name],
                                        inspect.isclass)
     serving_models = [
         class_ for _, class_ in class_members
         if issubclass(class_, self._base_class)
         and class_ not in self._excluded_classes
     ]
     if not serving_models:
         err_msg = f"Could not find any model serving in {python_module}"
         logger.error(err_msg)
         raise NoModelServingFoundError(err_msg)
     elif len(serving_models) == 1:
         model_serving = serving_models[0](**kwargs)
         logger.debug(
             f"Initialized single model serving for {serving_models[0]}")
     else:
         model_serving = Starlette(**kwargs)
         for asgi_app in serving_models:
             slugified_app_name = slugify(
                 re.sub(SLUGIFY_REGEX, SLUGIFY_REPLACE, asgi_app.__name__))
             model_serving.mount(f"/{slugified_app_name}",
                                 asgi_app(**kwargs))
         model_serving.add_route("/", _index_endpoint, methods=["GET"])
         logger.debug(
             f"Initialized multiple model serving for {serving_models}")
     return model_serving
Example #5
0
def create_app():
    app = Starlette()
    app.add_route("/auth", with_auth, methods=["GET"])
    app.add_route("/no-auth", without_auth, methods=["GET"])
    app.add_websocket_route("/ws-auth", ws_with_auth)
    app.add_websocket_route("/ws-no-auth", ws_without_auth)
    return app
Example #6
0
def build_app(StripeAPI, response_callback=None, full_auth=True):
    app = Starlette()
    stripe_instance = StripeAPI(
        public_key=str(STRIPE_PUBLIC_KEY),
        secret_key=str(STRIPE_SECRET_KEY),
        webhook_secret=str(STRIPE_WEBHOOK_SECRET),
        callback_domain=STRIPE_APPLICATION_DOMAIN,
    )
    app.add_middleware(CORSMiddleware,
                       allow_origins=["*"],
                       allow_methods=["*"],
                       allow_headers=["*"])

    async def new_webhook(request):
        return await webhook_view(request,
                                  stripe_instance=stripe_instance,
                                  full_auth=full_auth)

    # new_webhook = lambda request: expression asyncio.coroutine(
    #     functools.partial(webhook_view, stripe_instance=stripe_instance)
    # )
    app.add_route("/webhook", new_webhook, methods=["POST"])
    new_verify_payment = lambda request: verify_payment(
        request,
        response_callback=response_callback,
        stripe_instance=stripe_instance,
        StripeAPI=StripeAPI,
    )
    app.add_route("/verify-payment/{order_id}",
                  new_verify_payment,
                  methods=["GET"])
    app.state.stripe = stripe_instance
    return app
Example #7
0
def prepare_app(*args, **kwargs):
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    app = Starlette(*args, routes=_routes, **kwargs)
    app.add_middleware(PrometheusMiddleware)
    app.add_route("/metrics/", metrics)
    return app
Example #8
0
def create_app(*,
               static_dir: Optional[str] = None,
               static_path: Optional[str] = None,
               **_kwargs: Dict[str, Any]) -> Starlette:
    app = Starlette(debug=True)
    app.add_middleware(CORSMiddleware,
                       allow_origins=['*'],
                       allow_methods=['*'],
                       allow_headers=['*'],
                       allow_credentials=True)
    app.add_route('/api/synthesize', synthesize, methods=['POST'])
    if static_dir is not None and static_path is not None:
        app.mount(static_path,
                  app=StaticFiles(directory=static_dir),
                  name='static')

    # if os.name != 'nt':
    #     from timing_asgi import TimingClient, TimingMiddleware  # type: ignore
    #     from timing_asgi.integrations import StarletteScopeToName  # type: ignore
    #
    #     class StdoutTimingClient(TimingClient):  # type: ignore
    #         def timing(self, metric_name, timing, tags=None) -> None:  # type: ignore
    #             print(metric_name, timing, tags)
    #
    #     app.add_middleware(
    #         TimingMiddleware,
    #         client=StdoutTimingClient(),
    #         metric_namer=StarletteScopeToName(prefix="mockdown", starlette_app=app)
    #     )

    return app
def init_app():
    app = Starlette()
    app.add_middleware(CORSMiddleware,
                       allow_origins=['*'],
                       allow_headers=['X-Requested-With', 'Content-Type'])
    if enable_index_page:
        app.mount('/static', StaticFiles(directory='app/static'))
        app.add_route('/', index, methods=["GET"])
    return app
Example #10
0
class Server:
    """
    `Server` is a thin wrapper around a Starlette application. Rather than have the Server inherit
    the Starlette application class we choose to forward specific methods. This gives us greater control
    over the sufrace area of the application when used with the jab harness as well as leaves open
    the option to break away from using the Starlette application itself and instead begin to use the
    starlette toolkit.
    """

    def __init__(self, host: Optional[str] = None, port: Optional[int] = None, debug: bool = False) -> None:
        self._app = Starlette(debug)
        self._host = host
        self._port = port

    def add_route(self, fn: Handler, rule: str, **options: Any) -> None:
        self._app.add_route(rule, fn, **options)

    def add_websocket_route(self, fn: WebSocketHandler, rule: str, **options: Any) -> None:
        self._app.add_websocket_route(rule, fn, **options)

    async def asgi(self, scope: dict, receive: Receive, send: Send) -> None:
        """
        Exposes the ASGI interface of the Starlette application to be used with your favorite ASGI server.
        """
        await self._app(scope, receive, send)  # pragma: no cover

    async def run(self) -> None:
        """
        Runs the app inside of uvicorn inside of the jab harness.

        NOTE
        ----
        Despite the async definition this function immediately blocks. It's an ugly
        vestige of when jab did not support an ASGI interface itself and the jab ASGI interface should
        always be used instead of it.
        """
        uvicorn.run(self._app, host=self._host or "0.0.0.0", port=self._port or 8000, lifespan="on")

    @property
    def starlette(self) -> Starlette:
        """
        Provides access to the underlying Starlette application.
        Useful in conjunction with `starlette.TestClient`.
        """
        return self._app

    @property
    def jab(self) -> Callable:
        """
        Provides a jab constructor to incorporate an already instantiated Server object.
        """

        def constructor() -> Server:
            return self

        return constructor
Example #11
0
    def app(self):
        app_ = Starlette()
        app_.add_middleware(PrometheusMiddleware, prefix="test_")
        app_.add_route("/metrics/", metrics)

        @app_.route("/foo/")
        def foo(request):
            return PlainTextResponse("Foo")

        return app_
    def create_app():
        app = Starlette()

        @app.route("/count")
        def count(request):
            return JSONResponse({"count": User.query.count()})

        app.add_route("/count", count)

        return app
Example #13
0
def test_graphql_context():
    app = Starlette()
    app.add_middleware(FakeAuthMiddleware)
    app.add_route("/", GraphQLApp(schema=schema))
    client = TestClient(app)
    response = client.post("/",
                           json={"query": "{ whoami }"},
                           headers={"Authorization": "Bearer 123"})
    assert response.status_code == 200
    assert response.json() == {"data": {"whoami": "Jane"}}
def test_app_add_route():
    app = Starlette()

    async def homepage(request):
        return PlainTextResponse("Hello, World!")

    app.add_route("/", homepage)
    client = TestClient(app)
    response = client.get("/")
    assert response.status_code == 200
    assert response.text == "Hello, World!"
Example #15
0
def main() -> None:
    ip = get_local_ip()

    app = Starlette()

    graphql_app = GraphQL(schema)

    app.add_route("/graphql", graphql_app)
    app.add_websocket_route("/graphql", graphql_app)

    typer.echo(f"App running on http://{ip}:8000/graphql")

    uvicorn.run(app, host="0.0.0.0", port=8000, log_level="error")
Example #16
0
def client():
    @requires(["authenticated"], redirect="auth:login")
    def home(request):
        return JSONResponse({"user": request.user.email})

    app = Starlette()
    app.mount(path="/auth", app=starlette_auth.app, name="auth")
    app.add_middleware(AuthenticationMiddleware,
                       backend=starlette_auth.backends.ModelAuthBackend())
    app.add_middleware(SessionMiddleware, secret_key="secret")
    app.add_route("/", home)

    with TestClient(app) as client:
        yield client
Example #17
0
def test_not_active():
    app = Starlette()
    app.add_middleware(SessionMiddleware, secret_key="example")
    app.add_middleware(AuthenticationMiddleware, backend=InactiveBackend())

    app.add_route("/", homepage)
    app.add_route("/dashboard", dashboard)
    app.add_route("/admin", admin)
    app.add_route("/unauthenticated", unauthenticated)

    with TestClient(app) as client:
        response = client.get("/")
        assert response.status_code == 200
        assert response.json() == {"authenticated": False, "user": ""}

        response = client.get("/dashboard")
        assert response.status_code == 403

        response = client.get("/admin")
        assert response.status_code == 200
        assert response.json() == {"authenticated": False, "user": ""}

        response = client.get("/unauthenticated")
        assert response.status_code == 200
        assert response.json() == {"authenticated": False, "user": ""}
Example #18
0
def build_app(
    PaystackAPI,
    root_path="",
    response_callback=None,
    post_webhook_processing=None,
    _app: Starlette = None,
):
    paystack_instance = PaystackAPI(
        public_key=str(PAYSTACK_PUBLIC_KEY),
        secret_key=str(PAYSTACK_SECRET_KEY),
        base_url=str(PAYSTACK_API_URL),
        django=False,
    )
    if _app:
        app = _app
    else:
        app = Starlette()
        app.add_middleware(
            CORSMiddleware,
            allow_origins=["*"],
            allow_methods=["*"],
            allow_headers=["*"],
        )

    def background_action(signature, body):
        return paystack_instance.webhook_api.verify(
            signature, body, full_auth=True, full=False, loop=loop
        )

    verify_action = post_webhook_processing or background_action

    async def new_webhook(request):
        return await webhook_view(
            request,
            background_action=verify_action,
            paystack_instance=paystack_instance,
        )

    app.add_route(root_path + "/webhook", new_webhook, methods=["POST"])
    new_verify_payment = lambda request: verify_payment(
        request,
        response_callback=response_callback,
        paystack_instance=paystack_instance,
        PaystackAPI=PaystackAPI,
    )
    app.add_route(
        root_path + "/verify-payment/{order_id}", new_verify_payment, methods=["GET"]
    )
    app.state.paystack = paystack_instance
    return app
    def app(self):
        app_ = Starlette()
        app_.add_middleware(PrometheusMiddleware)
        app_.add_route("/metrics/", metrics)

        @app_.route("/foo/")
        def foo(request):
            return PlainTextResponse("Foo")

        @app_.route("/bar/")
        def bar(request):
            raise ValueError("bar")

        return app_
    def _testapp(**middleware_options):
        app = Starlette()
        app.add_middleware(starlette_exporter.PrometheusMiddleware,
                           **middleware_options)
        app.add_route("/metrics", handle_metrics)

        @app.route("/200")
        @app.route("/200/{test_param}")
        def normal_response(request):
            return JSONResponse({"message": "Hello World"})

        @app.route("/500")
        @app.route("/500/{test_param}")
        async def error(request):
            raise HTTPException(status_code=500, detail="this is a test error")

        @app.route("/unhandled")
        @app.route("/unhandled/{test_param}")
        async def unhandled(request):
            test_dict = {"yup": 123}
            return JSONResponse({"message": test_dict["value_error"]})

        @app.route("/background")
        async def background(request):
            def backgroundtask():
                time.sleep(0.1)

            task = BackgroundTask(backgroundtask)
            return JSONResponse({"message": "task started"}, background=task)

        # testing routes added using Mount
        async def test_mounted_function(request):
            return JSONResponse({"message": "Hello World"})

        async def test_mounted_function_param(request):
            return JSONResponse({"message": request.path_params.get("item")})

        mounted_routes = Mount("/",
                               routes=[
                                   Route("/test/{item}",
                                         test_mounted_function_param),
                                   Route("/test", test_mounted_function)
                               ])

        app.mount("/mounted", mounted_routes)
        app.mount('/static',
                  app=StaticFiles(directory='tests/static'),
                  name="static")
        return app
Example #21
0
def app():
    async def simple1(request):
        return PlainTextResponse('1', status_code=201)

    async def simple2(request):
        return JSONResponse({'result': 2}, status_code=202)

    async def stop(request):
        return SHUTDOWN_RESPONSE

    a = Starlette()
    a.add_route('/simple1', simple1, ['GET', 'POST'])
    a.add_route('/simple2', simple2, ['GET', 'POST'])
    a.add_route('/stop', stop, ['GET', 'POST'])
    return a
def create_app():
    app = Starlette()
    app.mount(path="/auth", app=auth_app, name="auth")
    app.add_middleware(AuthenticationMiddleware, backend=ModelAuthBackend())
    app.add_middleware(SessionMiddleware, secret_key="secret")
    app.add_route("/unauthed", unauthed)
    app.add_route("/authed", authed)
    app.add_route("/read", read)
    app.add_route("/write", write)
    return app
Example #23
0
class StarletteServer(object):
    def __init__(self, ip: str="127.0.0.1", port: int=8080, debug: bool=False):
        self.server = Starlette(debug=debug)
        self.ip = ip
        self.port = port

    def add_routes(self, routes: Routes):
        for route in routes.routes:
            self.add_route(route)

    def add_route(self, route: Route):
        self.server.add_route(route.path, route.function, route.methods)
    
    def add_static_file_directory(self, directory: str):
        self.server.mount(f"/{directory}", app=StaticFiles(directory=directory))

    def run(self):
        uvicorn.run(self.server, host=self.ip, port=self.port)
Example #24
0
def make_app(BASE):
    class CatchAll(BaseHTTPMiddleware):
        async def dispatch(self, request: Request, handler):
            request.scope["path"] = BASE  # TODO subscriptions path
            return await handler(request)

    app = Starlette(debug=True)

    app.add_middleware(CORSMiddleware,
                       allow_headers=["*"],
                       allow_origins=["*"],
                       allow_methods=["*"])

    graphql_app = GraphQL(schema, debug=True)

    app.add_route(BASE, graphql_app)
    app.add_websocket_route(BASE, graphql_app)
    app = CatchAll(app)
    return app
Example #25
0
    def app(self):
        """ create a test app with various endpoints for the test scenarios """
        app = Starlette()
        app.add_middleware(PrometheusMiddleware, group_paths=True)
        app.add_route("/metrics", handle_metrics)

        @app.route("/200/{test_param}")
        def normal_response(request):
            return JSONResponse({"message": "Hello World"})

        @app.route("/500/{test_param}")
        async def error(request):
            raise HTTPException(status_code=500, detail="this is a test error")

        @app.route("/unhandled/{test_param}")
        async def unhandled(request):
            test_dict = {"yup": 123}
            return JSONResponse({"message": test_dict["value_error"]})

        return app
Example #26
0
def init_app():
    engine = create_engine(
        os.environ.get("SQLALCHEMY_DATABASE_URI", "sqlite:///debug-database.db?check_same_thread=false"),
        **os.environ.get("SQLALCHEMY_ENGINE_OPTIONS", {"pool_pre_ping": True}),
    )

    Session = scoped_session(sessionmaker(bind=engine))
    app = Starlette()

    logger = make_base_logger(__name__)

    for base in AutoMarshmallowSchema.get_subclasses(Base):
        s = AutoMarshmallowSchema.generate_schema(base)
        endpoint = Client.make_endpoint(s)

        logger.info(f"Registering '{endpoint}'")
        app.add_route(f"/{endpoint}", DatabaseResource.make_endpoint(s, Session, create_ignore=["id"]))

    logger.info("Successfully registered all views")
    logger.info(f"Registered routes: {', '.join(r.path for r in app.routes)}")

    return app
    def _testapp(**middleware_options):
        app = Starlette()
        app.add_middleware(starlette_exporter.PrometheusMiddleware,
                           **middleware_options)
        app.add_route("/metrics", handle_metrics)

        @app.route("/200")
        @app.route("/200/{test_param}")
        def normal_response(request):
            return JSONResponse({"message": "Hello World"})

        @app.route("/500")
        @app.route("/500/{test_param}")
        async def error(request):
            raise HTTPException(status_code=500, detail="this is a test error")

        @app.route("/unhandled")
        @app.route("/unhandled/{test_param}")
        async def unhandled(request):
            test_dict = {"yup": 123}
            return JSONResponse({"message": test_dict["value_error"]})

        return app
Example #28
0
def init_app():
    engine = create_engine(
        os.environ.get("SQLALCHEMY_DATABASE_URI",
                       "sqlite:///debug-database.db?check_same_thread=false"),
        **os.environ.get("SQLALCHEMY_ENGINE_OPTIONS", {"pool_pre_ping": True}),
    )

    Session = scoped_session(sessionmaker(bind=engine))

    sleep(uniform(0.0, 5.0))
    Base.metadata.create_all(bind=engine)

    api = Starlette()

    for base in AutoMarshmallowSchema.get_subclasses(Base):
        s = AutoMarshmallowSchema.generate_schema(base)
        api.add_route(
            f"/{s.endpoint()}",
            DatabaseResource.make_endpoint(s, Session, mixin_ignore=BaseMixin))

    logger = make_base_logger(__name__)
    logger.info("Successfully registered all views")

    return api
    def decorate_app(self, starlette_app: Starlette):
        starlette_app.add_route(_get_url_path(self._base_path, "api",
                                              "status"),
                                self.get_status,
                                methods=["GET"])
        starlette_app.add_route(_get_url_path(self._base_path, "api",
                                              "process", "batch"),
                                self.process_batch,
                                methods=["POST"])

        starlette_app.add_route(_get_url_path(self._base_path, "swagger", "v1",
                                              "swagger.json"),
                                self.get_swagger,
                                methods=["GET"])
Example #30
0
def setup_routes(app: Starlette) -> None:
    """Add all of lamia's default routes.

    TODO: A different setup function should be added to do the same for
    routes associated with extensions.
    """
    # Static content loading
    app.mount('/static', StaticFiles(directory='statics'), name='static')

    # Just a boring test route
    app.add_route('/', lamia_general.introduction, ['GET'])

    # Nodeinfo routes
    app.add_route('/.well-known/nodeinfo', lamia_nodeinfo.nodeinfo_index,
                  ['GET'])
    app.add_route('/nodeinfo/2.0.json', lamia_nodeinfo.nodeinfo_schema_20,
                  ['GET'])

    # Graph QL endpoint
    app.add_route(
        '/graphql',
        GraphQLApp(schema=graphene.Schema(query=Queries, mutation=Mutations),
                   executor_class=AsyncioExecutor))
Example #31
0
def init():
    app = Starlette()

    @app.on_event("startup")
    async def async_setup():
        await pg_init()

    @app.exception_handler(JSONDecodeError)
    async def bad_json(request, exc):
        return JSONResponse({'reason': 'invalid json', 'details': str(exc)}, status_code=400)

    @app.exception_handler(InsufficientPermissionsError)
    async def handle_permissions(request, exc):
        return JSONResponse({'reason': 'you are not authorized to do that dave'}, status_code=403)

    # auth stuff
    auth = GoogleAuthBackend(GOOGLE_ID, GOOGLE_SECRET, GOOGLE_ORG)
    app.add_middleware(AuthenticationMiddleware,
                       backend=auth,
                       on_error=auth.on_error)

    app.add_middleware(SessionMiddleware, session_cookie=COOKIE_NAME,
                       secret_key=COOKIE_KEY, https_only=not LOCAL_DEV,
                       max_age=2 * 24 * 60 * 60)  # 2 days

    # sentry stuff
    sentry_sdk.init(dsn=SENTRY_URL, environment=ENV_NAME)
    app.add_middleware(SentryMiddleware)

    async def index_html(request):
        static = pathlib.Path('tmeister/static/index.html')
        return HTMLResponse(static.read_text())

    app.add_route('/api/envs/{name}/toggles', toggles.get_toggle_states_for_env, methods=['GET'])
    app.add_route('/api/toggles', toggles.get_all_toggle_states, methods=['GET'])
    app.add_route('/api/toggles', toggles.set_toggle_state, methods=['PATCH'])
    app.add_route('/api/features', features.get_features)
    app.add_route('/api/features', features.create_feature, methods=['POST'])
    app.add_route('/api/features/{name}', features.delete_feature, methods=['DELETE'])
    app.add_route('/api/envs', environments.get_envs)
    app.add_route('/api/envs', environments.add_env, methods=['POST'])
    app.add_route('/api/envs/{name}', environments.delete_env, methods=['DELETE'])
    app.add_route('/api/auditlog', auditing.get_audit_events)
    app.add_route('/heartbeat', health.get_health)
    app.add_route('/', index_html)

    app.mount('/', app=StaticFiles(directory='tmeister/static'), name='static')

    return app