示例#1
0
def init_app():
    custom_app = FastAPI()
    custom_app.add_middleware(
        PrometheusMiddleware, app_name="bookshelf", group_paths=True
    )
    custom_app.add_middleware(DBSessionMiddleware, db_url=DB_URL)
    custom_app.add_route("/metrics", handle_metrics)
    custom_app.include_router(author_controller.router)

    return custom_app
示例#2
0
def setup(app: FastAPI) -> None:

    app.add_middleware(
        Prometheus,
        app_name=settings.SKILL_NAME,
        prefix="http",
    )

    route = getattr(settings, "PROMETHEUS_ENDPOINT", "/prometheus")
    app.add_route(route, handle_metrics)
示例#3
0
def _setup_redoc(app: FastAPI):
    from fastapi.applications import Request, HTMLResponse

    async def redoc_html(_req: Request) -> HTMLResponse:
        return get_redoc_html(
            openapi_url=app.openapi_url,
            title=app.title + " - redoc",
            redoc_favicon_url=FAVICON,
        )

    app.add_route("/redoc", redoc_html, include_in_schema=False)
示例#4
0
def patch_fastapi(app: FastAPI) -> None:
    """Patch function to allow relative url resolution.

    This patch is required to make fastapi fully functional with a relative url path.
    This code snippet can be copy-pasted to any Fastapi application.
    """
    from fastapi.openapi.docs import get_swagger_ui_html
    from starlette.requests import Request
    from starlette.responses import HTMLResponse

    async def swagger_ui_html(req: Request) -> HTMLResponse:
        assert app.openapi_url is not None
        swagger_ui = get_swagger_ui_html(
            openapi_url="./" + app.openapi_url.lstrip("/"),
            title=app.title + " - Swagger UI",
            oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
        )

        # insert request interceptor to have all request run on relativ path
        request_interceptor = (
            "requestInterceptor: (e)  => {"
            "\n\t\t\tvar url = window.location.origin + window.location.pathname"
            '\n\t\t\turl = url.substring( 0, url.lastIndexOf( "/" ) + 1);'
            "\n\t\t\turl = e.url.replace(/http(s)?:\/\/[^/]*\//i, url);"  # noqa: W605
            "\n\t\t\te.contextUrl = url"
            "\n\t\t\te.url = url"
            "\n\t\t\treturn e;}")

        return HTMLResponse(
            swagger_ui.body.decode("utf-8").replace(
                "dom_id: '#swagger-ui',",
                "dom_id: '#swagger-ui',\n\t\t" + request_interceptor + ",",
            ))

    # remove old docs route and add our patched route
    routes_new = []
    for app_route in app.routes:
        if app_route.path == "/docs":  # type: ignore
            continue
        routes_new.append(app_route)

    app.router.routes = routes_new

    assert app.docs_url is not None
    app.add_route(app.docs_url, swagger_ui_html, include_in_schema=False)
示例#5
0
def init_app(settings: Optional[AppSettings] = None) -> FastAPI:
    if settings is None:
        settings = AppSettings.create_default()

    logging.basicConfig(level=settings.loglevel)
    logging.root.setLevel(settings.loglevel)

    app = FastAPI(
        debug=settings.debug,
        title="Public API Server",
        description="osparc-simcore Public RESTful API Specifications",
        version=api_version,
        openapi_url=f"/api/{api_vtag}/openapi.json",
        docs_url="/dev/docs",
        redoc_url=None,  # default disabled, see below
    )

    logger.debug(settings)
    app.state.settings = settings

    override_openapi_method(app)

    app.add_event_handler("startup", create_start_app_handler(app))
    app.add_event_handler("shutdown", create_stop_app_handler(app))

    app.add_exception_handler(HTTPException, http_error_handler)
    app.add_exception_handler(RequestValidationError, http422_error_handler)

    # Routing

    # healthcheck at / and at /v0/
    app.include_router(health_router)

    # docs
    redoc_html = create_redoc_handler(app)
    app.add_route("/docs", redoc_html, include_in_schema=False)

    # api under /v*
    app.include_router(api_router, prefix=f"/{api_vtag}")

    use_route_names_as_operation_ids(app)

    return app
示例#6
0
def update_openapi(app: FastAPI) -> FastAPI:
    """Update OpenAPI response content-type.

    This function modifies the openapi route to comply with the STAC API spec's
    required content-type response header
    """
    urls = (server_data.get("url") for server_data in app.servers)
    server_urls = {url for url in urls if url}

    async def openapi(req: Request) -> JSONResponse:
        root_path = req.scope.get("root_path", "").rstrip("/")
        if root_path not in server_urls:
            if root_path and app.root_path_in_servers:
                app.servers.insert(0, {"url": root_path})
                server_urls.add(root_path)
        return VndOaiResponse(app.openapi())

    # Remove the default openapi route
    app.router.routes = list(
        filter(lambda r: r.path != app.openapi_url, app.router.routes)
    )
    # Add the updated openapi route
    app.add_route(app.openapi_url, openapi, include_in_schema=False)
    return app
示例#7
0
def set_up_route_for_docs_with_contracts_plugin(app: fastapi.FastAPI,
                                                path: str = "/docs") -> None:
    """
    Set up the route for Swagger UI with included plugin swagger-ui-plugin-contracts.

    The path must not be set before.
    You must explicitly tell FastAPI to exclude it during initialization with:

    .. code-block:: python

        app = FastAPI(docs_url=None)
    """
    for route in app.routes:
        if not isinstance(route, fastapi.routing.APIRoute):
            continue

        assert isinstance(route, fastapi.routing.APIRoute)

        if route.path == path and "GET" in route.methods:
            raise ValueError(
                f"The FastAPI app {app} has already the route with the method 'GET' set up for "
                f"{path!r}. "
                f"No route with method 'GET' must be set for {path!r} if you want to set up "
                f"an alternative Swagger UI with contracts plugin.")

    if app.openapi_url is None:
        raise ValueError(
            f"The FastAPI app {app} has the OpenAPI URL set to None. "
            f"Swagger UI with contracts plug-in can not be generated "
            f"if OpenAPI schema is not available.")

    # The part below has been adapted from fastapi.applications.FastAPI.setup()

    async def swagger_ui_html(req: Request) -> HTMLResponse:
        root_path = req.scope.get("root_path", "").rstrip("/")
        openapi_url = root_path + app.openapi_url
        oauth2_redirect_url = app.swagger_ui_oauth2_redirect_url
        if oauth2_redirect_url:
            oauth2_redirect_url = root_path + oauth2_redirect_url
        return get_swagger_ui_html(
            openapi_url=openapi_url,
            title=app.title + " - Swagger UI",
            oauth2_redirect_url=oauth2_redirect_url,
            init_oauth=app.swagger_ui_init_oauth,
        )

    app.add_route(path, swagger_ui_html, include_in_schema=False)

    if app.swagger_ui_oauth2_redirect_url:
        oauth2_already_set_up = False

        for route in app.routes:
            if not isinstance(route, fastapi.routing.APIRoute):
                continue

            assert isinstance(route, fastapi.routing.APIRoute)

            if (route.path == app.swagger_ui_oauth2_redirect_url
                    and "GET" in route.methods):
                oauth2_already_set_up = True

        if not oauth2_already_set_up:
            # We need to set up the Oauth2 route if it has not been already set since
            # it will be not automatically set in app.setup().
            #
            # Here is the relevant part of the app.setup() implementation:
            #
            # .. code-block:: python
            #
            #     if self.openapi_url and self.docs_url:
            #         ...
            #         if self.swagger_ui_oauth2_redirect_url:
            #             ...
            #

            async def swagger_ui_redirect(
                    req: Request,  # pylint: disable=unused-argument
            ) -> HTMLResponse:
                return fastapi.openapi.docs.get_swagger_ui_oauth2_redirect_html(
                )

            app.add_route(
                app.swagger_ui_oauth2_redirect_url,
                swagger_ui_redirect,
                include_in_schema=False,
            )
示例#8
0
    formatted_process_time = '{0:.2f}'.format(process_time)
    log.info(
        f"RID={idem} COMPLETED={formatted_process_time}ms REQUEST={request.method.upper()} {request.url.path} STATUS_CODE={response.status_code}"
    )

    return response


@app.on_event("startup")
async def startup():
    print("app started")


@app.on_event("shutdown")
async def shutdown():
    print("SHUTDOWN")


cors_origins = [i.strip() for i in settings.CORS_ORIGINS.split(",")]
app.add_middleware(
    CORSMiddleware,
    allow_origins=cors_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.add_middleware(PrometheusMiddleware)
app.add_route("/metrics/", metrics)
app.include_router(router)
示例#9
0
    'moviestar-dashboard.herokuapp.com',
    'http://moviestar-dashboard.herokuapp.com',
    'https://moviestar-dashboard.herokuapp.com', 'localhost:3000',
    'http://localhost:3000'
]

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

app.add_route(
    "/movies",
    GraphQLApp(schema=Schema(query=MovieQuery, mutation=MovieMutation),
               executor_class=AsyncioExecutor))

# app.add_route("/genres", GraphQLApp(
#     schema=Schema(query=GenreQuery, mutation=GenreMutation),
#     executor_class=AsyncioExecutor
# ))

app.add_route(
    "/calculations",
    GraphQLApp(schema=Schema(query=CalculationQuery,
                             mutation=CalculationMutation),
               executor_class=AsyncioExecutor))

app.add_route(
    "/people",
示例#10
0
from fastapi import FastAPI
from ariadne.asgi import GraphQL
from app.server.graphql.schema import schema
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.middleware import Middleware
from starlette.middleware.sessions import SessionMiddleware

from starlette_context import context, plugins
from starlette_context.middleware import ContextMiddleware

middleware = [
    Middleware(
        ContextMiddleware,
        plugins=(plugins.RequestIdPlugin(), plugins.CorrelationIdPlugin()),
    )
]

app = FastAPI(middleware=middleware)

app.add_route("/graphql", GraphQL(schema, debug=True))
示例#11
0
                    courses.seek(0)
                    courses.truncate()

                    json.dump(course_list, courses, indent=2)
        return UpdateCourse(course=course_list[indexOfCourse])


class Mutation(ObjectType):
    create_course = CreateCourse.Field()
    Update_course = UpdateCourse.Field()


app = FastAPI()

app.add_route(
    "/",
    GraphQLApp(schema=Schema(query=Query, mutation=Mutation),
               executor_class=AsyncioExecutor))


@app.get("/")
async def root():
    return {"message": "Hello World"}


@app.get("/hey")
async def urMsg():
    return {"message": "This is my message"}


# {
#   getCourse(id: "2") {
示例#12
0
conn = None
conn_factory = lambda: conn


@app.on_event("startup")
def startup_event():
    # print("startup event")
    global conn
    conn = psycopg2.connect(host="localhost",
                            database="postgres",
                            user="******",
                            password="******")


@app.on_event("shutdown")
def shutdown_event():
    # print("shutdown event")
    if conn:
        conn.close()


@app.get("/test")
def handler():
    sql = "SELECT * from app.attributes;"
    df = sqlio.read_sql_query(sql, conn)
    # print(df.to_markdown(index=False))
    return df.to_dict(orient="records")


app.add_route("/", get_grapql_app(conn_factory))
示例#13
0
app = FastAPI(title=settings.PROJECT_NAME,
              docs_url="/users/docs",
              redoc_url="/users/redoc",
              openapi_url=f"/users{settings.API_V1_STR}/openapi.json")

# These dont work well with uvicorn

# @app.on_event("startup")
# async def startup():
#     await database.connect()

# @app.on_event("shutdown")
# async def shutdown():
#     await database.disconnect()

# Set all CORS enabled origins
if settings.BACKEND_CORS_ORIGINS:
    app.add_middleware(
        CORSMiddleware,
        allow_origins=[
            str(origin) for origin in settings.BACKEND_CORS_ORIGINS
        ],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

app.include_router(api_router, prefix=f"/users{settings.API_V1_STR}")
app.add_route("/users/graphql",
              GraphQLApp(schema=gql_schema, executor_class=AsyncioExecutor))
示例#14
0
from fastapi import FastAPI
from starlette.graphql import GraphQLApp

from schema import schema

app = FastAPI()
app.add_route("/", GraphQLApp(schema=schema, graphiql=True))
示例#15
0
                           name=graphene.String(default_value="stranger"))
    familia = graphene.List(ElementoQL,
                            name=graphene.String(default_value="stranger"))

    def resolve_elemento(parent, info, name):
        """Função que retorna os dados da querie de elemento."""
        resultado = find_nome(retornaChave(name), app.elementos)
        return buscaElemento_Nome(resultado)

    def resolve_sigla(parent, info, name):
        """Função que retorna os dados da querie de sigla."""
        resultado = find_sigla(retornaChave(name), app.elementos)
        return buscaElemento_Sigla(resultado)

    def resolve_familia(parent, info, name):
        """Função que retorna os dados da querie de familia."""
        lista = list()
        [lista.append(elemento) for elemento in buscaElemento_Familia(name)]
        return lista


app.add_route(
    '/graphql',
    GraphQLApp(schema=graphene.Schema(query=Query, auto_camelcase=False)))


@app.get('/')
async def search_elements(request: Request):
    print(local_directory)
    return templates.TemplateResponse('index.html', {'request': request})
示例#16
0
class Circle(graphene.ObjectType):
    radius = graphene.Float(required=True)

class Shape(graphene.Union):
    class Meta:
        types = (Square, Rectangle, Circle)

class Query(graphene.ObjectType):
    shape = Shape()

    def resolve_shape(self, info):
        choice = randint(1, 3)
        if choice == 1:
            return Square(side_len=10.123)
        if choice == 2:
            return Rectangle(width=10, height=20)
        if choice == 3:
            return Circle(radius=2.56)


app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)
app.add_route("/", GraphQLApp(schema=graphene.Schema(query=Query)))
示例#17
0
import strawberry
from fastapi import FastAPI
from strawberry.asgi import GraphQL


@strawberry.type
class User:
    name: str
    age: int


@strawberry.type
class Query:
    @strawberry.field
    def user(self) -> User:
        return User(name="Patrick", age=100)


schema = strawberry.Schema(query=Query)

graphql_app = GraphQL(schema)

app = FastAPI()
app.add_route("/graphql", graphql_app)
app.add_websocket_route("/graphql", graphql_app)
示例#18
0
    description="API documents for guild.randosoru.me",
    version="0.5.6",
    docs_url=None,
    redoc_url="/doc",
)

sio_app = socketio.ASGIApp(sio_router.sio)

# CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
#

app.include_router(oauth.router)
app.include_router(user.router)
app.include_router(form.router)
app.include_router(bot.router)

app.add_route("/socket.io/", route=sio_app, methods=["GET", "POST"])
app.add_websocket_route("/socket.io/", sio_app)


@app.get("/")
def index():
    return {"version": app.version}
示例#19
0
        libData = getLibraryInfo(name)
        return Library(libData["name"], libData["keywords"],
                       libData["description"], libData["license"],
                       libData["homepage"])


app = FastAPI()
templates = Jinja2Templates(directory='static/')


@app.get("/")
def read_root(request: Request):
    #return {"Hello": "World"}
    return templates.TemplateResponse('index.html',
                                      context={'request': request})


@app.get("/getinfo/")
def read_item():
    return "GraphQL endpoint to return data"


'''
@app.get("/graphiql")
def get_graphiql():
    return GraphQLApp(schema=graphene.Schema(query=Query))
'''

app.add_route("/graphiql",
              GraphQLApp(schema=graphene.Schema(query=Query, types=[Library])))
示例#20
0
@app.middleware("http")
async def logger_middleware(request: Request, call_next):
    path = PrometheusMiddleware.get_path_template(request)
    logger.info(f'{path} ENTRY',
                extra={
                    'unique_log_id':
                    request.headers.get('unique_log_id', 'Not provided')
                })
    response = await call_next(request)
    logger.info(f'{path} EXIT',
                extra={
                    'unique_log_id':
                    request.headers.get('unique_log_id', 'Not provided')
                })
    return response


app.add_middleware(PrometheusMiddleware)
app.add_route('/metrics/', metrics)

app.include_router(
    share.router,
    prefix=PREFIX,
    responses={404: {
        'description': 'Not found'
    }},
)

app.add_route('/health/live', check_liveness)
app.add_route('/health/ready', check_readiness)
示例#21
0
    def resolve_entry(self, info, entry_id):
        return client.entry(entry_id)

    def resolve_entries(self,
                        info,
                        skip: Optional[int] = 0,
                        limit: Optional[int] = 30):
        return sorted(blog.items(skip, limit) + qiita.items(skip, limit),
                      key=lambda x: x.get("published_at"),
                      reverse=True)


app = FastAPI()
app.add_middleware(GZipMiddleware)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)
app.add_route(
    "/api",
    GraphQLApp(
        schema=graphene.Schema(query=Query, types=[BlogEntry, ExternalEntry])))


@app.options("/api/cors")
def api_cors():
    return {"status": "ok"}
示例#22
0
app = FastAPI()


@app.on_event("startup")
async def startup():
    await database.connect()


@app.on_event("shutdown")
async def shutdown():
    await database.disconnect()


class Places(gp.ObjectType):
    async_places = gp.String(description='places',
                             start_date=gp.DateTime(),
                             end_date=gp.DateTime())

    async def resolve_async_places(self, info, start_date, end_date):
        print(start_date)
        print(end_date)
        rows = await database.fetch_all(
            query=
            '''SELECT * FROM places where last_review >= :start_date AND last_review < :end_date'''
        )
        print(rows)
        return "xd"


app.add_route("/", GraphQLApp(schema=gp.Schema(query=Places)))
示例#23
0
"""Main module for the API app."""

import graphene  # type: ignore

from fastapi import FastAPI
from starlette.graphql import GraphQLApp
from graphql.execution.executors.asyncio import AsyncioExecutor

import schema

app = FastAPI()
app.add_route(
    "/",
    GraphQLApp(schema=graphene.Schema(query=schema.Query),
               executor_class=AsyncioExecutor))
示例#24
0
def get_fastapi_app(
    args: 'argparse.Namespace',
    topology_graph: 'TopologyGraph',
    connection_pool: 'GrpcConnectionPool',
    logger: 'JinaLogger',
    metrics_registry: Optional['CollectorRegistry'] = None,
):
    """
    Get the app from FastAPI as the REST interface.

    :param args: passed arguments.
    :param topology_graph: topology graph that manages the logic of sending to the proper executors.
    :param connection_pool: Connection Pool to handle multiple replicas and sending to different of them
    :param logger: Jina logger.
    :param metrics_registry: optional metrics registry for prometheus used if we need to expose metrics from the executor or from the data request handler
    :return: fastapi app
    """
    with ImportExtensions(required=True):
        from fastapi import FastAPI
        from fastapi.middleware.cors import CORSMiddleware
        from fastapi.responses import HTMLResponse
        from starlette.requests import Request

        from jina.serve.runtimes.gateway.http.models import (
            JinaEndpointRequestModel,
            JinaRequestModel,
            JinaResponseModel,
            JinaStatusModel,
        )

    docs_url = '/docs'
    app = FastAPI(
        title=args.title or 'My Jina Service',
        description=args.description or
        'This is my awesome service. You can set `title` and `description` in your `Flow` or `Gateway` '
        'to customize this text.',
        version=__version__,
        docs_url=docs_url if args.default_swagger_ui else None,
    )

    if args.cors:
        app.add_middleware(
            CORSMiddleware,
            allow_origins=['*'],
            allow_credentials=True,
            allow_methods=['*'],
            allow_headers=['*'],
        )
        logger.warning(
            'CORS is enabled. This service is now accessible from any website!'
        )

    from jina.serve.runtimes.gateway.request_handling import RequestHandler
    from jina.serve.stream import RequestStreamer

    request_handler = RequestHandler(metrics_registry, args.name)

    streamer = RequestStreamer(
        args=args,
        request_handler=request_handler.handle_request(
            graph=topology_graph, connection_pool=connection_pool),
        result_handler=request_handler.handle_result(),
    )
    streamer.Call = streamer.stream

    @app.on_event('shutdown')
    async def _shutdown():
        await connection_pool.close()

    openapi_tags = []
    if not args.no_debug_endpoints:
        openapi_tags.append({
            'name':
            'Debug',
            'description':
            'Debugging interface. In production, you should hide them by setting '
            '`--no-debug-endpoints` in `Flow`/`Gateway`.',
        })

        from jina.serve.runtimes.gateway.http.models import JinaHealthModel

        @app.get(
            path='/',
            summary='Get the health of Jina service',
            response_model=JinaHealthModel,
        )
        async def _health():
            """
            Get the health of this Jina service.
            .. # noqa: DAR201

            """
            return {}

        @app.get(
            path='/status',
            summary='Get the status of Jina service',
            response_model=JinaStatusModel,
            tags=['Debug'],
        )
        async def _status():
            """
            Get the status of this Jina service.

            This is equivalent to running `jina -vf` from command line.

            .. # noqa: DAR201
            """
            _info = get_full_version()
            return {
                'jina': _info[0],
                'envs': _info[1],
                'used_memory': used_memory_readable(),
            }

        @app.post(
            path='/post',
            summary='Post a data request to some endpoint',
            response_model=JinaResponseModel,
            tags=['Debug']
            # do not add response_model here, this debug endpoint should not restricts the response model
        )
        async def post(body: JinaEndpointRequestModel):
            """
            Post a data request to some endpoint.

            This is equivalent to the following:

                from jina import Flow

                f = Flow().add(...)

                with f:
                    f.post(endpoint, ...)

            .. # noqa: DAR201
            .. # noqa: DAR101
            """
            # The above comment is written in Markdown for better rendering in FastAPI
            from jina.enums import DataInputType

            bd = body.dict()  # type: Dict
            req_generator_input = bd
            req_generator_input['data_type'] = DataInputType.DICT
            if bd['data'] is not None and 'docs' in bd['data']:
                req_generator_input['data'] = req_generator_input['data'][
                    'docs']

            result = await _get_singleton_result(
                request_generator(**req_generator_input))
            return result

    def expose_executor_endpoint(exec_endpoint, http_path=None, **kwargs):
        """Exposing an executor endpoint to http endpoint
        :param exec_endpoint: the executor endpoint
        :param http_path: the http endpoint
        :param kwargs: kwargs accepted by FastAPI
        """

        # set some default kwargs for richer semantics
        # group flow exposed endpoints into `customized` group
        kwargs['tags'] = kwargs.get('tags', ['Customized'])
        kwargs['response_model'] = kwargs.get(
            'response_model',
            JinaResponseModel,  # use standard response model by default
        )
        kwargs['methods'] = kwargs.get('methods', ['POST'])

        @app.api_route(path=http_path or exec_endpoint,
                       name=http_path or exec_endpoint,
                       **kwargs)
        async def foo(body: JinaRequestModel):
            from jina.enums import DataInputType

            bd = body.dict() if body else {'data': None}
            bd['exec_endpoint'] = exec_endpoint
            req_generator_input = bd
            req_generator_input['data_type'] = DataInputType.DICT
            if bd['data'] is not None and 'docs' in bd['data']:
                req_generator_input['data'] = req_generator_input['data'][
                    'docs']

            result = await _get_singleton_result(
                request_generator(**req_generator_input))
            return result

    if not args.no_crud_endpoints:
        openapi_tags.append({
            'name':
            'CRUD',
            'description':
            'CRUD interface. If your service does not implement those interfaces, you can should '
            'hide them by setting `--no-crud-endpoints` in `Flow`/`Gateway`.',
        })
        crud = {
            '/index': {
                'methods': ['POST']
            },
            '/search': {
                'methods': ['POST']
            },
            '/delete': {
                'methods': ['DELETE']
            },
            '/update': {
                'methods': ['PUT']
            },
        }
        for k, v in crud.items():
            v['tags'] = ['CRUD']
            v['description'] = f'Post data requests to the Flow. Executors with `@requests(on="{k}")` will respond.'
            expose_executor_endpoint(exec_endpoint=k, **v)

    if openapi_tags:
        app.openapi_tags = openapi_tags

    if args.expose_endpoints:
        endpoints = json.loads(args.expose_endpoints)  # type: Dict[str, Dict]
        for k, v in endpoints.items():
            expose_executor_endpoint(exec_endpoint=k, **v)

    if not args.default_swagger_ui:

        async def _render_custom_swagger_html(req: Request) -> HTMLResponse:
            import urllib.request

            swagger_url = 'https://api.jina.ai/swagger'
            req = urllib.request.Request(swagger_url,
                                         headers={'User-Agent': 'Mozilla/5.0'})
            with urllib.request.urlopen(req) as f:
                return HTMLResponse(f.read().decode())

        app.add_route(docs_url,
                      _render_custom_swagger_html,
                      include_in_schema=False)

    if args.expose_graphql_endpoint:
        with ImportExtensions(required=True):
            from dataclasses import asdict

            import strawberry
            from docarray import DocumentArray
            from docarray.document.strawberry_type import (
                JSONScalar,
                StrawberryDocument,
                StrawberryDocumentInput,
            )
            from strawberry.fastapi import GraphQLRouter

            async def get_docs_from_endpoint(data, target_executor, parameters,
                                             exec_endpoint):
                req_generator_input = {
                    'data': [asdict(d) for d in data],
                    'target_executor': target_executor,
                    'parameters': parameters,
                    'exec_endpoint': exec_endpoint,
                    'data_type': DataInputType.DICT,
                }

                if (req_generator_input['data'] is not None
                        and 'docs' in req_generator_input['data']):
                    req_generator_input['data'] = req_generator_input['data'][
                        'docs']

                response = await _get_singleton_result(
                    request_generator(**req_generator_input))
                return DocumentArray.from_dict(
                    response['data']).to_strawberry_type()

            @strawberry.type
            class Mutation:
                @strawberry.mutation
                async def docs(
                    self,
                    data: Optional[List[StrawberryDocumentInput]] = None,
                    target_executor: Optional[str] = None,
                    parameters: Optional[JSONScalar] = None,
                    exec_endpoint: str = '/search',
                ) -> List[StrawberryDocument]:
                    return await get_docs_from_endpoint(
                        data, target_executor, parameters, exec_endpoint)

            @strawberry.type
            class Query:
                @strawberry.field
                async def docs(
                    self,
                    data: Optional[List[StrawberryDocumentInput]] = None,
                    target_executor: Optional[str] = None,
                    parameters: Optional[JSONScalar] = None,
                    exec_endpoint: str = '/search',
                ) -> List[StrawberryDocument]:
                    return await get_docs_from_endpoint(
                        data, target_executor, parameters, exec_endpoint)

            schema = strawberry.Schema(query=Query, mutation=Mutation)
            app.include_router(GraphQLRouter(schema), prefix='/graphql')

    async def _get_singleton_result(request_iterator) -> Dict:
        """
        Streams results from AsyncPrefetchCall as a dict

        :param request_iterator: request iterator, with length of 1
        :return: the first result from the request iterator
        """
        async for k in streamer.stream(request_iterator=request_iterator):
            request_dict = k.to_dict()
            return request_dict

    return app
示例#25
0
import numpy as np
from mlflow.tracking import MlflowClient
import mlflow

from starlette_exporter import PrometheusMiddleware, handle_metrics
import prometheus_client as prom
import time

#docker run -it  -p 5001:5001 --mount type=bind,source=$(pwd),target=/app land95/mlflow-server:0.1

# Initialisation
app = FastAPI()
mlflow.set_tracking_uri("sqlite:///mlruns.db")

app.add_middleware(PrometheusMiddleware)
app.add_route("/metrics", handle_metrics)
histogram_inference_time = prom.Histogram('Inference_time',
                                          'This is inference time')
histogram_class_prediction = prom.Histogram('my_api_label_pred',
                                            'None',
                                            buckets={0, 1})
count_class_prediction = prom.Counter('api_label_pred_number', 'None count')

app.add_middleware(
    CORSMiddleware,
    allow_origins=['http://grafana:3000'],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
示例#26
0
        return MappingModel.objects.get(user_id=user_id)

    def resolve_users_to_genomes(self, info, user_ids):
        return list(MappingModel.objects(user_id__in=user_ids))


app = FastAPI()


@app.on_event("startup")
def connect_db_client():
    connect("genetrustee")


@app.on_event("shutdown")
def shutdown_db_client():
    disconnect_all


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

app.add_route(
    "/", GraphQLApp(schema=graphene.Schema(query=Query, mutation=Mutations)))
示例#27
0
        return AddTask(ok=True, task=task)


class DeleteTask(graphene.Mutation):
    class Arguments:
        idx = graphene.ID()

    ok = graphene.Boolean()
    task = graphene.Field(lambda: Task)

    def mutate(parent, info, idx):
        task = manager.delete_task(idx)
        return AddTask(ok=True, task=task)


class RootMutation(graphene.ObjectType):
    add_task = AddTask.Field()
    edit_task = EditTask.Field()
    delete_task = DeleteTask.Field()


app = FastAPI()
app.add_route(
    "/",
    GraphQLApp(schema=graphene.Schema(query=RootQuery, mutation=RootMutation)))

# Run:
# uvicorn main:app --reload
# Visit:
# http://127.0.0.1:8000/
示例#28
0
def init_prometheus(app: FastAPI, settings: Any):
    if getattr(settings, "PROMETHEUS_ENABLE", None):
        logger.info("Middleware enabled: PrometheusMiddleware")
        app.add_middleware(PrometheusMiddleware)
        app.add_route(settings.PROMETHEUS_PATH, metrics)
示例#29
0
import graphene
from fastapi import FastAPI
from starlette.graphql import GraphQLApp
from graphene_sqlalchemy import SQLAlchemyObjectType, SQLAlchemyConnectionField

from . import crud, models
from .database import engine, SessionLocal

models.Base.metadata.create_all(bind=engine)


class Song(SQLAlchemyObjectType):
    class Meta:
        model = models.Song


class Query(graphene.ObjectType):
    songs = graphene.List(Song)

    def resolve_songs(self, info):
        session = info.context.get("session", SessionLocal)
        return crud.get_all_songs(session)


app = FastAPI()
schema = graphene.Schema(query=Query)
app.add_route("/", GraphQLApp(schema=schema))
示例#30
0
)

# CORS
origins = []

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_methods=[settings.BACKEND_CORS_ORIGINS],
    allow_headers=[settings.BACKEND_CORS_ORIGINS],
    allow_credentials=True,
)

app.add_middleware(starlette_prometheus.PrometheusMiddleware)

app.add_route(f"{settings.API_V1_STR}/metrics", starlette_prometheus.metrics)

app.include_router(token.router,
                   tags=["token"],
                   prefix=f"{settings.API_V1_STR}")
app.include_router(home.router, tags=["home"], prefix=f"{settings.API_V1_STR}")
app.include_router(alive.router,
                   tags=["alive"],
                   prefix=f"{settings.API_V1_STR}")
app.include_router(version.router,
                   tags=["version"],
                   prefix=f"{settings.API_V1_STR}")
app.include_router(login.router,
                   tags=["login"],
                   prefix=f"{settings.API_V1_STR}")
app.include_router(users.router,