2012-07-16 48 views
5

我一直在長輪詢系統上工作。我用燒瓶+ mongokit +芹菜+ gevent。我想使用gevent.evnet到celery.task

當在芹菜任務中的進程,完成gevent.event.set()不工作。所以我想幫忙弄清楚(我之所以用芹菜同時使用gevent,在通知系統中有巨大的處理過程)

這裏是我的示例代碼。

#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> 

回答

4

現在,在瓶0.9 Flask.app_context增加,隨着Flask.app_context就可以得到當前的背景下。

請參閱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))