Flask app hangs when using wkhtmltopdf on PythonAnywhere

23 views Asked by At

I'm encountering an issue with my Flask application where it hangs when attempting to generate a PDF using wkhtmltopdf on PythonAnywhere. Here's the relevant code snippet:

    @app.route('/save_to_pdf')
    def save_to_pdf():
    # Get form data
    user_id = session.get('user_id')
    print("USER ID is: " + str(user_id))
    prompt = Prompt.query.filter_by(user_id=user_id).first()
    prompt_data = prompt.prompt_data
    
    print("Fetching pictures...")
    user = User.query.get(user_id)
    pictures = user.pictures
    print("Pictures found: " + str(len(pictures)))
    
    firstName = user.firstName
    lastName = user.lastName
    
    # Create HTML content with form data
    base_url = 'https://lilg263.pythonanywhere.com/'  # Change to your actual base URL
    html_content = render_template('pdf.html', prompt_data=prompt_data, pictures=pictures, firstName=firstName, lastName=lastName, base_url=base_url)
    
    # Save HTML to a temporary file
    temp_html_file = 'temp.html'
    with open(temp_html_file, 'w') as f:
        f.write(html_content)
    
    # Convert HTML to PDF using wkhtmltopdf
    pdf_file = 'output.pdf'
    
    css = ['static/style.css', 'static/responsive.css']
    print("Checkpoint1")
    config = pdfkit.configuration(wkhtmltopdf='/usr/bin/wkhtmltopdf')
    print("Checkpoint2")
    pdfkit.from_file(temp_html_file, pdf_file, configuration=config, css=css, options={"enable-local-file-access": True})
    print("Checkpoint3")
    
    # Provide the PDF as a response to the user
    with open(pdf_file, 'rb') as f:
        response = make_response(f.read())
        response.headers['Content-Type'] = 'application/pdf'
        response.headers['Content-Disposition'] = 'inline; filename=output.pdf'
    
    print("Checkpoint4")
    # Clean up temporary files
    os.remove(temp_html_file)
    os.remove(pdf_file)
    
    return response

I've inserted some checkpoints to debug the issue, and it appears that the execution hangs at pdfkit.from_file() call. The error logs indicate that it stops at Checkpoint2.

The application works fine locally, but encounters this issue when hosted on PythonAnywhere. Could this be due to a timeout or is there a way to optimize this process to speed it up? Any insights or suggestions would be greatly appreciated. Thank you!

1

There are 1 answers

0
Stephen Rosslan On

Using wkhtmltopdf on pythonAnywhere can be tricky because it involves execution of a binary which pythonAnywhere's execution environment might block. Check if wkhtmltopdf is installed and correctly configured in your pythonAnywhere account. If it is and you still face issues, consider generating your PDF asynchronously or offloading the task to an external service to avoid blocking your Flask app. pythonAnywhere forums or contacting their support might provide more specific assistance tailored to their environment.