gpt4 book ai didi

python - 将 gevent.evnet 与 celery.task 结合使用

转载 作者:太空狗 更新时间:2023-10-30 01:16:42 24 4
gpt4 key购买 nike

我一直在研究长轮询系统。我用的是 flask + mongokit + celery + gevent。

当 celery 任务中的进程完成时,gevent.event.set() 不起作用。我需要帮助来解决这个问题。 (我之所以同时使用gevent和celery,是因为在Notification系统中有一个巨大的进程需要处理。)

这是我的示例代码。

 #server.py
@celery.task()
def doing_task(uid, message):
notification = Notification() # this is a notification Model
notification.add(request.args.get('to'), some_notification)
app.event.set()
app.event.clear()

@app.route('/main')
def main():
return render_template('main.html')

@app.route('/set')
def set():
doing_task.delay(request.args.get('uid'), 'Notify')
return 'OK'

@app.route('/poll')
def poll():
uid = request.args.get('uid')
app.event.wait()
if is_authorized(uid): #uid 1 is a authorized account
return Notification().get(uid)

#main.html
<body>
<button>Click me</button>
</body>
<script>
$('button').click(function(e) {
$.ajax({
'url': '/set',
'data': 'uid=1',
'success': function(data) {
console.log(data);
}
});
e.preventDefault();
});

var poll = function() {
return $.ajax({
'url': '/poll',
'method': 'get',
'async':true,
'dataType': 'json',
'timeout': 10000,
'success': function(data) {
console.log(data);
setTimeout(poll, 50);
},
'error':function (req,sta,er){
setTimeout(poll, 3000);
},
});
};
poll()
</script>

最佳答案

现在,在 Flask 0.9 中添加了 Flask.app_context,使用 Flask.app_context 可以获取 current 的上下文。

参见 Application Context .

例如,

from flask import Flask
from celery import Celery

app = Flask(__name__)
celery = Celery(__name__)

@celery.task
def hello():
# Also, you are able to deal with current request as use test_request_context
with app.app_context():
print current_app
with app.test_request_context() as request:
print('Hello {0!r}'.format(request))

关于python - 将 gevent.evnet 与 celery.task 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11501991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com