Esempio n. 1
0
    async def deserialize(self,
                          data: t.Dict[str, t.Any],
                          partial: bool = False) -> DeserializedData:
        deserialized_data = await super().deserialize(data, partial)
        username = deserialized_data['username']
        raw_password = deserialized_data['password']
        db = self.context['request'].app.mongo
        user = await UsersQS(db=db).get_by_username(username)

        if not user:
            raise ValidationError('Wrong credentials.')

        is_correct_password = verify_password(raw_password, user.password)

        if not is_correct_password:
            raise ValidationError('Wrong credentials.')

        deserialized_data.update({
            'user_uuid':
            user.uuid,
            'token':
            generate_jwt(
                exp_in_secs=settings.JWT_EXP_SECONDS,
                secret_key=settings.SECRET_KEY,
                payload={'user_id': user.uuid},
            ),
        })

        return deserialized_data
Esempio n. 2
0
    async def deserialize(
            self,
            data: t.Mapping[str, t.Any],
            partial: bool = False,
    ) -> DeserializedData:
        if not isinstance(data, abc_collections.Mapping):
            raise ValidationError(
                f'Expected a dictionary, but got {type(data).__name__}'
            )

        deserialized_data = {}

        for field_name, field_obj in self.fields_map.items():
            if field_obj.serialization_only:
                continue

            load_from = field_obj.load_from or field_name
            loaded_value = data.get(load_from, field_obj.value_for_missing)

            if not loaded_value and partial:
                continue

            if not loaded_value and field_obj.is_required and not field_obj.default:
                raise ValidationError(details=f'{load_from} field is required.')

            serialized_value = await field_obj.deserialize(loaded_value)
            load_to = field_obj.load_to or field_name
            deserialized_data[load_to] = serialized_value

        return deserialized_data
Esempio n. 3
0
    def from_id(self, obj_id: int) -> 'Service':
        obj = session.query(self.model_class).get(obj_id)

        if not obj:
            raise ValidationError('Input data is incorrect.')

        self.obj = obj
        return self
Esempio n. 4
0
    def change_status(self, status: str) -> None:
        if self.is_deleted:
            raise ValidationError('Server is deleted.')

        self.obj.status = status
        session.commit()

        current_app.logger.info(f'Сервер с идентификатором {self.obj.id} изменил статус на {status}')
Esempio n. 5
0
    def add_server(self, server: Server) -> None:
        if not self.has_free_slots():
            raise ValidationError('The rack has not free slots')

        session.add(server)
        session.commit()

        current_app.logger.info(f'В стойку с идентификатором {self.obj.id} добавлен сервер')
Esempio n. 6
0
    def pay(self) -> None:
        if self.is_deleted:
            raise ValidationError('Server is deleted.')

        # имитация оплаты
        threading.Thread(
            target=self._pay_imitation,
            kwargs={'server_id': self.obj.id},
        ).start()

        self.mark_as_paid()
        self.obj.paid_at = datetime.datetime.now()
        session.commit()

        current_app.logger.debug(f'Оплачен сервер с идентификатором {self.obj.id}')
Esempio n. 7
0
    async def deserialize(self,
                          data: t.Dict[str, t.Any],
                          partial: bool = False) -> DeserializedData:
        deserialized_data = await super().deserialize(data, partial=partial)

        username = deserialized_data['username']
        db = self.context['request'].app.mongo
        user = await UsersQS(db=db).get_by_username(username)

        if user:
            raise ValidationError('This username is already in use.')

        hashed_password = hash_password(deserialized_data['password'])
        deserialized_data['password'] = hashed_password
        return deserialized_data
Esempio n. 8
0
    def serialize(self, data: t.Mapping[str, t.Any]) -> dict:
        if not isinstance(data, abc_collections.Mapping):
            raise ValidationError(
                f'Expected a dictionary, but got {type(data).__name__}')

        serialized_data = {}

        for field_name, field_obj in self.fields_map.items():
            if field_obj.deserialization_only:
                continue

            load_from = field_obj.load_from or field_name
            loaded_value = data.get(load_from, field_obj.value_for_missing)
            serialized_value = field_obj.serialize(loaded_value)
            load_to = field_obj.load_to or field_name
            serialized_data[load_to] = serialized_value

        return serialized_data
 def __call__(self, value, field_name):
     if value not in self.choices:
         raise ValidationError(
             details=f'{field_name} should be one of {self.choices}')
Esempio n. 10
0
 def to_internal_type(self, value: t.Any) -> int:
     try:
         return int(value)
     except ValueError:
         raise ValidationError(f'{self.name} should be an integer')
Esempio n. 11
0
    def to_internal_type(self, value: t.Any) -> str:
        if not isinstance(value, (str, int, float)):
            raise ValidationError(f"{self.name} should be string type")

        return str(value)