【问题标题】:default datetime.now value on entries doesnt change unless flask server restarted除非重新启动烧瓶服务器,否则条目的默认 datetime.now 值不会改变
【发布时间】:2020-08-24 08:46:45
【问题描述】:

我注意到当我在表单页面中提交条目时,除非重新启动,否则 date_input 将在随后的提交中重复。为什么会这样?我发誓重复的时间相隔几分钟,但似乎提交的时间仅来自服务器重启。我也在使用flask-sqlalchemy。

models.py

class Entry(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), unique=True, nullable=False)
    date_input = db.Column(db.DateTime, nullable=False, default=datetime.now(tz=pytz.timezone('Asia/Manila')))
Entry.date_input timestamp results (copy-pasted from cli)

 1. 2020-05-09 00:59:07.269489
 2. 2020-05-09 01:08:56.676228
 3. 2020-05-09 01:10:44.032547
 4. 2020-05-09 01:10:44.032547
 5. 2020-05-09 01:10:44.032547
 6. 2020-05-09 01:10:44.032547
 7. 2020-05-09 01:23:28.636399
 8. 2020-05-09 01:23:28.636399
 9. 2020-05-09 01:23:28.636399
Actual POST logs (copy-pasted from cli)

 1. 127.0.0.1 - - [09/May/2020 01:00:55]
 2. 127.0.0.1 - - [09/May/2020 01:09:25]
 3. 127.0.0.1 - - [09/May/2020 01:14:49]
 4. 127.0.0.1 - - [09/May/2020 01:18:07]
 5. 127.0.0.1 - - [09/May/2020 01:21:39]
 6. 127.0.0.1 - - [09/May/2020 01:23:46]
 7. 127.0.0.1 - - [09/May/2020 01:25:14]
 8. 127.0.0.1 - - [09/May/2020 01:25:14]
 9. 127.0.0.1 - - [09/May/2020 01:25:56]
Server restarts
-I took the timestamps from the first GET result after running the server. 
 The initial running itself doesnt have time indicated

 1. 127.0.0.1 - - [09/May/2020 00:59:11]
 2. 127.0.0.1 - - [09/May/2020 01:09:25]
 3. 127.0.0.1 - - [09/May/2020 01:10:50]
 4. 127.0.0.1 - - [09/May/2020 01:23:31]

【问题讨论】:

    标签: python datetime flask flask-sqlalchemy pytz


    【解决方案1】:

    注意固定默认值和默认函数(在需要时提供值)之间的区别。 documentation 显示了 datetime.now 的示例。

    您当前的代码可以重写为:

    dt = datetime.now(tz=pytz.timezone('Asia/Manila')) # evaluated once
    date_input = db.Column(db.DateTime, nullable=False, default=dt)
    

    要修复代码,请将表达式替换为函数,例如default=lambda: datetime.now(tz=...)

    【讨论】:

      猜你喜欢
      • 2011-05-26
      • 2015-03-09
      • 2021-12-30
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      • 2015-03-17
      • 2020-09-05
      • 1970-01-01
      相关资源
      最近更新 更多