我的 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() 调用处挂起。错误日志表明它停止在 Checkpoint2。
该应用程序在本地运行良好,但在 PythonAnywhere 上托管时遇到此问题。这可能是由于超时造成的,还是有办法优化此过程以加快速度?任何见解或建议将不胜感激。谢谢!
在 pythonAnywhere 上使用 wkhtmltopdf 可能会很棘手,因为它涉及执行 pythonAnywhere 的执行环境可能会阻止的二进制文件。检查您的 pythonAnywhere 帐户中是否安装并正确配置了 wkhtmltopdf。如果是这样并且您仍然遇到问题,请考虑异步生成 PDF 或将任务卸载到外部服务,以避免阻塞 Flask 应用程序。 pythonAnywhere 论坛或联系他们的支持可能会提供适合其环境的更具体的帮助。