def get_health() -> str:
    try:
        ProductsTable.query.limit(1).value(ProductsTable.name)
    except OperationalError as e:
        logger.warning("Health endpoint returned: notok!")
        logger.debug("Health endpoint error details", error=str(e))
        raise_status(HTTPStatus.INTERNAL_SERVER_ERROR)
    return "OK"
Exemple #2
0
def delete(cls: Type, primary_key: UUID) -> None:
    pk = list({
        k: v
        for k, v in cls.__table__.columns._data.items() if v.primary_key
    }.keys())[0]
    row_count = cls.query.filter(cls.__dict__[pk] == primary_key).delete()
    db.session.commit()
    if row_count > 0:
        return None
    else:
        raise_status(HTTPStatus.NOT_FOUND)
Exemple #3
0
def update(cls: Type, base_model: BaseModel) -> None:
    json_dict = transform_json(base_model.dict())
    pk = list({
        k: v
        for k, v in cls.__table__.columns._data.items() if v.primary_key
    }.keys())[0]
    instance = cls.query.filter(cls.__dict__[pk] == json_dict[pk])
    if not instance:
        raise_status(HTTPStatus.NOT_FOUND)
    json_dict = validate(cls, json_dict, is_new_instance=False)
    try:
        _merge(cls, json_dict)
    except Exception as e:
        raise_status(HTTPStatus.INTERNAL_SERVER_ERROR, str(e))
Exemple #4
0
def validate(cls: Type, json_dict: Dict, is_new_instance: bool = True) -> Dict:
    required_columns = {
        k: v
        for k, v in cls.__table__.columns._data.items()
        if not v.nullable and (not v.server_default or v.primary_key)
    }
    required_attributes: Iterable[str] = required_columns.keys()
    if is_new_instance:
        required_attributes = filter(
            lambda k: not required_columns[k].primary_key, required_attributes)
    missing_attributes = list(
        filter(lambda key: key not in json_dict, required_attributes))
    if len(missing_attributes) != 0:
        raise_status(
            HTTPStatus.BAD_REQUEST,
            f"Missing attributes '{', '.join(missing_attributes)}' for {cls.__name__}",
        )
    return json_dict
def get_by_id(id: UUID) -> ProductTypesTable:
    product_type = product_type_crud.get(id)
    if not product_type:
        raise_status(HTTPStatus.NOT_FOUND, f"ProductType id {id} not found")
    return product_type
def get_by_id(id: UUID) -> MapsTable:
    map = map_crud.get(id)
    if not map:
        raise_status(HTTPStatus.NOT_FOUND, f"Map id {id} not found")
    return map
Exemple #7
0
def _query_with_filters(
    response: Response,
    model: BaseModel,
    query: Query,
    range: Optional[List[int]] = None,
    sort: Optional[List[str]] = None,
    filters: Optional[List[str]] = None,
) -> List:
    if filters is not None:
        for filter in chunked(filters, 2):
            if filter and len(filter) == 2:
                field = filter[0]
                value = filter[1]
                value_as_bool = value.lower() in (
                    "yes",
                    "y",
                    "ye",
                    "true",
                    "1",
                    "ja",
                    "insync",
                )
                if value is not None:
                    if field.endswith("_gt"):
                        query = query.filter(
                            model.__dict__[field[:-3]] > value)
                    elif field.endswith("_gte"):
                        query = query.filter(
                            model.__dict__[field[:-4]] >= value)
                    elif field.endswith("_lte"):
                        query = query.filter(
                            model.__dict__[field[:-4]] <= value)
                    elif field.endswith("_lt"):
                        query = query.filter(
                            model.__dict__[field[:-3]] < value)
                    elif field.endswith("_ne"):
                        query = query.filter(
                            model.__dict__[field[:-3]] != value)
                    elif field == "tsv":
                        logger.debug("Running full-text search query.",
                                     value=value)
                        query = query.search(value)
                    elif field in model.__dict__:
                        query = query.filter(
                            cast(model.__dict__[field],
                                 String).ilike("%" + value + "%"))

    if sort is not None and len(sort) >= 2:
        for sort in chunked(sort, 2):
            if sort and len(sort) == 2:
                if sort[1].upper() == "DESC":
                    query = query.order_by(
                        expression.desc(model.__dict__[sort[0]]))
                else:
                    query = query.order_by(
                        expression.asc(model.__dict__[sort[0]]))

    if range is not None and len(range) == 2:
        try:
            range_start = int(range[0])
            range_end = int(range[1])
            assert range_start < range_end
        except (ValueError, AssertionError):
            msg = "Invalid range parameters"
            logger.exception(msg)
            raise_status(HTTPStatus.BAD_REQUEST, msg)
        total = query.count()
        query = query.slice(range_start, range_end)

        response.headers[
            "Content-Range"] = f"items {range_start}-{range_end}/{total}"

    return query.all()
Exemple #8
0
def create_or_update(cls: Type, obj: BaseModel) -> None:
    try:
        json_dict = transform_json(obj.dict())
        _merge(cls, json_dict)
    except Exception as e:
        raise_status(HTTPStatus.INTERNAL_SERVER_ERROR, str(e))
Exemple #9
0
def save(cls: Type, json_data: BaseModel) -> None:
    try:
        json_dict = transform_json(json_data.dict())
        _merge(cls, json_dict)
    except Exception as e:
        raise_status(HTTPStatus.INTERNAL_SERVER_ERROR, str(e))