2014-02-12 61 views
0

我有以下幾點:爲什麼SQLAlchemy的執行更新不工作

@periodic_task(run_every=crontab(minute="*/1")) 
def PeriodicUpdateAgentLastRica(): 
    query = """update agents 
      inner join 
       (select sims.consignment_agents_id as agents_id, 
       MAX(sims.rica_current_stamp) 
      as last_rica_stamp 
      from sims 
      where sims.rica_current_stamp > DATE_SUB(now(), INTERVAL 3 MONTH) and sims.consignment_agents_id is not NULL 
      group by sims.consignment_agents_id) as dt on dt.agents_id = agents.id 
      set agents.last_rica_stamp = dt.last_rica_stamp""" 
    res = Session.execute(query) 
    print res 
    if res.rowcount: 
     log.info("Updated %s agents" % res.rowcount) 
    #transaction.commit() 

當我運行celery worker -B這是返回什麼:

[2014-02-12 09:15:00,012: INFO/MainProcess] Received task: prepaid.models.Prepaid.PeriodicUpdateAgentLastRica[9ca091c8-595f-4163-8ddf-2742e573b90c] 
[2014-02-12 09:15:01,812: WARNING/Worker-7] <sqlalchemy.engine.result.ResultProxy object at 0x776f310> 
[2014-02-12 09:15:01,813: INFO/Worker-7] Updated 2923 agents 
[2014-02-12 09:15:01,816: INFO/MainProcess] Task prepaid.models.Prepaid.PeriodicUpdateAgentLastRica[9ca091c8-595f-4163-8ddf-2742e573b90c] succeeded in 1.798980095s: None 

即使它說,它更新:Updated 2923 agents,當我檢查數據庫,沒有記錄改變。

查詢沒有問題,因爲當我在mySQL Workbench中運行它時,它就起作用了。

同樣的,當我嘗試強制AutoCommit,即

res = Session.execute(text(query).execution_options(autocommit=True)) 

所以犯,但仍然Update不影響DB發生。 爲什麼它不影響數據庫?爲什麼它不起作用?

UPDATE

我也想這樣做:

with transaction.manager: 
    #Rest of code 

但它仍然無法在DB

改變什麼

回答

4

這就像你正在使用ZODB事務管理金字塔。

你必須標記該會話改變

http://www.upfrontsystems.co.za/Members/izak/sysadman/how-to-commit-a-transaction-even-when-sqlalchemy-thinks-the-session-is-clean

你應該這樣做

from zope.sqlalchemy import mark_changed 
mark_changed(Session) 

如果不行嘗試

from zope.sqlalchemy import ZopeTransactionExtension 
Session.configure(extension=ZopeTransactionExtension('changed')) 
+0

它給我的follwing錯誤:'任務prepaid.models.Prepaid.PeriodicUpdateAgentLastRica [260cb057-c117-4c68-bb 08-a55a169ce684] raise unexpected:AttributeError(「'scoped_session'object has no attribute'twophase'」,)' – Renier

+0

另一種方法是在執行操作之前標記它已更改。往上看。 –

相關問題