def from_dict(cls, d): """ Special from_dict to autoload the pydantic model from the location string """ model = d.get("model") if isinstance(model, str): module_path = ".".join(model.split(".")[:-1]) class_name = model.split(".")[-1] model = dynamic_import(module_path, class_name) assert issubclass( model, BaseModel), "The resource model has to be a PyDantic Model" d["model"] = model cls(**d)
def __init__( self, store: Store, model: Union[BaseModel, str], tags: Optional[List[str]] = None, query_operators: Optional[List[QueryOperator]] = None, description: str = None, ): """ Args: store: The Maggma Store to get data from model: the pydantic model to apply to the documents from the Store This can be a string with a full python path to a model or an actuall pydantic Model if this is being instantied in python code. Serializing this via Monty will autoconvert the pydantic model into a python path string tags: list of tags for the Endpoint query_operators: operators for the query language description: an explanation of wht does this resource do """ self.store = store self.tags = tags or [] self.description = description self.model: BaseModel = BaseModel() if isinstance(model, str): module_path = ".".join(model.split(".")[:-1]) class_name = model.split(".")[-1] self.model = dynamic_import(module_path, class_name) else: self.model = model self.query_operators = ( query_operators if query_operators is not None else [ PaginationQuery(), SparseFieldsQuery(self.model, default_fields=[self.store.key]), DefaultDynamicQuery(self.model), ] ) self.response_model = Response[self.model] # type: ignore self.router = APIRouter() self.prepare_endpoint()
def load(self, endpoint, prefix: str = "/"): """ loads an endpoint dynamically. The endpoint can be either a path to an EndpointCluster instance, or a EndpointCluster instance Args: endpoint: Returns: None Raises: ValueError -- if the endpoint is not a path to an EndpointCluster or it is not an EndpointCluster """ if isinstance(endpoint, str): module_path = ".".join(endpoint.split(".")[:-1]) class_name = endpoint.split(".")[-1] new_endpoint = dynamic_import(module_path, class_name) self.__setitem__(prefix, new_endpoint) elif isclass(endpoint) and issubclass(endpoint, Resource): self.__setitem__(prefix, endpoint) else: raise ValueError( "endpont has to be a EndpointCluster instance or a path to EndpointCluster instance" )