【问题标题】:Django view html to pdf executed twiceDjango查看html到pdf执行了两次
【发布时间】:2021-01-27 08:09:32
【问题描述】:

我有以下类来生成一个 pdf 文件,我使用 django-renderpdf 从 html 模板生成一个 pdf。但是视图执行了两次,就抛出了错误。

我的班级:

class WeeklyMetre(PDFView):
    template_name = 'reports/invoice/weekly_metre.html'

    allow_force_html = True
    prompt_download = True

    @property
    def download_name(self) -> str:
        invoice = Invoice.objects.get(pk=self.kwargs['pk'])
        return f"WeeklyMetre_{invoice.invoice_number}.pdf"

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        invoice = Invoice.objects.get(pk=self.kwargs.get('pk'))
        market_labor_specifications = _getWeeklyMetreData(invoice=invoice)

        # calculate reported items: reported market_labor_specifications
        # invoiced specifications which are validated in invoice-period
        # but labor_date before invoice-period

        reported_mls = MarketLaborSpecification.objects.filter(invoice_id=self.kwargs.get('pk'), market_labor__labor_date__lt=invoice.period_from) \
        .values('market_labor__labor_date', 'specification__position', 'specification__name') \
        .order_by('market_labor__labor_date', 'specification__position', 'specification__name') \
        .annotate(sum_pos=Sum('validated_quantity'))

        context.update({
            'invoice': invoice,
            'market_labor_specifications': market_labor_specifications,
            'reported_mlss': reported_mls
        })

        print('context data', datetime.datetime.now())
        return context

在两次执行之间我有以下错误:

[01/Feb/2021 07:16:38] "GET /reports/invoice/select/17/ HTTP/1.1" 200 1414
context data 2021-02-01 07:16:44.835695
[01/Feb/2021 07:16:45] "GET /reports/weekly/metre/17/ HTTP/1.1" 200 58063
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 60114)
Traceback (most recent call last):
  File "/usr/lib/python3.6/socketserver.py", line 654, in process_request_thread
    self.finish_request(request, client_address)
  File "/usr/lib/python3.6/socketserver.py", line 364, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python3.6/socketserver.py", line 724, in __init__
    self.handle()
  File "/home/t3tr4ktys/python-virtual-environments/BillOfQuantities/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 174, in handle
    self.handle_one_request()
  File "/home/t3tr4ktys/python-virtual-environments/BillOfQuantities/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request
    self.raw_requestline = self.rfile.readline(65537)
  File "/usr/lib/python3.6/socket.py", line 586, in readinto
    return self._sock.recv_into(b)
ConnectionResetError: [Errno 104] Connection reset by peer
----------------------------------------
context data 2021-02-01 07:16:47.544189
[01/Feb/2021 07:16:48] "GET /reports/weekly/metre/17/ HTTP/1.1" 200 58063

首先,我不知道为什么它会执行两次,而在第二次执行时,用户不再经过身份验证。最后,pdf 生成良好,但我无法应用 LoginRequiredMixin。如果需要,将提供更多信息,感谢您的帮助。

【问题讨论】:

  • 您问题代码中的缩进是否正确? context.update.. 应该在 get_context_data 里面吗?
  • 你怎么知道视图被执行了两次?
  • 是什么让你认为它执行了两次?你能提供完整的输出吗?我没有看到对 print('context data', datetime.datetime.now()) 的调用。
  • 缩进现在是正确的,这里只是一个提示。我还更新了错误,所以你可以看到打印被执行了两次

标签: django pdf-generation


【解决方案1】:

看起来您在浏览器中关闭了选项卡,或者浏览器停止以其他方式接受来自服务器的响应。但是网络服务器并没有停止它的渲染并且仍然产生响应,但是没有响应谁。这就是你看到的原因:

ConnectionResetError: [Errno 104] Connection reset by peer

在该浏览器重试页面重新加载后,您会在日志中看到第二个请求。

因此,您需要了解它发生的原因。查看浏览器日志和 Dev.Tools 将向您显示哪些内容(状态、响应等)。

附:关于LoginRequiredMixin - 不知道可能由“重试”引起的浏览器内部问题,但我相信它仍然应该发送cookies和session_id

【讨论】:

  • 我可以找到一种 chrome 扩展 pdf.js 错误,并决定生成文件,在下载之前将其保存在服务器上。谢谢大家的帮助
【解决方案2】:

我相信我经历过这样的事情。

问题是,当您调用端点时,您在 URL 中调用它,最后没有“/”导致 DRF 返回 301 这会将您重定向到相同的路径,但末尾带有“/”。问题在于,在重定向之后,您会丢失标头和 cookie,从而无法通过身份验证。

这也解释了为什么您可以看到 2 个调用。

所以基本上如果你有这样的电话:

api/viewset/dosomethngs

到:

api/viewset/dosomethngs/

【讨论】:

  • 我使用 Weekly Métré 并且在我的 urls.py 中它被定义为 url(r' ^reports/weekly/metre/(?P[0-9]+)/$', views.WeeklyMetre.as_view(), name='WeeklyMetreReport'),
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-18
  • 2013-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多