def test_load_instance_no_relation(self, task): schema = AutoMarshmallowSchema.generate_schema(Task)() dumped_task = schema.dump(task) loaded = schema.load_instance(dumped_task) self.verify_objects(task, loaded)
def create(self, objects: Union[T, List[T]], load_only=None, batched=False) -> Union[T, List[T]]: """ Create an object of type specified by Meta object in `schema`. :return: An object of type specified by Meta object in `schema` """ res = list() schema = AutoMarshmallowSchema.get_schema(type(objects[0])) load_only_ = self._load_only_fields(load_only or list(), schema) endpoint = self.make_endpoint(schema) init_schema = schema(many=True) for c in chunk(objects, INTERFACE_CHUNK_SIZE): dump = serialize(c, schema, load_only=load_only_, many=True) req = self._make_request("put", endpoint, json=dump, params={"batched": batched}) res.extend(init_schema.load_instance(self._send_request(req))) if any(res) and len(res) < 2: return res[0] return res
def test_schema_no_relationship_data(self, task_with_relationship): schema = AutoMarshmallowSchema.generate_schema(TaskWithRelationShip)() task_with_relationship.attachments = list() dumped = schema.dump(task_with_relationship) loaded = schema.load_instance(dumped) self.verify_objects(task_with_relationship, loaded)
def test_load_model(self, task): schema = AutoMarshmallowSchema.generate_schema(Task) dumped_task = schema().dump(task) loaded = schema().load(dumped_task) for k, v in vars(task).items(): if k.startswith("_"): continue assert v == loaded[k]
def test_dump_model(self, task): schema = AutoMarshmallowSchema.generate_schema(Task) dumped_task = schema().dump(task) expected = { "id": task.id, "name": task.name, "finished_by": task.finished_by.isoformat(), "type": task.type.name, } assert dumped_task == expected
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 test_nested_structure(self): schema = AutoMarshmallowSchema.generate_schema(User)() user = User(id=1, name="Testing 123") address = Address(id=1, user_id=user.id, value="Testing street 1") house_picture = HousePicture(id=1, address_id=address.id, location="C:/test") address.house_pictures = [house_picture] user.address = [address] dumped = schema.dump(user) loaded = schema.load_instance(dumped) self.verify_objects(user, loaded)
def test_schema_with_relationship(self, attachment, task_with_relationship): schema = AutoMarshmallowSchema.generate_schema(TaskWithRelationShip) expected = { "id": task_with_relationship.id, "name": task_with_relationship.name, "finished_by": task_with_relationship.finished_by, "type": task_with_relationship.type, "attachments": [{"id": attachment.id, "task_id": attachment.task_id, "location": attachment.location}], } dumped = schema().dump(task_with_relationship) loaded = schema().load(dumped) assert expected == loaded
def delete(self, objects: Union[T, List[T]]) -> int: """ Deletes an object with `id_` of type specified by Meta object in `schema`. :return: The number of affected items """ deleted = 0 schema = AutoMarshmallowSchema.get_schema(type(objects[0])) endpoint = self.make_endpoint(schema) for obj in objects: req = self._make_request("delete", endpoint=endpoint, params={"id": obj.id}) resp = self._send_request(req) deleted += resp["deleted"] return deleted
def update(self, objects: Union[T, List[T]], batched=False) -> List[T]: """ Updates an object with the new values. :return: The update object """ res = list() schema = AutoMarshmallowSchema.get_schema(type(objects[0])) endpoint = self.make_endpoint(schema) init_schema = schema(many=True) for c in chunk(objects, INTERFACE_CHUNK_SIZE): dump = serialize(c, schema, many=True) req = self._make_request("patch", endpoint, json=dump, params={"batched": batched}) res.extend(init_schema.load_instance(self._send_request(req))) return res
def get(self, objtype: Type[T], f: Callable[[T], bool] = None, one=False, operations: str = None) -> Union[T, List[T], None]: """ Get an object of type specified by Meta object in `schema`. :param objtype: The object type to get :param f: Function for designing a filter :param one: Whether to get only one :param operations: Whether to apply any special operations :return: The object of type specified by Meta object in `schema`, or all """ json = None schema = AutoMarshmallowSchema.get_schema(objtype) if f: fb = QueryBuilder(schema.Meta.model) json = fb.to_string(f(schema.Meta.model)) req = self._make_request("get", endpoint=self.make_endpoint(schema), params={ "filter": json, "ops": operations }) init_schema = schema(many=True) res = init_schema.load_instance(self._send_request(req)) if not one: return res if len(res) > 1: raise ValueError("More than 1 elements exist!") return next(iter(res), None)
def test_load_instance_with_relationship(self, task_with_relationship): schema = AutoMarshmallowSchema.generate_schema(TaskWithRelationShip)() dumped = schema.dump(task_with_relationship) loaded = schema.load_instance(dumped) self.verify_objects(task_with_relationship, loaded)
def test_generate_schema(self): schema = AutoMarshmallowSchema.generate_schema(Task) assert Task == schema.Meta.model
def test_generate_schema_for_subclasses(self): subclasses_and_schemas = AutoMarshmallowSchema.generate_schemas_for_subclasses(Base) assert len(subclasses_and_schemas) == len(Base.__subclasses__())