2011-01-10 39 views
2

我正在使用django_notification模塊。 https://github.com/pinax/django-notification/blob/master/docs/usage.txt我不明白這個Django文檔。我如何使用它這個模塊?

這是我在我的代碼做發送電子郵件給用戶,當有事情發生:

notification.send([to_user], "comment_received", noti_dict) 

但是,這似乎阻止請求。發送出去需要很長時間。我閱讀了文檔,它說可以將它添加到隊列中(異步)。我如何將它添加到異步隊列?

我不明白這些文檔試圖說什麼。什麼是「emit_notices」?我什麼時候打電話?我有一個腳本每5秒調用一次嗎?這很愚蠢。什麼是異步執行的正確方法?我該怎麼辦?

Lets first break down what each does. 

``send_now`` 
~~~~~~~~~~~~ 

This is a blocking call that will check each user for elgibility of the 
notice and actually peform the send. 

``queue`` 
~~~~~~~~~ 

This is a non-blocking call that will queue the call to ``send_now`` to 
be executed at a later time. To later execute the call you need to use 
the ``emit_notices`` management command. 

``send`` 
~~~~~~~~ 

A proxy around ``send_now`` and ``queue``. It gets its behavior from a global 
setting named ``NOTIFICATION_QUEUE_ALL``. By default it is ``False``. This 
setting is meant to help control whether you want to queue any call to 
``send``. 

``send`` also accepts ``now`` and ``queue`` keyword arguments. By default 
each option is set to ``False`` to honor the global setting which is ``False``. 
This enables you to override on a per call basis whether it should call 
``send_now`` or ``queue``. 

回答

2

它看起來就像在你的設置文件,你需要設置

NOTIFICATION_QUEUE_ALL=True 

然後你需要設置一個cronjob(也許每隔10-30秒或別的東西)來運行類似,

django_admin.py emit_notices 

這將定期運行並執行阻止呼叫,該呼叫將發送所有電子郵件以及通知應用程序需要的任何協調工作。我敢肯定,如果沒有什麼可做的事情,那不是那麼緊張的工作量。

而在你對這個愚蠢的評論展開討論之前,你應該考慮一下。這並不是真的愚蠢。您不希望阻止調用綁定到Web請求,否則用戶將永遠不會收到服務器的響應。從這個意義上說,發送電子郵件是阻塞的

現在,如果您只是想讓他們在登錄時收到此通知,那麼您可能不需要這樣做,因爲您必須撥打sendmail或您正在使用的任何外部電話發送電子郵件。但在你的情況下,發送電子郵件,你應該這樣做。

1

根據這些文檔,send只是包裝send_nowqueue。所以,如果你想發送的通知,異步,而不是同步的,你有兩個選擇:

  1. 修改您的設置:

    # This flag will make all messages default to async 
    NOTIFICATION_QUEUE_ALL = True 
    
  2. 使用德queue關鍵字參數:

    notification.send([to_user], "comment_received", noti_dict, queue=True) 
    

如果您排隊通知,您將不得不運行emit_notices管理命令定期。所以你可以把它放在一個cron工作中,每隔幾分鐘運行一次。