簡體   English   中英

使用 pyodbc 的 azure 函數在本地機器上工作正常,但在 azure 雲上不能正常工作

[英]azure function using pyodbc works fine on local machine, but not on azure cloud

我開發了一個簡單的 python Azure 函數應用程序,使用 pyodbc 從公共 IP MS SQL 服務器中選擇幾行。 我的函數應用程序在我的筆記本電腦上運行良好,但是當我在 Azure 雲上發布它時它不起作用(我使用了消費 - 無服務器計划,linux 環境)。 通過日志記錄,我知道它總是卡在 pyodbc.connect(...) 命令和超時處。

#...
conn_str = f'Driver={driver};Server={server},{port};Database={database};Uid={user};Pwd={password};Encrypted=yes;TrustServerCertificate=no;Connection Timeout=30'
sql_query = f'SELECT * FROM {table_name}'
try:
    conn = pyodbc.connect(conn_str) # always time-out here if running on Azure cloud!!!
    logging.info(f'Inventory API - connected to {server}, {port}, {user}.')
except Exception as error:
    logging.info(f'Inventory API - connection error: {repr(error)}.')
else:
    with conn.cursor() as cursor:
        cursor.execute(sql_query)
        logging.info(f'Inventory API - executed query: {sql_query}.')
        data = []
        for row in cursor:
            data.append({'Sku' : row.Sku, 'InventoryId' : row.InventoryId, 'LocationId' : row.LocationId, 'AvailableQuantity' : row.AvailableQuantity})
#...

記錄捕獲:

Inventory API - connection error: OperationalError('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)').

我已經在 requirements.txt 文件中包含了 pyodbc。 我還允許在我的 SQL 服務器防火牆上使用我的函數應用程序的所有 outboundIpAddresses 和 possibleOutboundIpAddresses。 我的函數應用對 Azure 雲沒有任何網絡限制(或者至少它在網絡設置上是這樣說的)。

我的配置文件:

driver={ODBC Driver 17 for SQL Server}
server=I tried both IP and full internet host name, both didn't work

有人可以給我一個提示嗎? 謝謝。

修復PYODBC連接錯誤的解決方法

嘗試使用以下格式

import pyodbc
server = 'tcp:myserver.database.windows.net'
database = 'mydb'
username = 'myusername'
password = 'mypassword'
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)

如果您使用域名添加TCP與域名server = 'tcp:myserver.database.windows.net'否則使用IP server = '129.0.0.1'

如果您正在使用像這樣'tcp:myserver.database.windows.net,1233'端口使用'tcp:myserver.database.windows.net,1233''129.0.0.1,1233'

嘗試刪除其他屬性,如Connection_TimeoutTrusted_certificate ,然后立即檢查。

參考這里

我將以下代碼段放入我的函數中以檢查出站 IP,並發現 Azure 使用了一些未在 [outboundIpAddresses] 和 [possibleOutboundIpAddresses] 中列出的出站 IP( 記錄在此 MS 鏈接中

import requests
#...
outbound_ip_response = requests.request('GET', 'https://checkip.amazonaws.com')
logging.info(f'Inventory API - main()- outbound ip = {outbound_ip_response.text}')

因此,我按照此鏈接中的說明為我的函數應用設置了一個靜態出站 IP,並允許該 IP 訪問我的 SQL 服務器。 有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM