2017-10-01 9 views
0

私は最初にdjangoビューで応答を返したいと思っています。最初に応答を返す方法はありますが、応答後も何か他のことをしますか? django

は、最初の応答を返すチャンスがあるかどう

class Res(View): 
    def post(self, request): 
     data = request.POST 
     new_obj = Model.objects.create(name=data.['name']) 

     # what is below does not have to be done RIGHT AWAY, can be done after a response is made 
     another_obj = Another() 
     another_obj.name = new_obj.name 
     another_obj.field = new_obj.field 
     another_obj.save() 

     # some other looping and a few other new models to save 

     return JsonResponse({'status': True}) 

は、だから私は疑問に思って.....さんは、私が一例として、このようなものを持っているとしましょうか?上記のことは、私が意味するものの例です。

私は、可能ならば、これは、ジャンゴで行うことができるかどうかわからない、誰かが私は、これは事前に

感謝を行うことができる人を知らせることができます。

+2

このためにセロリのタスクを使用できます。 – neverwalkaloner

+0

はい、セロリはそれを行う優れた方法の1つです。ここでそれについて読む:https://realpython.com/blog/python/asynchronous-tasks-with-django-and-celery/ –

+0

thx thx、私はすぐにこれを試し、それがどのように動作するか見る。 – Dora

答えて

2

これは、Djangoの質問よりもPythonのほうが多いです。コメントが指摘しているように、Celeryのような非同期待ち行列を実装することもできますが、これはあなたのユースケースには多少の過度の可能性があります。

はプレーンPython threads代わりに使用することを検討してください:ここ

from threading import Thread 


def create_another_obj(name, field): 
     another_obj = Another() 
     another_obj.name = name 
     another_obj.field = field 
     another_obj.save() 

class Res(View): 
    def post(self, request): 
     data = request.POST 
     new_obj = Model.objects.create(name=data['name']) 

     # start another thread to do some work, this is non-blocking 
     # and therefore the JsonResponse will be returned while it is 
     # running! 
     thread = Thread(
        target=create_another_obj, 
        args=(new_obj.name, new_obj.field), 
       ) 
     thread.start() 

     return JsonResponse({'status': True}) 

アイデアは、あなたが関数に非同期で実行され、スレッドでそれらを実行したいコードを抽出することです。

+0

私はちょうどあなたの応答を見ました、それは良いアイデアのようです、私はそれを試してみましょう。 'thread(target =)'は関数でなければなりませんか? この種のケースでの使用以外に、 'JsonResponse'が実行されるためにS3にオブジェクトを渡す必要がないような場合があります。 – Dora

+0

はい、 'target'は関数でなければなりません。[ドキュメントをチェックアウト](https://docs.python.org/3/library/threading.html#thread-objects)。 'Thread'から継承し、' run() 'をオーバーライドするクラスを作成することもできます。 – olieidel

関連する問題