Puppeteer не работает с Django Viewset
Я пытаюсь написать конечную точку Django REST, которая будет преобразовывать HTML-контент в PDF, а затем возвращать ответ Streaming file для загрузки отчета. Для этого я использую Puppeteer, который прекрасно работает вне области применения Django (например, для тестирования). Минимальный пример представления загрузки выглядит следующим образом
import asyncio
from pyppeteer import launch
from django.http import HttpResponse
from rest_framework.viewsets import ViewSet
from rest_framework.permissions import IsAuthenticated
from rest_framework_simplejwt.authentication import JWTAuthentication
class DownloadReport (ViewSet):
permission_classes = [IsAuthenticated]
authentication_classes = [JWTAuthentication]
async def html_to_pdf(self, html):
browser = await launch(
headless=True,
args=['--no-sandbox', '--disable-setuid-sandbox']
)
page = await browser.newPage()
await page.setContent(html)
await page.setViewport({
'width': 1920,
'height': 1080,
'deviceScaleFactor': 1
})
pdf = await page.pdf({
'format': 'A3',
'printBackground': True,
'landscape': True,
'scale': 1
})
await browser.close()
return pdf
def retrieve(self, request):
content = "<h1>Hurrah PDF conversion successfull<h1>"
content = asyncio.run(self.html_to_pdf(content))
response = HttpResponse(content, content_type='application/pdf')
response['Content-Disposition'] = f'attachment; filename="report.pdf"'
return response
Проблема в том, что в Djanog браузер даже не запускается, а выдает следующее исключение
Traceback (most recent call last):
File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 65, in _view_wrapper
return view_func(request, *args, **kwargs)
File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\viewsets.py", line 124, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\data\Office\Projects\Dockerized_DjangoApp\analytics\views.py", line 172, in retrieve
content = asyncio.run(self.html_to_pdf(content))
File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 649, in run_until_complete
return future.result()
File "C:\data\Office\Projects\Dockerized_DjangoApp\analytics\views.py", line 29, in html_to_pdf
browser = await launch(
File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\site-packages\pyppeteer\launcher.py", line 307, in launch
return await Launcher(options, **kwargs).launch()
File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\site-packages\pyppeteer\launcher.py", line 159, in launch
signal.signal(signal.SIGINT, _close_process)
File "C:\Users\Zain ul abdin\AppData\Local\Programs\Python\Python310\lib\signal.py", line 56, in signal
handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread of the main interpreter
Как я могу решить эту проблему, чтобы действительно получить PDF в ответ без этой проблемы, связанной с сигналом? Пожалуйста, не рекомендуйте wkhtmltopdf или любые другие инструменты, поскольку они не отображают современный синтаксис на основе JS правильно мой html содержит tailwind JS интеграций.