我一直在研究长轮询系统。我用 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/

10-14 00:06