Skip to main content
 首页 » 编程设计

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

2025年05月04日30over140

我有一个网络 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 

有没有一种方法可以在不过度设计*的情况下使其异步?

*例如,我会考虑为过度工程设置一个消息队列服务

请您参考如下方法:

如果给出了线程安全性(关于 PIL 以及您如何使用它),您可以使用 deferToThread:
https://twistedmatrix.com/documents/current/api/twisted.internet.threads.html

改进的配方,感谢 Calderone