我想在TemplateView中使用concurrent.futures异步执行某些工作单元。然而,我遇到了我的异步代码没有被调用的问题。我在这里做错了什么?这是一个示例代码,它只是乘以一个数字,但实际上我想要异步地复制背景中的某些文件。任何帮助是极大的赞赏!django在TamplateView问题中使用期货
import concurrent.futures
import time
class AsyncTest(TemplateView):
def get(self, request, *args, **kwargs):
op = kwargs.get('op')
if op == 'asynch':
print 'using futures async'
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
# I see this print message
print 'executing future 1 time'
executor.map(self.load, 10)
return render(request, 'text.html', {'lines':'Performing async processing!', 'op':op})
else:
return HttpResponseBadRequest("Operation not implemented at this time (op=%s)" % op)
def load(x):
#I never see this get invoked
print 'in load...sleep'
time.sleep(2)
print 'sqr x*x=%s of x=%s' %((x*x), x)
return x*x
我从来没有看到任何从服务器的负载方法印刷,只是页面呈现印有最后一件事:“执行未来1周时间”
感谢您的有见地的评论文森特。我实际上最终使用了django-芹菜和期货。我将芹菜用于异步处理逻辑,然后使用Future:ThreadPoolExecutor同时将多个文件加载到HDFS中。我来自Java世界,所以python对我来说是新的,所以放弃早期可能只是沮丧,无论如何,我开始越来越多地挖掘python。 – Marcin