2016-06-20 6 views
0

私はDjangoアプリを持っています。私のビューの1つでは、実際に電子メールを送信する関数に非同期呼び出しを行っています。私は両方ともthreading.thread(start()で)とafter_responseという小さなdjangoパッケージを使用しています。これは基本的に同じです。ここで非同期呼び出しを実行しているときのUWSGIとGunicornの違い

は、私がやったことです:

def my_synchronous_function(instance): 
    send_email_asynchronous.after_response(instance.id) 
    return "We are done here, but async call will continue." 

@after_response.enable 
def send_email_asynchronous(instance_id): 
    time.sleep(5) 
    print "Async has started" 
    instance = Instance.objects.get(pk=instance_id) 
    subject = "A subject" 
    ctx = {'username': instance.username} 
    message = get_template("email-template.html").render(ctx) 
    msg = EmailMessage(subject, message, to=[instance.email], from_email='[email protected]') 
    print "about to send email" 
    time.sleep(5) 
    msg.content_subtype = 'html' 
    msg.send() 
    print "message sent" 

ジャンゴmanage.pyのrunserverを実行しているときにこのコードは素晴らしい作品。それはまた、nginx + gunicornを使用するとうまく動作します。しかし、私はUWSGIとNginxを使用するときsend_email_asynchronous関数が呼び出されることはないことに気付きました。これは、次のように開始され

class SendNotification(threading.Thread): 
    """ 
    Sends notifications async. 
    """ 
    def __init__(self, instance_id): 
     """ 
     Sends notifications asynchronously provided an instance id. 
     """ 
     print "instance id: %s" % instance_id 
     self.instance = Instance.objects.get(pk=instance_id) 
     super(SendNotification, self).__init__() 

    def run (self): 
     time.sleep(5) 
     print "Async has started" 
     subject = "A subject" 
     ctx = {'username': self.instance.username} 
     message = get_template("email-template.html").render(ctx) 
     msg = EmailMessage(subject, message, to=[self.instance.email],        from_email='[email protected]') 
     print "about to send email" 
     time.sleep(5) 
     msg.content_subtype = 'html' 
     msg.send() 
     print "message sent" 

アゲイン のSendNotification(instance.id).start()、正常に動作しますafter_responseだけでなく、より長いthreading.Threadバージョン使用している場合これが真実でありますdevサーバ "runserver"は、gunicornでも動作しますが、uwsgiでは動作しません。なぜこれが起こっているのか少し不思議です。 uwsgiでは実際にはのprintステートメントが表示されますが、runメソッドのprintステートメントは表示されません。もちろん電子メールは表示されません。私はこの問題のためにgunicornを使用するように切り替えました。だから、私が求めているのは好奇心ではありません。

おかげで、

答えて

1

あなたのuWSGIの設定を投稿するが、これは、バックグラウンドスレッドがuWSGIの起動時need to add --enable-threads高いチャンスがあります実行していないについてです考慮しませんでした:

あなたなしuWSGIを起動した場合Python GILは になっていないので、アプリケーションで生成されたスレッドは決して実行されません。 はそのような選択肢が気に入らないかもしれませんが、uWSGIは言語に依存しないサーバ であることを覚えておいてください。ほとんどの選択肢は のままです。

しかし、基本的には、オプションで変更できないuWSGI 開発者による選択はありません。

複数のスレッドをアプリケーションに起動せずにPythonスレッドのサポートを維持する場合は、--enable-threads オプション(またはiniスタイルでenable-threads = true)を追加するだけです。

+0

答えてくれてありがとう!私はこれが私がuWSGIで持っていた問題だと信じています。 --enable-threadsを追加することはそのトリックを行うようです。 –

関連する問題