在我的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)
Run Code Online (Sandbox Code Playgroud)
而不是我想要的响应,如:
{"id":"13"}
Run Code Online (Sandbox Code Playgroud)
客户端获取如下字符串:
"<generator object create at 0x102c50050>"
Run Code Online (Sandbox Code Playgroud)
编辑:
我意识到使用yield是错误的方法,实质上我想要实现的是客户端在服务器进入manage_incident()的时间代价高昂的函数之前立即收到响应
这与生成器或让步没有任何关系,但是我使用了以下代码和装饰器让事情在后台运行,同时立即返回客户端的HTTP响应.
用法:
@postpone
def long_process():
do things...
def some_view(request):
long_process()
return HttpResponse(...)
Run Code Online (Sandbox Code Playgroud)
以下是使其工作的代码:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3926 次 |
| 最近记录: |