python - 如何在 Peewee 中创建一个将其值转换为 MD5 的字段

标签 python mysql python-3.x orm peewee

我在 Peewee 中定义了如下模型:

class User(Model):
    username = CharField(null=False)
    password = FixedCharField(null=False, max_length=32)

问题是我希望将字段 password 散列为 MD5。例如:

user = User.create(username="whatever", password="whatever")
user.password # returns '008c5926ca861023c1d2a36653fd88e2'

我使用 MySQL,它已经有一个 MD5() 函数。所以……

  • 有没有办法使用 MySQL 的内置 MD5() 函数?或者……
  • 是否有一种内置方法可以像 Django 一样在某种程度上操纵 Model::create 方法?

环境

  • MySQL 5.7.21
  • python 3.5.2
  • Peewee 3.1.0

最佳答案

来自peewee documentation hacks页:

def get_hexdigest(salt, raw_password):
    data = salt + raw_password
    return sha1(data.encode('utf8')).hexdigest()

@db.func()
def make_password(raw_password):
    salt = get_hexdigest(str(random()), str(random()))[:5]
    hsh = get_hexdigest(salt, raw_password)
    return '%s$%s' % (salt, hsh)

@db.func()
def check_password(raw_password, enc_password):
    salt, hsh = enc_password.split('$', 1)
    return hsh == get_hexdigest(salt, raw_password)


query = User.insert(
    username='charlie',
    password=fn.make_password('testing')).execute()

关于python - 如何在 Peewee 中创建一个将其值转换为 MD5 的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49684136/

相关文章:

python - 如何通过索引一次将多个值插入到列表中

Python 扭曲 : how to schedule?

python - Pandas 使用未对齐的索引进行选择

php - 拉拉维尔 5.2 : defined user and get information from other database table

html - SQL 查询内联表,打印到 HTML <select> 标签

mysql - Joomla Jdatabase select 语句不工作

python - Jupyter Notebook - 在函数内部绘图 - 图未绘制

python - 使用时间模块测试复杂性

Python - 函数继承 - 更改关键字参数

python - pd.apply 中不同的 np.std 行为