Пример #1
0
 def add_endpoint_to_router(self, router: APIRouter):
     """ Add one route to the router """
     router.add_api_route(
         self.path,
         self.view_func,
         methods=self.methods,
         **self.api_route_kwargs
     )
Пример #2
0
def MultiServer(objs, obj_ids):
    root_router = APIRouter()
    for obj, obj_id in zip(objs, obj_ids):
        router = create_obj_router(obj)
        root_router.include_router(router, prefix=f"/{obj_id}")
    root_router.add_api_route("/ids", lambda: obj_ids, methods=["POST"])
    app = FastAPI()
    app.include_router(root_router)
    return app
Пример #3
0
def api_route_read_all(router: APIRouter,
                       endpoint: Callable,
                       response_model: BaseModel,
                       path: str = "/"):
    router.add_api_route(
        path=path,
        endpoint=endpoint,
        methods=["GET"],
        response_model=response_model,
    )
Пример #4
0
def create_obj_router(obj):
    cls = obj.__class__
    relevant_attributes = get_relevant_attributes_from_class(cls)
    router = APIRouter()
    for attr_name, attr in relevant_attributes:
        if callable(attr):
            endpoint = create_method_endpoint(obj, attr_name, attr)
        elif isinstance(attr, property):
            endpoint = create_property_endpoint(obj, attr_name, attr)
        router.add_api_route(f"/{attr_name}", endpoint, methods=["POST"])
    return router
Пример #5
0
def create_router_from_dict(obj: Dict, name: str) -> APIRouter:
    router = APIRouter(prefix=f"/{name}", tags=[name])
    for k, v in obj.items():
        if not k.startswith("_") and callable(v) and hasattr(
                v, "__invocationmethod__"):
            router.add_api_route(
                getattr(v, "__invocationpath__", "/"),
                v,
                methods=[getattr(v, "__invocationmethod__")],
                summary=v.__name__,
            )
    return router
Пример #6
0
def fastapi_app():
    app = FastAPI()
    app.add_api_route("/", handle, methods=["GET"])
    app.add_api_route("/a", handle_a, methods=["GET"])
    app.add_api_route("/b", handle_b, methods=["GET"])
    app.add_api_route("/err", handle_error, methods=["GET"])
    app.add_api_route(MULTIPLE_THREADS_ROUTE,
                      multiple_threads_route,
                      methods=["GET"])
    router = APIRouter()
    router.add_api_route(TEST_ROUTER_PATH, handle_router_endpoint)
    app.include_router(router, prefix=TEST_ROUTER_PREFIX)
    return app
Пример #7
0
 def set_route(self):
     tags = [self.__mod_name]
     # dependencies = [Depends(oauth2_scheme)]
     dependencies = None
     path = "/{}".format(self.__mod_name)
     pathwithpara = "%s/{code}" % (path)
     apiroute = APIRouter(tags=tags, dependencies=dependencies)
     apiroute.add_api_route(path=path,
                            methods=["get"],
                            name=f"Get {self.__mod_name}",
                            endpoint=self.get,
                            response_model=Page[self.model])
     apiroute.add_api_route(path=pathwithpara,
                            methods=["get"],
                            name=f"Get {self.__mod_name}",
                            endpoint=self.get,
                            response_model=Page[self.model])
     apiroute.add_api_route(path=path,
                            methods=["post"],
                            name=f"Post {self.__mod_name}",
                            endpoint=self.post,
                            response_model=Page[self.model])
     apiroute.add_api_route(path=pathwithpara,
                            methods=["post"],
                            name=f"Post {self.__mod_name}",
                            endpoint=self.post,
                            response_model=Page[self.model])
     return {"route": apiroute}
Пример #8
0
def api_route_delete(router: APIRouter,
                     endpoint: Callable,
                     path: str = "/{uuid}"):
    router.add_api_route(
        path=path,
        endpoint=endpoint,
        methods=["DELETE"],
        responses={
            status.HTTP_400_BAD_REQUEST: {
                "description": "Unable to delete the alert queue"
            },
        },
        status_code=status.HTTP_204_NO_CONTENT,
    )
Пример #9
0
def api_route_read(router: APIRouter,
                   endpoint: Callable,
                   response_model: BaseModel,
                   path: str = "/{uuid}"):
    router.add_api_route(
        path=path,
        endpoint=endpoint,
        methods=["GET"],
        response_model=response_model,
        responses={
            status.HTTP_404_NOT_FOUND: {
                "description": "The UUID was not found"
            },
        },
    )
Пример #10
0
    def register(self, app: FastAPI) -> None:
        """register extension with the application"""
        items_request_model = _create_request_model(schemas.Items)

        router = APIRouter()
        router.add_api_route(
            name="Bulk Create Item",
            path="/collections/{collectionId}/bulk_items",
            response_model=str,
            response_model_exclude_unset=True,
            response_model_exclude_none=True,
            methods=["POST"],
            endpoint=create_endpoint_from_model(self.client.bulk_item_insert,
                                                items_request_model),
        )
        app.include_router(router, tags=["Bulk Transaction Extension"])
Пример #11
0
def api_route_create(router: APIRouter, endpoint: Callable, path: str = "/"):
    router.add_api_route(
        path=path,
        endpoint=endpoint,
        methods=["POST"],
        response_class=
        Response,  # This allows to respond with a 201 and no body listed in the documentation
        responses={
            status.HTTP_201_CREATED: {
                "headers": {
                    "Content-Location": {
                        "description": "The path to retrieve the resource"
                    },
                },
            },
            status.HTTP_409_CONFLICT: {
                "description": "The resource already exists"
            },
        },
        status_code=status.HTTP_201_CREATED,
    )
Пример #12
0
def init_app() -> Starlette:
    app = FastAPI()
    # 每个app创建特有路由
    for app_info in INJECTION_APPS:
        router = APIRouter()
        for api_name, params in get_app_info(parse_path=PRASE_PATH, frida_js_path=app_info["absolute_path"]).items():
            params_dict = dict(zip(params, function_params_hints[api_name])) if (
                api_name in function_params_hints) else dict.fromkeys(params, "bb")
            model_name = f"{api_name}Model"
            Model = create_model(model_name, **params_dict)
            new_api_name = name_transform(api_name)
            func = generate_function(
                new_api_name,
                app_info["script"],
                model_name,
                Model
            )
            router.add_api_route(f"/{new_api_name}", func, methods=["POST"])
        app.include_router(
            router,
            prefix=f"/{app_info['path']}",
            tags=[app_info["name"]]
        )

    def custom_openapi():
        if app.openapi_schema:
            return app.openapi_schema
        openapi_schema = get_openapi(
            title="Arida框架",
            version="0.0.1",
            description="基于FastAPI实现的Frida-RPC工具   https://github.com/lateautumn4lin/arida",
            routes=app.routes,
        )
        openapi_schema["info"]["x-logo"] = {
            "url": "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png"
        }
        app.openapi_schema = openapi_schema
        return app.openapi_schema
    app.openapi = custom_openapi
    return app
Пример #13
0
    def register(self, app: FastAPI) -> None:
        """Register the extension with a FastAPI application.

        Args:
            app: target FastAPI application.

        Returns:
            None
        """
        items_request_model = _create_request_model(Items)

        router = APIRouter()
        router.add_api_route(
            name="Bulk Create Item",
            path="/collections/{collectionId}/bulk_items",
            response_model=str,
            response_model_exclude_unset=True,
            response_model_exclude_none=True,
            methods=["POST"],
            endpoint=create_sync_endpoint(self.client.bulk_item_insert,
                                          items_request_model),
        )
        app.include_router(router, tags=["Bulk Transaction Extension"])
Пример #14
0
class FileBrowser():
    def __init__(self):
        self.router = APIRouter()

        self.router.add_api_route("/init",
                                  self._get_list_dir,
                                  name="list_dir",
                                  response_model=DirList,
                                  methods=["GET"])

        self.router.add_api_route("/list-dir",
                                  self._post_list_dir,
                                  name="list_dir",
                                  response_model=DirList,
                                  methods=["POST"])

    async def _post_list_dir(self, path: FilePath):
        content = {"items": App().file_browser.list_dir(path.path)}
        return content

    async def _get_list_dir(self):
        content = {"items": App().file_browser.list_dir("")}
        return content
Пример #15
0
def api_route_update(router: APIRouter,
                     endpoint: Callable,
                     path: str = "/{uuid}"):
    router.add_api_route(
        path=path,
        endpoint=endpoint,
        methods=["PATCH"],
        responses={
            status.HTTP_204_NO_CONTENT: {
                "headers": {
                    "Content-Location": {
                        "description": "The path to retrieve the resource"
                    }
                },
            },
            status.HTTP_404_NOT_FOUND: {
                "description": "The UUID was not found"
            },
            status.HTTP_409_CONFLICT: {
                "description": "The database returned an IntegrityError"
            },
        },
        status_code=status.HTTP_204_NO_CONTENT,
    )
Пример #16
0
def _build_fastapi_app():
    app = FastAPI()
    app.add_api_route("/", handle, methods=["GET"])
    app.add_api_route(CUSTOM_RESPONSE_PATH,
                      handle_custom_response,
                      methods=["GET"])
    app.add_api_route(BASE_MODEL_RESPONSE_PATH,
                      handle_base_model_response,
                      methods=["GET"])
    app.add_api_route(CUSTOM_STATUS_CODE_PATH,
                      handle_custom_status_code,
                      methods=["GET"],
                      status_code=CUSTOM_STATUS_CODE)
    app.add_api_route(OVERRIDDEN_CUSTOM_STATUS_CODE_PATH,
                      handle_overridden_custom_status_code,
                      methods=["GET"],
                      status_code=CUSTOM_STATUS_CODE)
    app.add_api_route(REQUEST_OBJ_PATH, handle_given_request, methods=["POST"])
    app.add_api_route("/a", handle_a, methods=["GET"])
    app.add_api_route("/b", handle_b, methods=["GET"])
    app.add_api_route("/err",
                      handle_error_from_route,
                      methods=["GET"],
                      status_code=200)
    app.add_api_route(MULTIPLE_THREADS_ROUTE,
                      multiple_threads_route,
                      methods=["GET"])
    router = APIRouter()
    router.add_api_route(TEST_ROUTER_PATH, handle_router_endpoint)
    app.include_router(router, prefix=TEST_ROUTER_PREFIX)
    router_with_custom_route = APIRouter(route_class=CustomRouteClass)
    router_with_custom_route.add_api_route(TEST_CUSTOM_ROUTE_PATH,
                                           handle_custom_route_endpoint)
    app.include_router(router_with_custom_route,
                       prefix=TEST_CUSTOM_ROUTE_PREFIX)
    return app
Пример #17
0
from fastapi import APIRouter, Depends

from resources import get_session
from .dal import get_user_posts, get_user_posts_sync
from .schemas import PostSchema, PostORMSchema


async def user_posts(user_id: int):
    posts = await get_user_posts(user_id)
    return posts


def user_posts_sync(user_id: int, session=Depends(get_session)):
    posts = get_user_posts_sync(session, user_id)
    return posts


router = APIRouter()
router.add_api_route(
    "/users/{user_id}/posts",
    user_posts,
    response_model=List[PostSchema],
    methods=("GET",),
)
router.add_api_route(
    "/users/{user_id}/posts/sync",
    user_posts_sync,
    response_model=List[PostORMSchema],
    methods=("GET",),
)
Пример #18
0
def model_view(
    router: APIRouter,
    path: str,
    orm_model,
    pydantic_model,
    create_model=None,
    allowed_methods: List[str] = ["GET_ONE"] + HTTP_METHODS,
    custom_methods: Dict[str, Callable] = {},
    background_tasks_mapping: Dict[str, Callable] = {},
):
    if not create_model:
        create_model = pydantic_model
    response_models: Dict[str, Type] = {
        "get": List[pydantic_model],  # type: ignore
        "get_one": pydantic_model,
        "post": pydantic_model,
        "put": pydantic_model,
        "patch": pydantic_model,
        "delete": pydantic_model,
    }

    item_path = path_join(path, "{model_id}")
    paths: Dict[str, str] = {
        "get": path,
        "get_one": item_path,
        "post": path,
        "put": item_path,
        "patch": item_path,
        "delete": item_path,
    }

    async def get():
        return await orm_model.query.gino.all()

    async def get_one(model_id: int):
        item = await orm_model.get(model_id)
        if not item:
            raise HTTPException(
                status_code=404,
                detail=f"Object with id {model_id} does not exist!")
        return item

    async def post(
            model: create_model,
            background_tasks: BackgroundTasks  # type: ignore
    ):
        try:
            obj = await orm_model.create(**model.dict())  # type: ignore
        except (
                asyncpg.exceptions.UniqueViolationError,
                asyncpg.exceptions.NotNullViolationError,
                asyncpg.exceptions.ForeignKeyViolationError,
        ) as e:
            raise HTTPException(422, e.message)
        if background_tasks_mapping.get("post"):
            background_tasks.add_task(background_tasks_mapping["post"], obj)
        return obj

    async def put(model_id: int, model: pydantic_model):  # type: ignore
        item = await get_one(model_id)
        try:
            await item.update(**model.dict()).apply()  # type: ignore
        except (
                asyncpg.exceptions.UniqueViolationError,
                asyncpg.exceptions.NotNullViolationError,
                asyncpg.exceptions.ForeignKeyViolationError,
        ) as e:
            raise HTTPException(422, e.message)
        return item

    async def patch(model_id: int, model: pydantic_model):  # type: ignore
        item = await get_one(model_id)
        try:
            await item.update(**model.dict(skip_defaults=True)  # type: ignore
                              ).apply()
        except (
                asyncpg.exceptions.UniqueViolationError,
                asyncpg.exceptions.NotNullViolationError,
                asyncpg.exceptions.ForeignKeyViolationError,
        ) as e:
            raise HTTPException(422, e.message)
        return item

    async def delete(model_id: int):
        item = await get_one(model_id)
        await item.delete()
        return item

    for method in allowed_methods:
        method_name = method.lower()
        router.add_api_route(  # type: ignore
            paths.get(method_name),
            custom_methods.get(method_name) or locals()[method_name],
            methods=[method_name if method in HTTP_METHODS else "get"],
            response_model=response_models.get(method_name),
        )
Пример #19
0
# Log response status code and body
@APP.middleware("http")
async def log_response(request: Request, call_next):
    response = await call_next(request)
    body = b""
    async for chunk in response.body_iterator:
        body += chunk

    logger.info(f"{response.status_code} {body!r}")

    return Response(
        content=body,
        status_code=response.status_code,
        headers=dict(response.headers),
        media_type=response.media_type,
    )


# Add routes from resources
for resource in RESOURCES:
    API_ROUTER.add_api_route(
        resource.route,
        resource.endpoint,
        description=resource.description,
        summary=resource.summary,
        methods=[resource.method],
        responses=resource.doc,
    )

APP.include_router(API_ROUTER, dependencies=[Depends(log_request)])
Пример #20
0
from controllers.token import token_create
from controllers.transfer import transfer_create, transfer_list
from controllers.user import user_create, user_get
from controllers.wallet import wallet_list
from views.token import TokenView
from views.transfer import TransferView
from views.user import UserView
from views.wallet import WalletView

router = APIRouter()

router.add_api_route(
    '/token',
    token_create,
    tags=['token'],
    methods=['POST'],
    response_model=TokenView,
)

router.add_api_route(
    '/user',
    user_create,
    tags=['user'],
    methods=['POST'],
    response_model=UserView,
)
router.add_api_route(
    '/user/me',
    user_get,
    tags=['user'],
Пример #21
0
            lineno=5,
            col_offset=4,
            value=Name(lineno=5, col_offset=11, id='res', ctx=Load()),
        ),
    ],
    decorator_list=[],
    returns=None,
)
module_ast = Module(body=[function_ast], type_ignores=[])
module_code = compile(module_ast, "<>", "exec")
function_code = [
    c for c in module_code.co_consts if isinstance(c, types.CodeType)
][0]
test = types.FunctionType(function_code, {
    "script": script,
    "Url": Url,
    "print": print
})
test.__annotations__ = {"item": Url}

router = APIRouter()
for k, v in get_app_info().items():
    router.add_api_route("/generate_url", test, methods=["POST"])
    break
app.include_router(router)

# @app.post('/generate_url')
# def generate_url(item: c):
#     res = script.exports.generate_url(item.origin_url)
#     return res
Пример #22
0
 def install(self, endpoint: CallableType, router: APIRouter):
     router.add_api_route(endpoint=endpoint, **self.args)
Пример #23
0
async def get_zipcode_risk_factor_from_database(request: Request,
                                                zipcode: int):
    # EXERCISE 3
    return await request.app.repositories.zipcodes.get(zipcode)


router = APIRouter()

router.add_api_route(
    "/index",
    get_index,
    include_in_schema=True,
    deprecated=False,
    methods=["GET"],
    status_code=200,
    description=
    "Retrieve the latest Belgian health index from external source for given base year. (default 2004)",
    summary="Retrieve Belgian Health Index",
    tags=["EX1"],
    response_model=IndexResponse,
)

router.add_api_route(
    "/zipcode/{zipcode}",
    get_zipcode_risk_factor,
    include_in_schema=True,
    deprecated=False,
    methods=["GET"],
    status_code=200,
    description="Retrieve the risk factor associated with given zipcode",
Пример #24
0
        if fuzzy:
            trait = str(cypher_fuzzify(trait))
            assoc_trait = cypher_fuzzify(assoc_trait)
            eq_symbol = "=~"
        if assoc_trait is not None:
            query = queries.GwasPairwise.trait_assoc_trait.format(
                trait=trait,
                assoc_trait=assoc_trait,
                semmantic_type_query=semmantic_type_query,
                pval_threshold=pval_threshold,
                eq_symbol=eq_symbol,
                skip=skip,
                limit=limit,
            )
        else:
            query = queries.GwasPairwise.trait.format(
                trait=trait,
                semmantic_type_query=semmantic_type_query,
                pval_threshold=pval_threshold,
                eq_symbol=eq_symbol,
                skip=skip,
                limit=limit,
            )
    res = epigraphdb.run_query(query)
    return res


router.add_api_route(path="/literature/gene",
                     endpoint=get_gene_literature,
                     methods=["GET"])
Пример #25
0
        "/google/",
    ),
    (
        SpotifyAuth,
        "/spotify/",
    ),
    (
        VKAuth,
        "/vk/",
    ),
]

for provider, endpoint in providers:
    router = APIRouter(route_class=provider)
    router.add_api_route(path=endpoint,
                         methods=["GET", "POST"],
                         endpoint=process_auth_route)
    auth_router.include_router(router)


@auth_router.post("/logout/",
                  response_model=LogoutOut,
                  summary="Destroy auth session")
async def logout_route(
        request: Request,
        user_id: str = Depends(bearer_auth),  # pylint: disable=unused-argument
) -> LogoutOut:
    """Logout user endpoint."""
    access_token: Optional[str] = request.scope.get("token")
    result: bool = await logout(access_token=access_token)
    response: LogoutOut = LogoutOut(data=result)
Пример #26
0
        db: Session = Depends(get_db),
        username: str = Form(None),
        password: str = Form(None),
):
    if request.method == "POST":
        db_user = db.query(
            models.User).filter(User.username == username).first()
        if not db_user:
            raise HTTPException(status_code=400, detail="用户不存在")
        print("验证通过 !!!")
        return RedirectResponse('/index')

    return templates.TemplateResponse("user/login.html", {"request": request})


async def userList(*, request: Request, db: Session = Depends(get_db)):
    userList = db.query(models.User).all()
    return templates.TemplateResponse("user/user-index.html", {
        "request": request,
        'userList': userList
    })


userRouter.add_api_route(methods=['GET', 'POST'],
                         path="/login",
                         endpoint=login,
                         response_model=schemas.UserOut)
userRouter.add_api_route(methods=['GET', 'POST'],
                         path="/list",
                         endpoint=userList)
Пример #27
0
import re

from fastapi import APIRouter
from starlette.requests import Request
from starlette.responses import Response
from starlette_prometheus import metrics

from ..models.admin import Health, HeathStatus

DESCRIPTION_RE = re.compile(r"\W")

router = APIRouter()


def health(request: Request):
    h = Health(
        status=HeathStatus.PASS,
        version=request.app.version.split(".", 1)[0],
        releaseID=request.app.version,
        description=DESCRIPTION_RE.sub("-", request.app.title.lower()),
    )
    return Response(
        content=h.json(by_alias=True, skip_defaults=True),
        media_type="application/health+json",
    )


router.add_api_route("/metrics", metrics)
router.add_api_route("/health", health, response_model=Health)
Пример #28
0
from typing import List

from fastapi import APIRouter

from app.models.employee import Employee
from app.router.endpoints import employee

api = APIRouter()

api.add_api_route("/findByField",
                  endpoint=employee.find_by_field,
                  methods=["GET"],
                  response_model=List[Employee])
api.add_api_route("/findByRange",
                  endpoint=employee.find_by_range,
                  methods=["GET"],
                  response_model=List[Employee])
Пример #29
0
def model_view(
    router: APIRouter,
    path: str,
    orm_model,
    pydantic_model,
    get_data_source,
    create_model=None,
    display_model=None,
    allowed_methods: List[str] = ["GET_COUNT", "GET_ONE"] + HTTP_METHODS,
    custom_methods: Dict[str, Callable] = {},
    background_tasks_mapping: Dict[str, Callable] = {},
    request_handlers: Dict[str, Callable] = {},
    auth=True,
    get_one_auth=True,
    post_auth=True,
    get_one_model=True,
    scopes=None,
):
    from . import schemes

    if scopes is None:
        scopes = {i: [] for i in ENDPOINTS}
    crud_models.append((path, orm_model, get_data_source))

    display_model = pydantic_model if not display_model else display_model
    if isinstance(scopes, list):
        scopes_list = scopes.copy()
        scopes = {i: scopes_list for i in ENDPOINTS}
    scopes = defaultdict(list, **scopes)

    PaginationResponse = create_pydantic_model(
        f"PaginationResponse_{display_model.__name__}",
        count=(int, ...),
        next=(Optional[str], None),
        previous=(Optional[str], None),
        result=(List[display_model], ...),
        __base__=BaseModel,
    )

    if not create_model:
        create_model = pydantic_model  # pragma: no cover
    response_models: Dict[str, Type] = {
        "get": PaginationResponse,
        "get_count": int,
        "get_one": display_model if get_one_model else None,
        "post": display_model,
        "put": display_model,
        "patch": display_model,
        "delete": display_model,
    }

    item_path = path_join(path, "{model_id}")
    count_path = path_join(path, "count")
    paths: Dict[str, str] = {
        "get": path,
        "get_count": count_path,
        "get_one": item_path,
        "post": path,
        "put": item_path,
        "patch": item_path,
        "delete": item_path,
    }

    auth_dependency = AuthDependency(auth)

    async def _get_one(model_id: int,
                       user: schemes.User,
                       internal: bool = False):
        if orm_model != models.User:
            query = orm_model.query.select_from(get_data_source())
            if user:
                query = query.where(models.User.id == user.id)
        else:
            query = orm_model.query
        item = await query.where(orm_model.id == model_id).gino.first()
        if custom_methods.get("get_one"):
            item = await custom_methods["get_one"](model_id, user, item,
                                                   internal)
        if not item:
            raise HTTPException(
                status_code=404,
                detail=f"Object with id {model_id} does not exist!")
        return item

    async def get(
        pagination: pagination.Pagination = Depends(),
        user: Union[None, schemes.User] = Security(auth_dependency,
                                                   scopes=scopes["get_all"]),
    ):
        if custom_methods.get("get"):
            return await custom_methods["get"](pagination, user,
                                               get_data_source())
        else:
            return await pagination.paginate(orm_model, get_data_source(),
                                             user.id)

    async def get_count(user: Union[None, schemes.User] = Security(
        auth_dependency, scopes=scopes["get_count"])):
        return (await ((orm_model.query.select_from(get_data_source()).where(
            models.User.id == user.id) if orm_model != models.User else
                        orm_model.query).with_only_columns([
                            db.db.func.count(distinct(orm_model.id))
                        ]).order_by(None).gino.scalar()) or 0)

    async def get_one(model_id: int, request: Request):
        try:
            user = await auth_dependency(request,
                                         SecurityScopes(scopes["get_one"]))
        except HTTPException:
            if get_one_auth:
                raise
            user = None
        return await _get_one(model_id, user)

    async def post(
        model: create_model,  # type: ignore,
        request: Request,
    ):
        try:
            user = await auth_dependency(request,
                                         SecurityScopes(scopes["post"]))
        except HTTPException:
            if post_auth:
                raise
            user = None
        try:
            if custom_methods.get("post"):
                obj = await custom_methods["post"](model, user)
            else:
                obj = await orm_model.create(**model.dict())  # type: ignore
        except (
                asyncpg.exceptions.UniqueViolationError,
                asyncpg.exceptions.NotNullViolationError,
                asyncpg.exceptions.ForeignKeyViolationError,
        ) as e:
            raise HTTPException(422, e.message)
        if background_tasks_mapping.get("post"):
            background_tasks_mapping["post"].send(obj.id)
        return obj

    async def put(
        model_id: int,
        model: pydantic_model,
        user: Union[None, schemes.User] = Security(auth_dependency,
                                                   scopes=scopes["put"]),
    ):  # type: ignore
        item = await _get_one(model_id, user, True)
        try:
            if custom_methods.get("put"):
                await custom_methods["put"](item, model,
                                            user)  # pragma: no cover
            else:
                await item.update(**model.dict()).apply()  # type: ignore
        except (
                asyncpg.exceptions.UniqueViolationError,
                asyncpg.exceptions.NotNullViolationError,
                asyncpg.exceptions.ForeignKeyViolationError,
        ) as e:
            raise HTTPException(422, e.message)
        return item

    async def patch(
        model_id: int,
        model: pydantic_model,
        user: Union[None, schemes.User] = Security(auth_dependency,
                                                   scopes=scopes["patch"]),
    ):  # type: ignore
        item = await _get_one(model_id, user, True)
        try:
            if custom_methods.get("patch"):
                await custom_methods["patch"](item, model,
                                              user)  # pragma: no cover
            else:
                await item.update(
                    **model.dict(exclude_unset=True)  # type: ignore
                ).apply()
        except (  # pragma: no cover
                asyncpg.exceptions.UniqueViolationError,
                asyncpg.exceptions.NotNullViolationError,
                asyncpg.exceptions.ForeignKeyViolationError,
        ) as e:
            raise HTTPException(422, e.message)  # pragma: no cover
        return item

    async def delete(
        model_id: int,
        user: Union[None, schemes.User] = Security(auth_dependency,
                                                   scopes=scopes["delete"]),
    ):
        item = await _get_one(model_id, user, True)
        if custom_methods.get("delete"):
            await custom_methods["delete"](item, user)
        else:
            await item.delete()
        return item

    for method in allowed_methods:
        method_name = method.lower()
        router.add_api_route(
            paths.get(method_name),  # type: ignore
            request_handlers.get(method_name) or locals()[method_name],
            methods=[method_name if method in HTTP_METHODS else "get"],
            response_model=response_models.get(method_name),
        )
Пример #30
0
 def register_core(self):
     """register stac core endpoints"""
     search_request_model = _create_request_model(schemas.STACSearch)
     fields_ext = self.get_extension(FieldsExtension)
     router = APIRouter()
     router.add_api_route(
         name="Landing Page",
         path="/",
         response_model=LandingPage,
         response_model_exclude_unset=True,
         response_model_exclude_none=True,
         methods=["GET"],
         endpoint=create_endpoint_with_depends(self.client.landing_page,
                                               EmptyRequest),
     )
     router.add_api_route(
         name="Conformance Classes",
         path="/conformance",
         response_model=ConformanceClasses,
         response_model_exclude_unset=True,
         response_model_exclude_none=True,
         methods=["GET"],
         endpoint=create_endpoint_with_depends(self.client.conformance,
                                               EmptyRequest),
     )
     router.add_api_route(
         name="Get Item",
         path="/collections/{collectionId}/items/{itemId}",
         response_model=schemas.Item,
         response_model_exclude_unset=True,
         response_model_exclude_none=True,
         methods=["GET"],
         endpoint=create_endpoint_with_depends(self.client.get_item,
                                               ItemUri),
     )
     router.add_api_route(
         name="Search",
         path="/search",
         response_model=ItemCollection if not fields_ext else None,
         response_model_exclude_unset=True,
         response_model_exclude_none=True,
         methods=["POST"],
         endpoint=create_endpoint_from_model(self.client.post_search,
                                             search_request_model),
     ),
     router.add_api_route(
         name="Search",
         path="/search",
         response_model=ItemCollection if not fields_ext else None,
         response_model_exclude_unset=True,
         response_model_exclude_none=True,
         methods=["GET"],
         endpoint=create_endpoint_with_depends(self.client.get_search,
                                               SearchGetRequest),
     )
     router.add_api_route(
         name="Get Collections",
         path="/collections",
         response_model=List[schemas.Collection],
         response_model_exclude_unset=True,
         response_model_exclude_none=True,
         methods=["GET"],
         endpoint=create_endpoint_with_depends(self.client.all_collections,
                                               EmptyRequest),
     )
     router.add_api_route(
         name="Get Collection",
         path="/collections/{collectionId}",
         response_model=schemas.Collection,
         response_model_exclude_unset=True,
         response_model_exclude_none=True,
         methods=["GET"],
         endpoint=create_endpoint_with_depends(self.client.get_collection,
                                               CollectionUri),
     )
     router.add_api_route(
         name="Get ItemCollection",
         path="/collections/{collectionId}/items",
         response_model=ItemCollection,
         response_model_exclude_unset=True,
         response_model_exclude_none=True,
         methods=["GET"],
         endpoint=create_endpoint_with_depends(self.client.item_collection,
                                               ItemCollectionUri),
     )
     self.app.include_router(router)