Databricks / ADF python协助

问题描述 投票:2回答:1

需要帮助从Azure数据库执行python脚本。要求是使用python脚本连接到数据库并从表中读取数据并使用表中的内容触发电子邮件。

这是我的示例脚本。它本地工作正常,但我不知道如何使它在Databricks或数据工厂工作。

import pyodbc
import settings
import sendgrid
import time
from sendgrid.helpers.mail import *

username = settings.username
password = settings.password
server = settings.server
database = settings.database
driver= '{SQL Server}'
connection_string = 'DRIVER={driver};PORT=1433;SERVER={server};DATABASE= 
{database};
UID={username};
PWD={password}'.format(driver=driver, server=server, 
database=database, username=username, password=password)
cnxn = pyodbc.connect(connection_string)

cursor= cnxn.cursor()
cursor.execute("Select Job_status as Status, COUNT(*) AS 
count FROM demo_table group by Job_status")
arr=[]
while 1:
row = cursor.fetchone()
if not row:
break
print(row.Status, row.count)
arr.append(row.Status+" "+str(row.count))
Status = arr[0] , arr[1]
cnxn.close()

sg = sendgrid.SendGridAPIClient(apikey='***********************')
from_email = Email("********************")
to_email = Email("****************************")
subject = "Job Monitoring | Job Failures"
content = Content("text/html", value = 'Hi,Provided are the details of the 
jobs.' +str(Status[0])+''+str(Status[1]) +'Regards,Team')
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())"

作业完成后,理想情况下应该从表中读取数据,然后使用作业详细信息触发电子邮件。

请帮忙!

python azure azure-data-factory databricks azure-databricks
1个回答
2
投票

我看到您的代码中需要两个第三方Python库,因此首先需要在Azure Databricks中安装它们,如下所示。

  1. 安装sendgrid包比较简单,如下图所示。 图1.1。单击Azure门户中的Launch Workspace按钮并登录.enter image description here 图1.2。移动到选项卡ClustersCreate Cluster,然后单击群集的Libraries链接enter image description here 图1.3。单击Install New按钮并选择PyPI库源以键入包名称sendgridInstall enter image description here 图1.4。 sendgrid包裹立即安装了enter image description here
  2. 按照博客Executing SQL Server Stored Procedures from Databricks (PySpark)安装pyodbc软件包及其所需的linux软件包,如下所示。 图2.1。为下一个安装install_pyodbc创建一个新的笔记本enter image description here 图2.2。要检查Linux发行版本并按照博客安装这些软件包enter image description here 图2.3。尝试通过pyodbc连接和查询数据库,它工作enter image description here import pyodbc connection_string = "Driver={ODBC Driver 17 for SQL Server};Server=tcp:<your db name>.database.windows.net,1433;Database=<db name>;Uid=<username>@<dbinstance name>;Pwd=<password>;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;" cnxn = pyodbc.connect(connection_string) cursor= cnxn.cursor() cursor.execute("select * from table") row = cursor.fetchone() if row: print(row)

然后,您可以创建一个新的笔记本来运行您的代码。要与Azure Data Factory集成,请参阅官方文档Transform data by running a Python activity in Azure Databricks以了解如何操作。

© www.soinside.com 2019 - 2024. All rights reserved.