【问题标题】:using PIL in asynchronous code (Twisted Web)在异步代码中使用 PIL (Twisted Web)
【发布时间】:2013-02-07 16:31:19
【问题描述】:

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

有没有办法让它异步而不过度设计*?

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

【问题讨论】:

    标签: python asynchronous twisted python-imaging-library


    【解决方案1】:

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

    增强配方,感谢 Calderone

    【讨论】:

    • 使用线程时,线程安全始终是一个问题!我认为你的意思是“如果 PIL 是线程安全的,......”。 :)
    • 那你的问题有点难以回答。
    • 什么是“过度”工程?如果您没有其他满足您所需规格的解决方案,那么这似乎是恰到好处的工程量。
    猜你喜欢
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多