python - 狗书中的用户资料一章,User模型的注册时间member_since属性每次本地调试时发生变化是什么原因?
PHP中文网
PHP中文网 2017-04-18 09:44:05
0
1
369

先贴上相关代码,就是狗书的源码
app/models.py

class User(UserMixin, db.Model):
    member_since = db.Column(db.DateTime(), default=datetime.utcnow)
    last_seen = db.Column(db.DateTime(), default=datetime.utcnow)
    
    def ping(self):
        self.last_seen = datetime.utcnow()
        db.session.add(self)

app/auth/views.py

@auth.before_app_request
def before_request():
    if current_user.is_authenticated:
        current_user.ping()

代码是在本地测试的,我是9月份的时候添加的3个用户,但发现每次run,用户资料页的member_since值都会刷新成当天的日期,last_seen值倒是没问题。请问是哪里出问题了?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(1)
洪涛

The rendering template should be written as the following code
I don’t know what the author’s code looks like, it’s best to post it and take a look

<p>Member since {{ moment(user.member_since).format('L') }}.Last seen {{ moment(user.last_seen).fromNow() }}.</p>

PS: After discussion and exchange with the original poster, I found that it should be in models. The time when the attribute member_since was added to the database was after the user was created, so there was no data in it, and during the previous rendering, it caused member_since = db in the model. The datetime.utcnow function of .Column(db.DateTime(), default=datetime.utcnow) was triggered and the date was refreshed, but it was not entered into the database by db.session.add, resulting in datetime.utcnow being triggered every time you log in. function, so it is the latest date every time.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!