无法使用Python函数应用程序连接到Azure Postgresql

2024-09-28 21:03:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经使用了thisthisthis以及许多其他资源,但仍然无法连接到数据库。这就是我提出这个问题的原因。我非常沮丧。希望有人能把我引向正确的方向。下面是我所做的步骤

  1. 我从这个article开始做了步骤1-3。顺便问一下,在数据库中为函数创建角色时,我应该使用azure函数的应用程序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:分配前引用了局部变量“connection”。如果连接:

此外,即使我在函数体中编写日志,也看不到任何日志。不在函数洞察中,也不在为函数定义的存储帐户中。所以基本上我是瞎飞的。此外,最初我使用的是psycopg2,在here中接收到异常。然后我切换到psycopg2二进制,异常消失了。任何帮助都将不胜感激

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")

Tags: 函数importinfotokenaccessosloggingenviron
1条回答
网友
1楼 · 发布于 2024-09-28 21:03:01

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

相关问题 更多 >