繁体   English   中英

如何漂亮地打印 SqlAlChemy 的输出?

[英]How to pretty print output for SqlAlChemy?

这是我将 SqlAlChemy 链接到数据库后的代码。 我正在尝试打印 2017 年的顶级 IP 地址。但是,我无法很好地打印我的结果。

from sqlalchemy import select, func, and_, desc
import math

Top2017 = session.query(Log.IP,func.count(Log.IP).label('count')).filter(and_(Log.date >= '2017-1-1',Log.date <= '2017-12-31')).group_by(Log.IP).order_by(desc('count'))

print("The Top IP Address is   ")
print("Year" , "IP Address")
for q in Top2017.limit(3):
    print("2017", q)

我的输出是:

The Top IP Address is   
Year IP Address
2020-03-06 10:21:03,811 INFO sqlalchemy.engine.base.Engine SELECT logfile."IP" AS "logfile_IP", count(logfile."IP") AS count 
FROM logfile 
WHERE logfile.date >= ? AND logfile.date <= ? GROUP BY logfile."IP" ORDER BY count DESC
 LIMIT ? OFFSET ?
2020-03-06 10:21:03,812 INFO sqlalchemy.engine.base.Engine ('2017-1-1', '2017-12-31', 3, 0)
2017 ('10.131.0.1', 1921)
2017 ('10.130.2.1', 1805)
2017 ('10.128.2.1', 1667)

输出非常混乱,因为打印所有查询的结果都不是很清楚。 因此,我想要的输出将是:

The Top IP Address is 

Year IP Address Count 
2017 10.131.0.1 1921
2017 10.130.2.1 1805
2017 10.128.2.1 1667

感谢您的帮助。

这是 dict 的输出。

The Top IP Address is   
Year IP Address Count
OrderedDict([('10.131.0.1', 1921), ('10.130.2.1', 1805), ('10.128.2.1', 1667)])

你可以这样做:

from collections import OrderedDict

Top2017 = (
    session.query(Log.IP, func.count(Log.IP).label("count"))
    .filter(and_(Log.date >= "2017-1-1", Log.date <= "2017-12-31"))
    .group_by(Log.IP)
    .order_by(desc("count"))
    .limit(3)
)

dict = OrderedDict(Top2017)

现在,您将查询结果保存在字典中,并且可以像这样打印所需的输出:

print("The Top IP Address is   ")
print("Year" , "IP Address", "Count")
for key, value in dict.items():
    print("2017", key, value)

如果您需要更多解释,请告诉我。

如果要将结果打印为表格,请使用 tabulate 包。

pip 安装表格

from tabulate import tabulate

q = engine.execute('SHOW DATABASES;')
result = q.fetchall()
print(tabulate(result, headers=q.keys(), tablefmt='psql'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM