Flask应用在PythonAnywhere使用wkhtmltopdf时挂起

-1 投票
1 回答
21 浏览
提问于 2025-04-12 18:15

我在使用Flask开发的应用程序中遇到了一个问题,当我尝试在PythonAnywhere上用wkhtmltopdf生成PDF时,程序就卡住了。以下是相关的代码片段:

    @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

我插入了一些检查点来调试这个问题,发现程序在调用pdfkit.from_file()时就停住了。错误日志显示它在检查点2的地方停止了。

这个应用程序在本地运行得很好,但在PythonAnywhere上托管时就出现了这个问题。这可能是因为超时,还是有什么方法可以优化这个过程,让它更快呢?任何见解或建议都非常感谢。谢谢!

1 个回答

1

在pythonAnywhere上使用wkhtmltopdf可能会有点麻烦,因为它需要运行一个二进制文件,而pythonAnywhere的执行环境可能会阻止这个操作。首先要检查一下你的pythonAnywhere账户里是否安装并正确配置了wkhtmltopdf。如果已经安装了但还是遇到问题,可以考虑异步生成PDF,或者把这个任务交给外部服务来处理,这样就不会影响你的Flask应用程序了。此外,你还可以去pythonAnywhere的论坛或者联系他们的客服,可能会得到更具体的帮助,适合他们的环境。

撰写回答