【问题标题】:Can't connect to Azure Postgresql with a Python Function App无法使用 Python 函数应用连接到 Azure Postgresql
【发布时间】:2021-06-03 14:24:23
【问题描述】:

我关注了thisthisthis 以及许多其他资源,但仍然无法连接到数据库。这就是我打开这个问题的原因。我非常沮丧。希望有人可以引导我走向正确的方向。以下是我已经完成的步骤。

  1. 我从article 执行了步骤 1-3。顺便说一句,在为数据库中的函数创建角色时,我应该使用天蓝色函数的应用程序 ID 还是系统分配标识的主体 ID?我使用了应用程序 ID。
  2. 我已添加 azure 函数的所有可能出站 IP 地址以通过数据库防火墙。
  3. 功能在 Linux 消费计划上。根据此article,如果功能在 Linux 消费计划中,则需要使用 2017-09-01 api 版本。

我在 os.environ["MSI_ENDPOINT"], os.environ["MSI_SECRET"] 的函数属性/配置中没有找到任何内容,所以我假设这些是由 microsoft 在函数执行时分配的。这是我在运行该函数时遇到的异常:

"执行函数时出现异常:Functions.FunctionTrigger 结果:失败 例外:UnboundLocalError:分配前引用的局部变量“连接”。如果连接:"

此外,即使我将它们写在函数体中,我也看不到任何日志。不在函数见解中,也不在为函数定义的存储帐户中。所以基本上我是在瞎飞。此外,最初我使用的是 psycopg2,我在here 中收到了异常。然后我切换到 psycopg2-binary 并且异常消失了。任何帮助将不胜感激。

import logging
import os
import azure.functions as func
import psycopg2
from psycopg2 import Error
import requests

def main(mytimer: func.TimerRequest) -> None:
    utc_timestamp = datetime.datetime.utcnow().replace(
        tzinfo=datetime.timezone.utc).isoformat()

    if mytimer.past_due:
        logging.info('The timer is past due!')

    logging.info('Python timer trigger function ran at %s', utc_timestamp)

    try:
        #get access token
        # identity_endpoint = os.environ["IDENTITY_ENDPOINT"]
        # identity_header = os.environ["IDENTITY_HEADER"]
        # resource_uri="https://database.windows.net/"
        # token_auth_uri = f"{identity_endpoint}?resource={resource_uri}&api-version=2019-08-01"
        # head_msi = {'X-IDENTITY-HEADER':identity_header}
        # resp = requests.get(token_auth_uri, headers=head_msi)
        # access_token = resp.json()['access_token']
        msi_endpoint = os.environ["MSI_ENDPOINT"]
        msi_header = os.environ["MSI_SECRET"]
        # resource_uri="https://database.windows.net/"
        resource_uri="https://ossrdbms-aad.database.windows.net"
        token_auth_uri = f"{msi_endpoint}?resource={resource_uri}&api-version=2017-09-01"
        head_msi = {'secret':msi_header}
        resp = requests.get(token_auth_uri, headers=head_msi)
        access_token = resp.json()['access_token']

        logging.info(msi_endpoint)
        logging.info(msi_header)
        logging.info(access_token)
        
        USER = 'name of the role that I created for the function'
        connection = psycopg2.connect(
            user = USER,
            password = access_token,
            host = HOST,
            database = DB,
            port = '5432'
        )

        cursor = connection.cursor()

        query = "SELECT * FROM table;"
        cursor.execute(query)


    except (Exception, Error) as error:
        print(error)
        logging.info(error)

    finally:
        if connection:
            cursor.close()
            connection.close()
            print("PostgreSQL connection is closed")

【问题讨论】:

  • 我认为os.environ 用于获取操作系统变量的值。在 Windows 中,我们应该先set IDENTITY_ENDPOINT=<...>set MSI_SECRET=<...>

标签: python azure-functions azure-postgresql


【解决方案1】:

我不确定您是否需要使用托管标识连接到 Azure PostgreSQL。如果不是,那么可能的问题是使用 psycopg2。请改用 psycopg2-binary。将 psycopg2-binary 添加到您的 requirements.txt 中。这将解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多