> 文章列表 > Power BI利用Python和Sql Server制作实时看板

Power BI利用Python和Sql Server制作实时看板

Power BI利用Python和Sql Server制作实时看板

通常我们在制作Power BI报表时使用的都是导入模式,导入确实相比DirectQuery模式性能和限制会更少些,但是某些场景下我们对数据刷新的上频率要求较高,比如即将到来的618大促,销售看板肯定不能再按天更新了,最好是做到秒级更新,当然微软也有相应的解决方案,使用流式数据,但这对于企业级项目来说成本又要提升一些了。

我们还可以使用DirectQuery来实现相对实时数据刷新,在桌面端查看效果时可实现秒级更新,发布到服务端后最小每15分钟刷新,具体可参见官方文档

Power BI 中的 DirectQuery - Power BI | Microsoft Learn[1]

接下来就来今天的小例子,我们使用windows的内存和硬盘使用情况来构建数据集,会使用到sql server和python

在sql server中创建如下表

CREATE TABLE [dbo].[Performance] ([Time] datetime  NULL,[cpu_usage] numeric(5,2)  NULL,[memory_usage] numeric(5,2)  NULL,[cpu_interrupts] numeric(18)  NULL,[cpu_calls] numeric(18)  NULL,[memory_used] numeric(18)  NULL,[memory_free] numeric(18)  NULL,[bytes_sent] numeric(18)  NULL,[bytes_received] numeric(18)  NULL,[disk_usage] numeric(18)  NULL
)

接下来打开编辑器,编写python代码,我这里使用的是Azure Data Studio,感兴趣的可以了解 你的下一个Jupyter可以是Azure Data Studio

import psutil
import time
import pyodbc
con = pyodbc.connect('Driver={SQL Server};'
'Server=.;'
'Database=test2;'
'Trusted_Connection=yes;'
)
cursor = con.cursor()
while 1==1:cpu_usage = psutil.cpu_percent()memory_usage = psutil.virtual_memory()[2]cpu_interrupts = psutil.cpu_stats()[1]cpu_calls = psutil.cpu_stats()[3]memory_used = psutil.virtual_memory()[3]memory_free = psutil.virtual_memory()[4]bytes_sent = psutil.net_io_counters()[0]bytes_received = psutil.net_io_counters()[1]dis_usage = psutil.disk_usage('/')[3]cursor.execute('insert into dbo.performance values(GETDATE(),'+ str(cpu_usage) + ','+ str(memory_usage) + ','+ str(cpu_interrupts) + ','+ str(cpu_calls) + ','+ str(memory_used) + ','+ str(memory_free) + ','+ str(bytes_sent) + ','+ str(bytes_received) + ','+ str(dis_usage) + ')')con.commit()print(memory_usage)time.sleep(1)

最后,使用Power BI,DirectQuery模式下连接数据源,简单制作以下看板,最终效果如下

 

参考来源

Power BI: Displaying Live System Performance using Power BI, SQL and Python - YouTube[2]

引用链接

[1] Power BI 中的 DirectQuery - Power BI | Microsoft Learn: https://learn.microsoft.com/zh-cn/power-bi/connect-data/desktop-directquery-about
[2] Power BI: Displaying Live System Performance using Power BI, SQL and Python - YouTube: https://www.youtube.com/watch?v=9VtkwH6iLL0&ab_channel=ViSIT