第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用帶有 ActiveDirectoryMSI 身份驗證的 Python 的 Azure 函數(shù)連接

使用帶有 ActiveDirectoryMSI 身份驗證的 Python 的 Azure 函數(shù)連接

UYOU 2022-05-24 15:02:42
我正在嘗試使用 ActiveDirectoryMSI 身份驗證從用于 python 的 Azure 函數(shù)連接 Azure SQL 數(shù)據(jù)庫。請檢查以下代碼:-import loggingfrom . import hy_paramimport sysimport pyodbcimport azure.functions as funcdef main(req: func.HttpRequest) -> func.HttpResponse:    logging.info('Python HTTP trigger function processed a request.')    try:        connection = pyodbc.connect('driver={%s};server=%s;database=%s;Authentication=ActiveDirectoryMSI' % (hy_param.sql_driver, hy_param.server_name, hy_param.database_name))        sql_db = connection.cursor()        logging.info("MSSQL Database Connected")    except Exception as e:        return func.HttpResponse(f"Error in sql database connection : {e}", status_code=400)        sys.exit()    return func.HttpResponse(            "Database Connected",            status_code=200    )請檢查以下錯誤:-Error in sql database connection : ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]SSL Provider: [error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed:self signed certificate] (-1) (SQLDriverConnect)')有什么方法可以使用 ActiveDirectoryMSI 從 Azure 函數(shù)連接 Azure、SQL 數(shù)據(jù)庫?
查看完整描述

2 回答

?
千萬里不及你

TA貢獻1784條經(jīng)驗 獲得超9個贊

您可以嘗試使用下面的代碼使用 MSI 訪問令牌連接到您的 Azure SQL(在運行此代碼之前,請確保您的功能 MSI 已啟用并且它有權(quán)訪問您的 Azure SQL):


import logging

import os

import azure.functions as func

import pyodbc

import requests 

import struct


msi_endpoint = os.environ["MSI_ENDPOINT"]

msi_secret = os.environ["MSI_SECRET"]


def main(req: func.HttpRequest) -> func.HttpResponse:


   token_auth_uri = f"{msi_endpoint}?resource=https%3A%2F%2Fdatabase.windows.net%2F&api-version=2017-09-01"

   head_msi = {'Secret':msi_secret}

   resp = requests.get(token_auth_uri, headers=head_msi)

   access_token = resp.json()['access_token']


   accessToken = bytes(access_token, 'utf-8');

   exptoken = b"";

   for i in accessToken:

        exptoken += bytes({i});

        exptoken += bytes(1);

   tokenstruct = struct.pack("=i", len(exptoken)) + exptoken;


   conn = pyodbc.connect("Driver={ODBC Driver 17 for SQL Server};Server=tcp:andyserver.database.windows.net,1433;Database=database2", attrs_before = { 1256:bytearray(tokenstruct) });


   cursor = conn.cursor()

   cursor.execute("select @@version")

   row = cursor.fetchall()

   return func.HttpResponse(str(row))

請使用您贏得的服務器名稱和數(shù)據(jù)庫名稱編輯連接字符串


這是我這邊的測試結(jié)果:

http://img1.sycdn.imooc.com//628c83470001351314260816.jpg

查看完整回答
反對 回復 2022-05-24
?
拉丁的傳說

TA貢獻1789條經(jīng)驗 獲得超8個贊

使用 SDK 和 ODBC 驅(qū)動程序直接連接到 Azure SQL 有一種更好的新方法。

你需要:

  1. 啟用 Azure 函數(shù)托管服務標識 (MSI)

  2. 為 Azure SQL Server 啟用 AAD 集成

  3. 將 Azure Function MSI 用戶添加到數(shù)據(jù)庫

  4. Authentication=ActiveDirectoryMsi你的pyodbc.connect.

要將 MSI 用戶添加到數(shù)據(jù)庫,您必須使用 AAD 管理員連接,然后運行此查詢:

CREATE USER "<MSI user display name>" FROM EXTERNAL PROVIDER;

ALTER ROLE db_datareader ADD MEMBER "<MSI user display name>" -- grant permission to read to database

ALTER ROLE db_datawriter ADD MEMBER "<MSI user display name>" -- grant permission to write to database

<MSI user display name>通常是 Azure 函數(shù)名稱。您也可以 Get-AzureADObjectByObjectId -ObjectIds在 PowerShell 中使用它


這是一個 hello-world 函數(shù)的源代碼:


import logging

import azure.functions as func


# Sql driver

import pyodbc


def main(req: func.HttpRequest) -> func.HttpResponse:


    try:


        logging.info('Python HTTP trigger function processed a request.')


        # Connecting to Azure SQl the standard way

        server = 'tcp:<servername>.database.windows.net' 

        database = '<dbname>' 

        driver = '{ODBC Driver 17 for SQL Server}' # Driver 13 did not work for me


        with pyodbc.connect(

            "Driver="

            + driver

            + ";Server="

            + server

            + ";PORT=1433;Database="

            + database

            + ";Authentication=ActiveDirectoryMsi", # This is important :)

        ) as conn:


            logging.info("Successful connection to database")


            with conn.cursor() as cursor:

                #Sample select query

                cursor.execute("SELECT Name FROM People;") 


                peopleNames = ''

                row = cursor.fetchone() 

                while row: 

                    peopleNames += str(row[0]).strip() + " " 

                    row = cursor.fetchone()


                return func.HttpResponse(f"Hello {peopleNames}!")

    except Exception as e:

        return func.HttpResponse(str(e))

這里有一個完整的項目,您可以作為示例:https ://github.com/crgarcia12/azure-function-msi-python


查看完整回答
反對 回復 2022-05-24
  • 2 回答
  • 0 關(guān)注
  • 245 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號