如何在python类中基于现有属性生成其他属性?

时间:2013-11-29 20:09:24

标签: python sqlalchemy flask-sqlalchemy

我在SQLAlchemy中有一个类,用于存储我的用户的联系人详细信息:

# UserExtension extension creates a ForeignKey and relationship to users
# which is also the PK
class Contact(UserExtension, db.Model):
    __tablename__ = 'user_contact'

    _email = Column(String(254), nullable=True, unique=True)
    _telephone = Column(String, nullable=True, unique=True)
    _crsid = Column(String, nullable=True, unique=True)
    ...

为了防止某人意外地将其联系方式或第三方注册的人员无效,我希望通过向必须回复的相关地址发送激活码来验证这些字段中的每项更改。我想自动生成这样的东西:

    ...
    @property
    def email(self):
        return self._email
    @email.setter
    def email(self, email):
        change_request = EmailChange(self, email)
        db.session.add(change_request)
        db.commit()

class EmailUpdate(db.Model):
    TOKEN_LENGTH = 32 # Ideally adjustable for each detail type
    def make_token(cls):
        return ''.join(random.choice(string.ascii_letters)
            for i in range(cls.TOKEN_LENGTH))

    new_email = Column(String)
    token = Column(String, default=make_token)
    contact_id = Column(UUID, ForeignKey('user_contact.user_id'))
    contact = relationship(Contact, backref='pending_email_update')

    def __init__(self, contact, new_email):
        self.new_email = new_email
        self.contact = contact

    def apply(self, token):
        if token != hashlib.sha256(self.new_email + self.token):
            raise ValueError("Invalid token.")
        else:
            self.contact._email = self.new_email
            db.delete(self)
            db.session.commit()

是否可以包装(或某事?)一个类,以便为每个字段生成?

0 个答案:

没有答案