具有 Python 一次性初始化的 Azure 函数应用程序

Azure function apps with Python one time initialization

我在 Python 中使用 Azure 函数应用程序。我有两打函数应用程序,它们都使用 Postgres 数据库和自定义视觉。所有函数应用程序都设置为 HttpTriggers。现在,当一个函数被触发时,一个新的数据库处理程序(或自定义视觉处理程序)对象被创建、使用并在函数应用程序调用完成时终止。

在每个传入的请求上实例化一个新对象似乎会适得其反。有没有办法实例化一次共享对象,然后在调用它们时将它们传递给函数?

一般来说,Azure Functions 旨在 无状态 并且不会从一次调用到下一次调用共享对象。但是,也有一些例外。


共享连接对象

Azure 文档推荐 Improper Instantiation Pattern 用于共享连接对象,这些连接对象旨在在应用程序中打开一次并再次使用。

要使此功能适合您,需要记住一些事项,主要是:

The key element of this antipattern is repeatedly creating and destroying instances of a shareable object. If a class is not shareable (not thread-safe), then this antipattern does not apply.

他们那里有一些演练可能会对您有所帮助。由于您的问题相当笼统,我能做的最好的就是建议您通读一下,看看是否对您有帮助。


持久功能

备选方案是考虑 Durable Functions 而不是标准。它们旨在能够在函数之间传递对象,使它们不是完全无状态的。

Durable Functions is an advanced extension for Azure Functions that isn't appropriate for all applications. This article assumes that you have a strong familiarity with concepts in Azure Functions and the challenges involved in serverless application development.