【问题标题】:pyramid ZopeTransactionExtension with celery: how can I commit transaction immediately without keep transaction after web request?带有芹菜的金字塔ZopeTransactionExtension:如何在Web请求后立即提交交易而不保留交易?
【发布时间】:2013-07-07 05:19:09
【问题描述】:

这是我的情况。

我正在构建一个 RESTful 网络服务,它从客户端接收数据,然后从该数据创建一个事件,然后我想将此新事件推送到 celery 以异步处理它。

我使用 pyramid 来构建 RESTful 网络服务,并使用 pyramid_celery 使金字塔和 celery 协同工作。

这是我的观点的源代码:

# views.py
# This code recive data from client, then create a new record Event from this

posted_data = schema.deserialize(request.POST.mixed())

e = Event()
e.__dict__.update(posted_data)
DBSession.add(e)
transaction.commit()

print "Commited #%d" % e.id # code mark 01
fire_event.delay(e.id) # fire_event is a celery task
logging.getLogger(__name__).info('Add event #%d to tasks' % e.id)

这是我的任务的源代码:

# tasks.py
@celery.task()
def fire_event(event_id):
    e = DBSession.query(Event).get(event_id)

    if e is None:
        return

    print "Firing event %d#%s" % (event_id, e)
    logger.info("Firing event %d#%s", event_id, e)

如果我使用来自金字塔炼金术脚手架的默认代码,则会在 code mark 01 行引发异常。像这样的例外:

DetachedInstanceError: Instance <Event at ...> is not bound to a Session; ...

来自ZopeAlchemy document,为避免此异常,我这样配置 DBSession:

# models.py
DBSession = scoped_session(sessionmaker(
                extension=ZopeTransactionExtension(keep_session=True)
            ))

现在我的问题是我的 RESTful 请求完成后与我的 MySQL 服务器的金字塔保持事务。当 RESTful 请求完成后,我转到 MySQL 服务器并运行命令:

SHOW engine innodb status;

从结果中,我看到了:

--TRANSACTION 180692, ACTIVE 84 sec
MySQL thread id 94, OS thread handle 0x14dc, query id 1219 [domain] [ip] [project name] cleaning up
Trx read view will not see trx with id >= 180693, sees < 180693

这意味着 Pyramid 仍然保持连接,没关系,但 Pyramid 也开始事务,这是一个问题。当我尝试使用其他工具访问我的 MySQL 服务器时,此事务可能使我处于锁定状态。

我的问题是:

如何让 Pyramid 在 RESTful 请求完成后立即关闭事务。如果不能,是否有针对我的情况的其他解决方案?

非常感谢。

【问题讨论】:

    标签: transactions celery pyramid


    【解决方案1】:

    Celery 保持一种“透明地”将代码作为任务运行的错觉——你用@task 装饰你的函数,然后使用 my_function.delay(),一切都会神奇地工作。

    事实上,实现起来有点棘手,您的代码在完全不同的进程中运行,可能在另一台机器上,可能在几分钟/几小时后,并且该进程中不存在 Pyramid 请求/响应周期,所以 ZopeTransactionExtension不能用于在请求完成时自动提交工作进程中的事务 - 因为没有请求,只有一个长时间运行的工作进程。

    所以不是 Pyramid 让未完成的交易挂起 - 这是您的工作进程。当您调用 e = DBSession.query(Event).get(event_id) 时,事务由 SQLAlchemy 启动,并且永远不会完成。

    在这里,我为类似问题写了一个更长的答案,其中包含更多详细信息:https://stackoverflow.com/a/16346587/320021 - 重点是为您的工作进程使用不同的会话

    另一件事是最好避免在 Pyramid 代码中使用transaction.commit(),因为对象过期和其他丑陋。在金字塔中,可以在请求完成后调用一个函数 - 我编写了一个函数,它注册了一个回调,该回调从那里调用一个 celery 任务:

    from repoze.tm import after_end
    import transaction
    
    def invoke_task_after_commit(task_fn, task_args, task_kwargs):
        """
        This should ONLY be used within the web-application process managed by repoze.tm2
        otherwise a memory leak will result. See http://docs.repoze.org/tm2/#cleanup
        for more details.
        """
        t = transaction.get()  # the current transaction
    
        def invoke():
            task_fn.apply_async(
                args=task_args,
                kwargs=task_kwargs,
            )
    
        after_end.register(invoke, t)
    

    (我从函数中删除了很多不相关的代码,因此可能存在拼写错误等。视为伪代码)

    【讨论】:

    • 很抱歉我是 Python 和 Pyramid 的新手。尝试实现您的功能时出现此错误: from repoze.tm import after_end ImportError: No module named tm 我知道我缺少一些包。如果你有其他教程或答案,请介绍给我,我还是新手。非常感谢。
    • 谢谢你,你帮了我很多。我从你的回答中改变了一点,我附加到 SQLAlchemy 事件而不是 repoze 事件。然后我对金字塔和芹菜使用不同的 DBSession。我解决了我的问题,非常感谢。
    猜你喜欢
    • 2014-12-23
    • 2021-10-22
    • 2020-10-04
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    相关资源
    最近更新 更多