T
T
Tremo2016-12-14 11:30:04
Python
Tremo, 2016-12-14 11:30:04

How to write data to pdf from mysql Python?

Good day to all!
The second day I'm trying to solve the problem when trying to extract data from mysql and write it correctly to a pdf file. I work with flask, and to create pdf files I use the reportlab library.
The database has 6 columns of types:
I will give the code below: int, date, time, varchar, varchar,int

data = c.fetchall() # вытаскидываю данные из базы
for row in data:
            ptext = row
            Story.append(Paragraph(ptext,styles["Normal"]))
            Story.append(Spacer(1, 12))
        doc.build(Story) # пишет в pdf

I get the following error:
AttributeError: 'tuple' object has no attribute 'split'
When I do the same but write to a text file, I get the following:
(datetime.date(2016, 12, 12), datetime.timedelta(0, 72785) , 'late', 'Monday')

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2016-12-14
@tremo0880

Each individual element of the tuple must be converted to a string. If the number of fields is known, unchanged and not numerous:

ptext = '{} {} {} {}'.format(
  row[0].strftime('%d.%m.%Y'),
  row[1].strftime('%d.%m.%Y'),
  row[2],
  row[3]
)
Story.append(Paragraph(ptext, styles["Normal"]))

A more versatile option is to bypass the fields in a loop:
ptext = ''
for ndx, field in enumerate(row):
    if ndx:
        ptext += ' '
    if isinstance(field, date):
        ptext += field.strftime('%d.%m.%Y')
    else:
        ptext += str(field)
Story.append(Paragraph(ptext, styles["Normal"]))

Or use the inclusion, it will be a little faster and more compact:
ptext = ' '.join(field.strftime('%d.%m.%Y') if isinstance(field, date) else str(field) for field in row)
Story.append(Paragraph(ptext, styles["Normal"]))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question