如何格式化sqlalchemy中的输出?

how to formatize output in sqlalchemy?

我需要有关以下代码输出格式的帮助:

    p = select([persons])
    st = select([persons,students]).where(students.c.id == persons.c.id)
    t = select([persons,teachers]).where(persons.c.id == teachers.c.person_id)
    cl = select([classes])
    s_in_cl = select([students_in_class])

    p1 = conn.execute(p)
    st1 = conn.execute(st)
    t1 = conn.execute(t)
    cl1 = conn.execute(cl)
    ss1 = conn.execute(s_in_cl)

    print('\nTable "persons" : \n')
    q1 = p1.fetchall()
    if len(q1) < 1 : print('\tTable "persons" is empty!\n')
    else :
        for row in q1 : print(f'\t{row}')

    print('\nTable "students" : \n')
    q2 = st1.fetchall()
    if len(q2) < 1 : print('\tTable "students" is empty!\n')
    else : 
        for row in q2 : print(f'\t{row}')

    print('\nTable "teachers" : \n')
    q3 = t1.fetchall()
    if len(q3) < 1 : print('\tTable "teachers" is empty!\n')
    else :
        for row in q3 : print(f'\t{row}')

    print('\nTable "classes" : \n')
    q4 = cl1.fetchall()
    if len(q4) < 1 : print('\tTable "classes" is empty!\n')
    else : 
        for row in q4 : print(f'\t{row}')

    print('\nTable "students_in_class" : \n')
    q5 = ss1.fetchall()
    if len(q5) < 1 : print('\tTable "students_in_class" is empty!\n')
    else : 
        for row in q5 : print(f'\t{row}')

当前输出:

Table "人" :

    (2, 'Rajiv', 'Khanna', None, None)
    (3, 'Komal', 'Bhandari', None, None)
    (4, 'Michael', 'Ross', 'mikey4@gmail.com', datetime.datetime(2006, 10, 12, 0, 0))
    (5, 'Ann', 'Ross', 'ann_qw@gmail.com', datetime.datetime(2021, 11, 25, 0, 0))

Table "学生" :

    (4, 'Michael', 'Ross', 'mikey4@gmail.com', datetime.datetime(2006, 10, 12, 0, 0), 1, 4)

Table“老师们”:

    (3, 'Komal', 'Bhandari', None, None, 1, 3)

Table "类" :

    (1, 'philosophy', 'group_1', 1)

Table "students_in_class" :

    Table "students_in_class" is empty!

我想以 PrettyTable 的形式查看它,如何向其中添加 headers(列名)并正确格式化字符串(table 的行)? 任何帮助将不胜感激 ;)

如果你想使用 PrettyTable 那么你就拥有了 documentation

首先创建 PrettyTable(),然后将列名列表分配给 table.field_names,然后将所有行添加到 table,最后 print()

import datetime

q1 = [
    (2, 'Rajiv', 'Khanna', None, None),
    (3, 'Komal', 'Bhandari', None, None),
    (4, 'Michael', 'Ross', 'mikey4@gmail.com', datetime.datetime(2006, 10, 12, 0, 0)),
    (5, 'Ann', 'Ross', 'ann_qw@gmail.com', datetime.datetime(2021, 11, 25, 0, 0)),
]

from prettytable import PrettyTable

table = PrettyTable()

table.field_names = ["A", "B", "C", "D", "E"]
table.add_rows(q1)

print(table)

给予

+---+---------+----------+------------------+---------------------+
| A |    B    |    C     |        D         |          E          |
+---+---------+----------+------------------+---------------------+
| 2 |  Rajiv  |  Khanna  |       None       |         None        |
| 3 |  Komal  | Bhandari |       None       |         None        |
| 4 | Michael |   Ross   | mikey4@gmail.com | 2006-10-12 00:00:00 |
| 5 |   Ann   |   Ross   | ann_qw@gmail.com | 2021-11-25 00:00:00 |
+---+---------+----------+------------------+---------------------+

如果你想在没有 PrettyTable 的情况下做同样的事情,那么它需要做很多工作,因为首先你必须在每一列中获得最大长度,然后你可以在 f-string 中使用它在列中设置字符串长度 - 即。

f"{row[0]:{lenght_row_0}} | {row[1]:{lenght_row_1}} | ... "

例子

import datetime

q1 = [
    (2, 'Rajiv', 'Khanna', None, None),
    (3, 'Komal', 'Bhandari', None, None),
    (4, 'Michael', 'Ross', 'mikey4@gmail.com', datetime.datetime(2006, 10, 12, 0, 0)),
    (5, 'Ann', 'Ross', 'ann_qw@gmail.com', datetime.datetime(2021, 11, 25, 0, 0)),
]

# --- add headers ---

q1.insert(0, ["A", "B", "C", "D", "E"])

# --- lengths ---

columns_lengths = [0 for _ in range(len(q1[0]))]

for row in q1:
    for number, item in enumerate(row):
        length = len(str(item))
        if length > columns_lengths[number]:
            columns_lengths[number] = length

# --- horizontal line ---

items = []
for number, item in enumerate(row):
    length = columns_lengths[number]
    items.append(f'{"-"*(length+2)}')
horizontal_line = "+" +  "+".join(items) + "+"

# --- table ---

# - line -

print(horizontal_line)

# - header - 

items = []
for number, item in enumerate(q1[0]):
    length = columns_lengths[number]
    items.append(f'{str(item):^{length}}')
print("|", " | ".join(items), "|")

# - line -

print(horizontal_line)

# - rows - 

for row in q1[1:]:
    items = []
    for number, item in enumerate(row):
        length = columns_lengths[number]
        items.append(f'{str(item):^{length}}')
    print("|", " | ".join(items), "|")

# - line -

print(horizontal_line)

结果:

+---+---------+----------+------------------+---------------------+
| A |    B    |    C     |        D         |          E          |
+---+---------+----------+------------------+---------------------+
| 2 |  Rajiv  |  Khanna  |       None       |        None         |
| 3 |  Komal  | Bhandari |       None       |        None         |
| 4 | Michael |   Ross   | mikey4@gmail.com | 2006-10-12 00:00:00 |
| 5 |   Ann   |   Ross   | ann_qw@gmail.com | 2021-11-25 00:00:00 |
+---+---------+----------+------------------+---------------------+