Uploading a FPDF output pdf to the s3 bucket

133 Views Asked by At

The error message "No such file or directory: '/tmp/tmpnj0aocz9'" indicates that the code is unable to find the temporary file that should contain the PDF content.

Does anyone have a solution or a reason why this may happen.

def save_pdf_to_s3(pdf, pdf_type, s3_bucket, s3_bucket_path):
s3 = boto3.client('s3')

# Create a temporary file to hold the PDF content
temp_file = tempfile.NamedTemporaryFile(delete=False)
try:
    # Generate the PDF content as bytes and write it to the temporary file
    pdf_content = pdf.output(dest='S').encode('latin1')
    temp_file.write(pdf_content)
    
    # Upload the temporary file to S3
    s3.put_object(Key=f'{s3_bucket_path}/{pdf_type}.pdf', Body=open(temp_file.name, 'rb'), Bucket=s3_bucket)

    print("PDF saved to S3")
finally:
    # Close and remove the temporary file
    temp_file.close()

I tried to make an temp file and save the content of the pdf to that file. only it crashes at this line, because output wants to save automatically to a dir that is not there.

pdf_content = pdf.output(dest='S').encode('latin1')
1

There are 1 best solutions below

0
FifthAxiom On BEST ANSWER

Here's is an updated script that should work. Basically because now we use the with statement to open files. In your case the path to the temporary file was probably incorrect since you did not use the os.path.abspath() function to get it formatted properly.

Sample:

...
# Create a temporary file to hold the PDF content
temp_file = tempfile.NamedTemporaryFile(delete=False)

# Get the absolute path to the temporary file
temp_file_path = os.path.abspath(temp_file.name)
...

The updated script:

import boto3
import contextlib

def save_pdf_to_s3(pdf, pdf_type, s3_bucket, s3_bucket_path):
s3 = boto3.client('s3')

# Create a context manager to hold the temporary file
with tempfile.NamedTemporaryFile(delete=False) as temp_file:

    # Generate the PDF content as bytes and write it to the temporary file
    pdf_content = pdf.output(dest='S').encode('latin1')
    temp_file.write(pdf_content)

    # Upload the temporary file to S3
    with open(temp_file.name, 'rb') as f:
        s3.put_object(Key=f'{s3_bucket_path}/{pdf_type}.pdf', Body=f, Bucket=s3_bucket)

print("PDF saved to S3")

I hope this helps!