![](/img/trans.png)
[英]How to get rid of 500 Internal Server Error using Python and Flask?
[英]Flask: how to get rid of pdfkit causing 500 Error
嘗試使用Flask應用程序的pdfkit創建.pdf文件時遇到錯誤。 該應用程序確實可以在本地計算機上運行。 當我嘗試在Digitalocean的Ubuntu 18.04 Droplet上運行代碼時,問題開始出現(Nginx用作Web服務器,Gunicorn(由主管協助)運行wsgi)。 那是我進入瀏覽器的錯誤(500):
服務器遇到內部錯誤,無法完成您的請求。 服務器超載或應用程序中有錯誤。
那是Gunicorn錯誤日志中的錯誤:
[2019-07-27 14:44:56,969] ERROR in app: Exception on /store/resins/daylight/3 [POST]
Traceback (most recent call last):
File "/home/slava/env/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/home/slava/env/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/slava/env/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/slava/env/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/home/slava/env/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/home/slava/env/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/slava/ag3d/ag3d/routes.py", line 184, in resin_store
pdfkit.from_string(rendered, pdf_name, options = options)
File "/home/slava/env/lib/python3.6/site-packages/pdfkit/api.py", line 72, in from_string
return r.to_pdf(output_path)
File "/home/slava/env/lib/python3.6/site-packages/pdfkit/pdfkit.py", line 159, in to_pdf
raise IOError("wkhtmltopdf exited with non-zero code {0}. error:\n{1}".format(exit_code, stderr))
OSError: wkhtmltopdf exited with non-zero code 1. error:
qt.qpa.screen: QXcbConnection: Could not connect to display
Could not connect to any X display.
這是應用程序使用pdfkit的方式:
options = {
'page-size': 'A4',
'margin-top': '0.75in',
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
}
rendered = render_template('order_doc.html', pdf_resin = pdf_resin)
pdfkit.from_string(rendered, pdf_name, options = options)
PDFKit軟件包使用wkhtmltopdf
,而后者又需要X Server來運行。 在Debian土地上,這通常需要xvfb-run
包裝器。
headless_pdfkit軟件包試圖使jakewins提出的修補程序更易於使用。
您可以通過運行以下命令來安裝headless_pdfkit
:
pip install headless-pdfkit
從字符串保存一個簡單的PDF:
from headless_pdfkit import generate_pdf
ret = generate_pdf('<html></html>')
with open('output.pdf', 'wb') as w:
w.write(ret)
options = {
'auto_servernum': ''
}
ret = generate_pdf('<html></html>', options=options)
with open('output.pdf', 'wb') as w:
w.write(ret)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.