【Azure 应用服务】App Service中运行Python 编写的 Jobs,怎么来安装Python包 (pymssql)呢?

问题描述

在App Service中运行Python编写的定时任务,需要使用pymssql连接到数据库,但是发现使用 python.exe -m pip install --upgrade -r requirements.txt -t D:homesitewwwrootpymodules。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:homesitewwwroot目录。

可以直接将文件拖拽到这个目录下,操作如下:

2)在App Service的高级管理工具(Kudu)中进行安装

进入D:homepython364x64目录,执行这个命令进行安装 pip install D:homesitewwwrootpymssql-2.1.5-cp36-cp36m-win_amd64.whl

3)在Python的package文件夹中查看是否安装成功

安装成功之后,可以在这个目录D:homepython364x64Libsite-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.5https://pypi.org/project/pymssql/2.1.5/#files

Running Python Webjob on Azure App Services using non-default python versionhttps://azureossd.github.io/2016/12/09/running-python-webjob-on-azure-app-services-using-non-default-python-version/

当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!

原文地址:https://www.cnblogs.com/lulight/p/15414630.html