在我的 django 活塞 API 中,我想在调用另一个需要相当长的时间的函数之前向客户端产生/返回一个 http 响应。如何使yield 给出包含所需JSON 的HTTP 响应,而不是与生成器对象创建相关的字符串?
我的活塞处理程序方法如下所示:
def create(self, request):
data = request.data
*other operations......................*
incident.save()
response = rc.CREATED
response.content = {"id":str(incident.id)}
yield response
manage_incident(incident)
而不是我想要的回应,例如:
{"id":"13"}
客户端得到这样的字符串:
"<generator object create at 0x102c50050>"
EDIT:
我意识到使用yield是解决这个问题的错误方法,本质上我想要实现的是客户端在服务器转移到manage_incident()的耗时函数之前立即收到响应
这与生成器或生成没有任何关系,但我使用了以下代码和装饰器让事情在后台运行,同时立即向客户端返回 HTTP 响应。
Usage:
@postpone
def long_process():
do things...
def some_view(request):
long_process()
return HttpResponse(...)
这是使其工作的代码:
import atexit
import Queue
import threading
from django.core.mail import mail_admins
def _worker():
while True:
func, args, kwargs = _queue.get()
try:
func(*args, **kwargs)
except:
import traceback
details = traceback.format_exc()
mail_admins('Background process exception', details)
finally:
_queue.task_done() # so we can join at exit
def postpone(func):
def decorator(*args, **kwargs):
_queue.put((func, args, kwargs))
return decorator
_queue = Queue.Queue()
_thread = threading.Thread(target=_worker)
_thread.daemon = True
_thread.start()
def _cleanup():
_queue.join() # so we don't exit too soon
atexit.register(_cleanup)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)