問題描述
在App Service中運行Python編寫的定時任務,需要使用pymssql連接到數據庫,但是發現使用 python.exe -m pip install --upgrade -r requirements.txt -t D:\home\site\wwwroot\pymodules。requirements.txt中包含pymssql庫。安裝時候出現錯誤消息: Failed to build pymssql.

問題答案
因為App Service上無法直接編譯Python Package為Wheel文件,所以需要在本地編譯好之后,上傳到App Service中。使用PIP命令直接安裝Wheel文件。操作步驟為:
1)從網絡中下載 pymssql的wheel文件
在 https://pypi.org/project/pymssql/2.1.5/#files 找到對應 Python 版本的安裝模塊,如:pymssql-2.1.5-cp36-cp36m-win_amd64.whl ,下載到本地,然后上傳到App Service的D:\home\site\wwwroot目錄。
可以直接將文件拖拽到這個目錄下,操作如下:

2)在App Service的高級管理工具(Kudu)中進行安裝
進入D:\home\python364x64目錄,執行這個命令進行安裝 pip install D:\home\site\wwwroot\pymssql-2.1.5-cp36-cp36m-win_amd64.whl

3)在Python的package文件夾中查看是否安裝成功
安裝成功之后,可以在這個目錄D:\home\python364x64\Lib\site-packages查看到安裝的包.

需要注意,執行Python的Webjob時,需要使用 .cmd 來啟動 Python,指定自定義后的Python.exe的路徑。

附錄:pymssql 連接數據庫代碼
import time,datetime,dingtalk.api,pyodbc from sqlalchemy import create_engine import pandas as pd server="xxxx.database.windows.net" database='xxx' #數據庫名稱 user="xxxx" #登陸賬號 password="xxxxxxxxxxxxx" #賬號密碼 driver= '{ODBC Driver 17 for SQL Server}' conn=pyodbc.connect('DRIVER='+driver+';SERVER=tcp:'+server+';PORT=1433;DATABASE='+database+';UID='+user+';PWD='+ password,encoding = 'utf-8') sqlcmd="SELECT * FROM dbo.xxxxxxxxx" #sql語句 dataset=get_df_from_db_1(sqlcmd) S_sheet =[] S_sheet =pd.DataFrame(columns=('xxx','xxx','xxx')) ### ... ### ... S_sheet=S_sheet.reset_index(drop=True) #存入數據庫 conn_engine='mssql+pyodbc://'+user+':'+password+'@'+server+'/'+database+'?driver=ODBC Driver 17 for SQL Server' engine = create_engine(conn_engine) pd.io.sql.to_sql(S_sheet, 'xxx', con=engine, index=False, if_exists='append') print('Data:%s'%len(S_sheet)) conn.close()
參考資料
pymssql 2.1.5:https://pypi.org/project/pymssql/2.1.5/#files
Running Python Webjob on Azure App Services using non-default python version : https://azureossd.github.io/2016/12/09/running-python-webjob-on-azure-app-services-using-non-default-python-version/
