【问题标题】:Long Polling in Python Flask with SQLALCHEMY使用 SQLALCHEMY 在 Python Flask 中进行长轮询
【发布时间】:2015-04-09 11:28:52
【问题描述】:

我正在烧瓶框架下使用 python 开发一个项目。我也在使用 SQLAlchemy 来做所有的数据库事务。

我正在进行长时间轮询以检查数据库表中的新条目。我遇到了 SQLAlchemy 的问题

比较日期时间似乎不起作用。一个有意义的解释是 SQLAlchemy 正在缓存结果,但根据我在网上阅读的内容,情况并非如此。

这是我的代码(对于糟糕的格式无法在 stackoverflow 上得到它表示歉意):

@app.route('/poll')
def poll():
now = datetime.utcnow()
print(models.dump_datetime(now))

timeout = time.time() + 60*1
while time.time() <= timeout:
    time.sleep(0.5)
    db.session.expire_all()
    check = AuditLogEntry.query.filter((AuditLogEntry.datetime >= now) 
    & ((AuditLogEntry.action == "action1") | (AuditLogEntry.action == "action2")))
    if(check.count() > 0):
        for c in check:
            print(c.to_dict())
        break

return "DONE"

所以当第一次调用 poll() 函数时,它会将时间记录为日期时间。然后它在数据库中搜索日期时间晚于now 的任何行。如果它找到了,它应该将它打印到控制台,并打破循环。

但是,简单地说,它不起作用。添加新行时,时间在now 中存储的时间之后,它不会注意到它。

另外,当我测试以确保 now 正确,并且与 AuditLogEntry.datetime with the following code, I can print the count oftest` 中的日期时间相当时,它是我表中的行数。所以它起作用了。

 test = AuditLogEntry.query.filter((AuditLogEntry.datetime < now) & ((AuditLogEntry.action == "action1") |
                                                                         (AuditLogEntry.action == "action2")))
print(test.count())

db.session.expire_all() 似乎不起作用。结果集似乎没有改变。

任何帮助将不胜感激!!!

【问题讨论】:

    标签: python mysql flask sqlalchemy long-polling


    【解决方案1】:

    我尝试删除行 db.session.expire_all() 并在 SQLAlchemy 查询后添加 db.session.commit,它可以工作。

    我不完全确定它为什么会起作用,如果有人可以向我解释一下,我会很高兴:)

    【讨论】:

      猜你喜欢
      • 2015-06-13
      • 2014-10-09
      • 2017-05-15
      • 2018-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-02
      相关资源
      最近更新 更多