Roman
Roman

Reputation: 3941

Python flask upload generated pdf with pdfkit to AWS S3 without saving it to folder

I am currently using this code to generate a pdf from a template where certain variables need to be set. Everything works fine. But the pdf is also saved to the folder with the executing .py file.

I actually do not need it to be saved. I could delete it right after the upload, but that would be a workarround. I feel like there could be a better way.

path_wkthmltopdf = r'C:\Programme\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)

pdfkit.from_string(render_template('invoice_template.html', invoice_id=the_id, invioce_date_start=the_start_date,
                         invioce_date_end=the_end_date, invioce_company_name=the_invoice_company, invioce_user_vorename=the_invoice_user_forename,
                         invioce_user_surname=the_invoice_user_surname, invioce_user_email=the_invoice_user_email), the_invoice_filename, configuration=config)

new_invoice = Rechnung(name=the_invoice_filename, date_created=the_start_date, mandatnummer=1, rechnungsnummer=1, users_id=current_user.id)
db_session.add(new_invoice)

s3 = boto.connect_s3(app.config['MY_AWS_ID'], app.config['MY_AWS_SECRET'], host='s3.eu-central-1.amazonaws.com')
# Get a handle to the S3 bucket
bucket_name = 'my-bucket'
bucket = s3.get_bucket(bucket_name)
k = Key(bucket)

k.key = "invoices/" + the_invoice_filename   
k.set_contents_from_filename(the_invoice_filename)

Upvotes: 2

Views: 1875

Answers (1)

Roman
Roman

Reputation: 3941

Issue solved by changing the the_invoice_filename to False. If this argument is False the file wont be saved.

Now AWS must use k.set_contents_from_string(YOUR_CONTENTS) instead of k.set_contents_from_filename(YOUR_CONTENTS)

Here is a full example:

def create_invoice(the_invioce_rechnungsnummer):        

    config = pdfkit.configuration(wkhtmltopdf=app.config['WKHTMLTOPDF_CMD'])

    the_pdf = pdfkit.from_string(render_template('invoice_template.html', invioce_rechnungsnummer=the_invioce_rechnungsnummer), False, configuration=config)

    s3 = boto.connect_s3(app.config['MY_AWS_ID'], app.config['MY_AWS_SECRET'], host='s3.eu-central-1.amazonaws.com')
    bucket_name = 'YOUR_BUCKET_NAME'
    bucket = s3.get_bucket(bucket_name)
    k = Key(bucket)              

    PDF_FILE_NAME = "YOUR_PDF_FILE_NAME"
    k.key = "BUCKET/" + PDF_FILE_NAME   
    k.set_contents_from_string(the_pdf)

Upvotes: 2

Related Questions