首页 > 解决方案 > 使用 Azure Datapreb 库与 Azure AD 服务主体连接 Azure SQL 数据库时出错

问题描述

我正在尝试使用 azure datapreb 库将 Azure SQL 数据库与 Azure AD 服务主体连接起来。

请检查以下代码:-

import logging
import struct
from . import hy_param
import azureml.dataprep as dprep
import azure.functions as func
import adal

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    try:
        SQL_COPT_SS_ACCESS_TOKEN = 1256
        # connection string for database connection without username and password
        connection_string = "Driver=" + hy_param.sql_driver + ';SERVER=' + hy_param.server_name + ';DATABASE=' + hy_param.database_name

        token = get_token()
        conn = dprep.MSSQLDataSource(connection_string, attrs_before = { SQL_COPT_SS_ACCESS_TOKEN:token})
        logging.info("Connection is : ",conn)
        cursor = conn.cursor()

        # # Read data from table
        cursor.execute("SELECT GETDATE()")
        row = cursor.fetchone()
        return func.HttpResponse(f"Created :- {row}",
            status_code=200
        )
    except Exception as e:
        return func.HttpResponse(f"Error in sql database connection : {e}", status_code=400)

def get_token():
    # get token using the Azure AD Service Principals
    authority_url = (hy_param.login_url + '/' + hy_param.tenant_id)

    context = adal.AuthenticationContext(authority_url, api_version=None)
    access_token = context.acquire_token_with_client_credentials(hy_param.resource_url, hy_param.client_id, hy_param.client_secret)

    converted_token = bytes(access_token["accessToken"], "UTF-8")
    operated_token = b''
    for each_token_data in converted_token:
        operated_token += bytes({each_token_data})
        operated_token += bytes(1)
    token_data = struct.pack("=i", len(operated_token)) + operated_token
    return token_data

请检查以下错误:-

Error in sql database connection : __init__() got an unexpected keyword argument 'attrs_before'

有没有办法解决上述问题?我想使用带有 Azure AD 服务主体的 Datapreb 库来访问 Azure SQL DB。

我在 Pyodb 库上试过了,它工作正常,但在 datapreb 库上不行。

标签: pythonpython-3.xazureazure-sql-databaseazure-functions

解决方案


错误是说这一行不满意并且无法识别此参数。您使用的是什么版本的库,它实际上是否可能不接受名为 this 或重命名的参数 (attrs_before)?

conn = dprep.MSSQLDataSource(connection_string, attrs_before = { SQL_COPT_SS_ACCESS_TOKEN:token})


推荐阅读