Представь, что ты программист Fast API. У меня есть модель: class Employee(Base):…
- User
Представь, что ты программист Fast API. У меня есть модель:
class Employee(Base): tablename = "employees"
"""System info""" id = Column(Integer, primary_key=True, index=True) is_active = Column(Boolean, default=False, nullable=False, comment="Статус") is_owner = Column(Boolean, default=True, nullable=False, comment="Владелец компании") role = Column(String, nullable=False, default='CA', comment="Роль сотрудника") hashed_password = Column(String, nullable=True, comment="Пароль") email_change_token = Column(String, nullable=True, comment="Token смены email") email_change_token_created_at = Column(DateTime(timezone=True), nullable=True, comment="Дата создания токена смены email") email_change_token_new_email = Column(EmailType, unique=True, nullable=True, comment="Новый Email") phone_change_code = Column(String(6), nullable=True, comment="Код смены телефона") phone_change_code_created_at = Column(DateTime(timezone=True), nullable=True, comment="Дата создания кода смены телефона") new_phone = Column(String, nullable=True, comment="Новый телефон") """Основная информация""" first_name = Column(String, nullable=True, comment="Имя") last_name = Column(String, nullable=True, comment="Фамилия") patronymic = Column(String, nullable=True, comment="Отчество") email = Column(EmailType, unique=True, index=True, nullable=True, comment="Email") email_is_missing = Column(Boolean, nullable=True, comment="Отсутствие Email-a") send_invitation = Column(Boolean, nullable=True, comment="Пригласить сотрудника") phone = Column(String, unique=True, index=True, nullable=True, comment="Телефон") position_enbek = Column(String, nullable=True, comment="Должность в Enbek") department = Column(String, nullable=True, comment="Отдел") supervisor_id = Column(Integer, ForeignKey('employees.id'), nullable=True, comment="Идентификатор руководителя") supervisor = relationship("Employee", remote_side=[id], backref="subordinates") inn = Column(String, nullable=True, comment="ИНН") """Рабочие данные""" position_hrm = Column(String, nullable=True, comment="Должность HRM") start_date = Column(DateTime(timezone=True), nullable=True, comment="Дата начала работы") contract_number = Column(String, nullable=True, comment="Номер договора") contract_term = Column(String, nullable=True, comment="Срок действия договора") contract_date_of_signing = Column(Date, nullable=True, comment="Дата подписания договора") contract_date_expiration = Column(Date, nullable=True, comment="Дата окончания договора") contract_type = Column(String, nullable=True, comment="Вид договора") probation = Column(Integer, nullable=True, comment="Испытательный срок") type_of_work = Column(String, nullable=True, comment="Вид работы") form_of_employment = Column(String, nullable=True, comment="Форма занятости") working_hours = Column(String, nullable=True, comment="Режим рабочего времени") work_schedule = Column(String, nullable=True, comment="Рабочий график") tariff_rate = Column(Float, nullable=True, comment="Тарифная ставка") work_address = Column(String, nullable=True, comment="Адрес места работы") type_of_calculation = Column(String, nullable=True, comment="Вид расчета") salary = Column(Integer, nullable=True, comment="Оклад") allowances = relationship(Allowance, back_populates="employee", cascade="all, delete-orphan") unique_employee_number = Column(Integer, nullable=True, comment="Уникальный номер сотрудника") is_pensioner = Column(Boolean, default=False, nullable=True, comment="Пенсионер") bank_requisites = relationship(BankRequisites, back_populates="employee", uselist=False) employment_contract_file = Column(String, nullable=True, comment="Файл трудового договора") """Персональные данные""" birth_date = Column(Date, nullable=True, comment="Дата рождения") gender = Column(String, nullable=True, comment="Пол") identification_documents = relationship(IdentificationDocument, back_populates="employee", cascade="all, delete-orphan") nationality = Column(String, nullable=True, comment="Национальность") citizenship = Column(String, nullable=True, comment="Гражданство") birth_place = relationship(BirthPlace, back_populates="employee", uselist=False) registration_address = relationship(RegistrationAddress, back_populates="employee", uselist=False) family_data = relationship(FamilyData, back_populates="employee", uselist=False) military_registration = relationship(MilitaryRegistration, back_populates="employee", uselist=False) photo = Column(String, nullable=True, comment="Фото") """Профессиональные данные""" education = relationship(Education, back_populates="employee", cascade="all, delete-orphan") courses = relationship(Courses, back_populates="employee", cascade="all, delete-orphan") language_proficiency = relationship(LanguageProficiency, back_populates="employee", cascade="all, delete-orphan") work_experiences = relationship(WorkExperience, back_populates="employee", cascade="all, delete-orphan") professional_skills = Column(String, nullable=True, comment="Профессиональные навыки") personal_qualities = Column(String, nullable=True, comment="Личные качества") """Контактные данные""" contact_phone = Column(String, unique=True, nullable=True, comment="Телефон") contact_email = Column(EmailType, unique=True, index=True, nullable=True, comment="Email") is_matches_registration_address = Column(Boolean, nullable=True, comment="Адрес проживания") residential_address = relationship(ResidentialAddress, back_populates="employee", uselist=False) emergency_contact_name = Column(String, nullable=True, comment="Контакт на ЧС, имя") emergency_contact_phone = Column(String, nullable=True, comment="Телефон контакта на ЧС") """Компания""" company_id = Column(Integer, ForeignKey('companies.id')) company = relationship(Company, back_populates="employees") metadata = meta def __repr__(self): return f"<User(id={self.id}, email='{self.email}')>"и метод создания этой модели. Как мне шифровать все данные этой модели в базе данных при создании? база данных Postgresql.
- Assistant
Для шифрования данных в базе данных Postgresql при создании модели Employee в FastAPI, вам понадобится использовать криптографический алгоритм, такой как AES (Advanced Encryption Standard) или SHA-256. Вот пример как можно зашифровать данные при создании экземпляра модели:
- Импортируйте необходимые модули для шифрования:
from sqlalchemy.ext.hybrid import hybrid_property from cryptography.fernet import Fernet- Создайте ключ для шифрования. Ключ должен быть длиной 32 байта:
key = b'your_secret_key_here' fernet = Fernet(key)- Добавьте декоратор
@hybrid_propertyк каждому полю модели, которое вы хотите зашифровать:
@hybrid_property def email(self): if self._email: return fernet.decrypt(self._email).decode() else: return None @email.setter def email(self, value): self._email = fernet.encrypt(value.encode())- В вашем методе создания модели используйте зашифрованные значения:
def create_employee(employee_data: Dict) -> Employee: employee = Employee() employee.email = employee_data['email'] # Другие поля модели session.add(employee) session.commit() return employeeТеперь все данные модели, отмеченные декоратором
@hybrid_property, будут автоматически шифроваться перед сохранением в базе данных и дешифроваться при получении из базы данных. Помните, что вы также должны сохранять ключ шифрования в безопасном месте и использовать его для дешифрования данных при необходимости.