gpt4 book ai didi

Python Flask使用pdfkit将生成的pdf上传到AWS S3而不将其保存到文件夹

转载 作者:太空宇宙 更新时间:2023-11-03 15:01:41 24 4
gpt4 key购买 nike

我目前正在使用此代码从需要设置某些变量的模板生成 pdf。一切正常。但 pdf 也会保存到执行 .py 文件的文件夹中。

我实际上不需要保存它。我可以在上传后立即将其删除,但这将是一个解决方法。我觉得可能有更好的方法。

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)

最佳答案

通过将 the_invoice_filename 更改为 False 解决了问题。如果此参数为False,则不会保存文件。

现在 AWS 必须使用 k.set_contents_from_string(YOUR_CONTENTS) 而不是 k.set_contents_from_filename(YOUR_CONTENTS)

这是一个完整的示例:

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)

关于Python Flask使用pdfkit将生成的pdf上传到AWS S3而不将其保存到文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45038501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com