使peewee模型JSON可序列化?

时间:2017-05-11 04:39:05

标签: python json serialization flask peewee

我一直在开发一个小型网络应用程序,如果我使用电子邮件验证,我认为这是一个好主意。好吧,当我试图添加电子邮件验证时,我有点破坏了我的代码......我一直在跟踪,告诉我以下内容:

  

TypeError:<'peewee.CharField对象位于0x7f46c6a7ba50>不是JSON可序列化的

我得出结论,我需要让我的用户模型JSON可序列化,但我不是100%确定这是我需要做的。即使我是对的,我也不知道该怎么做。

这是我的用户模型:

class User(UserMixin, Model):
    username = CharField(unique=True)
    password = CharField(max_length=20)
    email = CharField(unique=True)
    confirmed = BooleanField(default=False)
    confirmed_on = DateTimeField(default=datetime.datetime.now())
    joined_at = DateTimeField(default=datetime.datetime.now)

    class Meta:
        database = db
        order_by = ('-joined_at',)

    @classmethod
    def create_user(cls, username, email, password, confirmed):
        try:
            with db.transaction():
            cls.create(
                username=username,
                email=email,
                password=generate_password_hash(password),
                confirmed=False)
        except IntegrityError:
            raise ValueError("User already exists")

就我所尝试的电子邮件验证而言:

def generate_serializer(secret_key=None):
    return URLSafeTimedSerializer(app.config['SECRET_KEY'])


def generate_activation_url(user):
    serializer = generate_serializer()
    token = serializer.dumps(user.username)
    return url_for('activate_user', token=token, _external=True)

@app.route('/', methods=('GET', 'POST'))
def index():
    form = forms.RegisterForm()
    if form.validate_on_submit():
        models.User.create_user(
            username=form.username.data,
            email=form.email.data,
            password=form.password.data,
            confirmed=False
        )
    token = generate_activation_url(models.User)
    msg =Message(render_template('activation_email.html', token=token),
                                  recipients=[models.User.email])
    mail.send(msg)

    return render_template('activate.html', user=models.User)
return render_template('index.html', form=form)


@app.route('/activate/<token>')
def activate_user(token, expiration=3600):
    serializer = generate_serializer()
    try:
        serializer.loads(token, salt=app.config[
                                   'SECRET_KEY'], max_age=expiration)
    except (BadSignature, SignatureExpired):
        abort(404)

    models.User.confirmed = True
    flash('User activated')
    return redirect(url_for('index'))

0 个答案:

没有答案