在异步代码中使用PIL(Twisted Web)

2 投票
1 回答
2006 浏览
提问于 2025-04-17 15:07

我有一个网络API,它可以接收一张图片,然后把这张图片传递给另一个异步服务。不过在传递之前,我会用PIL把图片缩小。

我的代码大概是这样的(为了简单起见,省略了一些不相关的细节):

def render_POST(self, request):
    pil_image = Image.open(request.content)
    pil_image.thumbnail((640,640), Image.ANTIALIAS) 
    outfile = StringIO()
    pil_image.save(outfile, "JPEG")
    do_something_async_and_write_result(outfile)
    return NOT_DONE_YET

有没有什么办法可以让这个过程变成异步的,而不需要做得太复杂呢?

*我觉得比如为了这个目的而专门设置一个消息队列服务就是过于复杂了

1 个回答

1

如果你确保线程安全(关于PIL和你如何使用它),你可以使用deferToThread:
https://twistedmatrix.com/documents/current/api/twisted.internet.threads.html

感谢Calderone的改进表述

撰写回答