如何在Python Flask中保留一个芹菜任务中的请求上下文? [英] How to keep a request context in a celery task, in Python Flask?

查看:161
本文介绍了如何在Python Flask中保留一个芹菜任务中的请求上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以将请求复制到Flask中的芹菜任务,使得任务在启动任务的请求上下文中执行?

我需要访问flask安全当前用户在芹菜任务中,但由于任务不在请求的上下文中,所以我不能这样做。我需要来自请求的附加信息,所以只要将当前用户转发到任务就行。



我的任务插入到数据库中。它需要当前用户保存创建该行的用户的ID。将用户对象传递给任务将解决问题。然而,应用程序逻辑是这样的,每一个插入/删除/更新都是在刷新事件之前记录的,记录修改的用户,他的IP地址,原始URL,插入的数据......)

记录事件就像我之前说的flush一样完成,它在99%的情况下工作。
但是当我有一个冗长的任务,我想成为一个芹菜任务时,请求
数据不可用,也不是当前用户(因为它在原始请求上下文之外)

解决方案

但是人们已经通过创建一个包装器来调用请求上下文中的芹菜任务来解决这个问题了。



Flask请求上下文中的Celery任务博客文章详细探讨了这个主题。要点来自 Xion ,并由 aviaryan 与Request Context wrapper。


Is there a way to copy the request to a celery task in Flask in such a manner that the task executes inside the request context which initiated the task?
I need to access the flask security current user in a celery task, but since the task is outside the request context, I can not do that. I need additional information from the request, so just forwarding the current user to the task would not do the trick.

My task does inserts on the database. It needs the current user to save the id of the user which creates the row. Passing the user object to the task would solve the problem. However, the application logic is such that every insert/delete/update is logged via before flush event, which logs the user who did the modification, his IP, original url, the data it inserts...)

Log event is done like I said before flush, and it works in 99% scenarios. But when I have one lengthy task which I want to be a celery task, the request data is not available, nor is the current user (since it is outside the original request context)

解决方案

The is no out-of-the-box way to pass the request or current_user objects to the celery task as they are non serializable. But people have worked around this by creating a wrapper to call the celery task in the request context.

The Celery task in a Flask request context blog post explores this topic in detail. The gists by Xion and derived one by aviaryan with the Request Context wrapper.

这篇关于如何在Python Flask中保留一个芹菜任务中的请求上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
Python最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆