Azure函数-雪花python连接器的池dbconnection

时间:2020-01-15 07:25:48

标签: azure azure-functions snowflake-cloud-data-platform dbconnection

我有一个azure函数应用程序(python),该应用程序连接到雪花数据库(创建dbconnection对象),执行查询并返回结果,并且运行良好。唯一的挑战是返回查询所花费的时间。每次调用它时都会创建dbconnection对象。

问题:是否可以使用功能应用程序来建立连接池(考虑到功能应用程序是无状态的)

1 个答案:

答案 0 :(得分:1)

简短的答案是“是”,这是我的带有HTTP触发器的Azure Function示例代码,如下所示。

import logging

import azure.functions as func

def inc(n):
    while True:
        n += 1
        yield n

count = inc(0)

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    return func.HttpResponse(f"Count: {count.__next__()}!")

我在函数count外部声明了一个全局变量inc(0),其生成器main的值,然后可以得到如下图所示的增加的计数响应。

enter image description here

这与我对SO线程Azure use python flask framework for function app的另一个答案相同。

因此,我认为确实要在Azure Functions中实现连接池,例如使用snowflakedb/snowflake-sqlalchemy在Azure Function的函数main之外为Python中的Snowflake数据库创建连接池,作为代码请参阅SQLAlchemy文档Connection Pooling

import logging
import azure.functions as func
from sqlalchemy import create_engine
import sqlalchemy.pool as pool

engine = create_engine(
    'snowflake://{user}:{password}@{account}/'.format(
        user='<your_user_login_name>',
        password='<your_password>',
        account='<your_account_name>',
    )
)

def getconn():
    connection = engine.connect()
    return connection

mypool = pool.QueuePool(getconn, max_overflow=10, pool_size=5)

def main(req: func.HttpRequest) -> func.HttpResponse:
    try:
        conn = mypool.connect()
        # Do the code what you want, such as
        # cursor = conn.cursor()
        # cursor.execute("select foo")
        ....
    finally:
        conn.close()
    return func.HttpResponse(f"......")

上面代码的解释如下。

  1. 适用于Python的Azure函数从头到尾编译源代码并将其字节码加载到内存中,然后在触发mypool函数之后从内存中调用main对象,直到{长时间闲置后,{1}}已从内存中删除。
  2. 下一次在空闲后触发mypool函数时,将创建一个新的main对象,并继续执行上述操作。