将 Jython 游标结果解析为 table

Parse Jython cursor result into table

我创建了一个 Jython 查询,returns 来自红移的信息 table:

cursor = context.cursor()
cursor.execute('WITH t1 as (SELECT date, partner AS partner, 
revenue AS revenue, avg(revenue)OVER (partition BY 
partner ORDER BY date ROWS BETWEEN 7 preceding AND 1 PRECEDING) as 
"7-day avg"FROM (SELECT date, partner, sum(revenue) as 
revenue FROM data.base GROUP BY date, 
partner))SELECT * FROM t1 WHERE date = CURRENT_DATE - 1 ORDER BY 
revenue DESC')

然后:

for item in cursor.fetchall():
    print item

Returns:

(datetime.date(2018, 9, 4), u'Disney', 458.171787, 487.70715842857)
(datetime.date(2018, 9, 4), u'Amazon', 142.33, 741.864285714284)
(datetime.date(2018, 9, 4), u'Google', 82.26, 83.510000000002)

我遇到问题的地方是将其转换为人类可读的 table,并且可以通过 SES 通过电子邮件发送。理想情况下,最终版本应类似于:

| Date       | Partner | Revenue | Avg    |
|------------|---------|---------|--------|
| 2018-09-04 | Disney  | 458.17  | 487.71 |
| 2018-09-04 | Amazon  | 142.33  | 741.86 |
| 2018-09-04 | Google  | 82.26   | 83.51  |

另一个限制因素是我没有安装包的权限,所以我仅限于基础 Jython 或 Python。

这是我获得所需格式的方法:

sample = cursor.fetchall()

#Get maximum length for each variable to create padding
max_partner = max([len(sample[x][1]) for x in range(len(sample))])
max_rev = max([len('${:,.2f}'.format(sample[x][2],2)) for x in range(len(sample))])
max_avg = max([len('${:,.2f}'.format(sample[x][3],2)) for x in range(len(sample))])

#Create column header
subject = "".join(["Date", 7 * " ","| ", 
      "Partner", (max_partner - len("Partner") + 1) * " ","| ", 
      "Revenue", (max_rev - len("Revenue") + 1) * " ","| " 
      "7 Day Avg", "\n", 50 * "-"])

#Generate rows from Redshift query
for item in sample:
    subject += "\n" + str(item[0]) + " | " + \
    item[1] + (max_partner - len(item[1])) * " " + " | " + \
    '${:,.2f}'.format(item[2]) + (max_rev - len('${:,.2f}'.format(item[2],2))) * " " + " | " + \
    '${:,.2f}'.format(item[3])

print subject


Date       | Partner       | Revenue    | 7 Day Avg
--------------------------------------------------
2018-09-09 | Disney        | 4.93    | 4.70
2018-09-09 | Amazon        | 8.48    | $,604.38
2018-09-09 | Google        | .05     | .11