Internal Server Error 500 (Nginx) when I try to generate PDF by Weasyprint

Asked

Viewed 120 times

1

Good morning, you guys.

I have a problem in my application and I tried everything and I could not solve.

I decided to generate dynamic PDF in my application and for this I used the Weasyprint library. The function is called by Django Admin and renders an html template to generate the PDF. In my development machine the application behaved smoothly and everything went well. However, when I uploaded to the web server the PDF generator shows an error Internal Server Error. After a lot of head-breaking I realized that, strangely, this error only occurs when the client’s name is stressed. Other variables even if they are accented render smoothly.

I am using Django 2.2.3 and my application is hosted on Digital Ocean. I am using Gunicorn and Ngnix.

Follow my function to generate PDF:

def generate_pdf_procuracao(self, request, obj):
        # Antes de renderizar o template pega-se as variáveis da forenkey e passa para a variável endereco
        endereco = f'{obj.cliente.endereco_set.first().logradouro}, {obj.cliente.endereco_set.first().numero}, {obj.cliente.endereco_set.first().bairro} - {obj.cliente.endereco_set.first().cidade}/{obj.cliente.endereco_set.first().uf} - {obj.cliente.endereco_set.first().cep}'
        get_email = '' # Seta um valor padrão para o e-mail para o caso de o cliente não o possuir
        for email in obj.cliente.contato_set.all():
            if email.tipo_contato == '4':
                get_email = email.contato
        context = {
            'obj': obj,
            'endereco': endereco,
            'get_email': get_email
        }
        if obj.alfabetizado:
            template = 'reports/pdf_procuracao_template-1.html'
        else:
            template = 'reports/pdf_procuracao_template-2.html'
        html_string = render_to_string(template, context)

        html = HTML(string=html_string)
        html.write_pdf(target='/tmp/{}.pdf'.format(obj));

        fs = FileSystemStorage('/tmp')
        with fs.open('{}.pdf'.format(obj)) as pdf:
            response = HttpResponse(pdf, content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename="Procuracao_-_{}.pdf"'.format(obj)
            return response

        return response

    generate_pdf_procuracao.label = 'Gerar PDF'
    generate_pdf_procuracao.short_description = 'Clique para gerar o PDF dessa Procuração. Certifique-se de que o registro já foi salvo'

    change_actions = ('generate_pdf_procuracao',)

Ngnix access.log log

100.00.000.000 - - [07/Jul/2019:06:16:53 +0000] "GET /admin/ged/hipossuficiencia/3/actions/generate_pdf_procuracao/ HTTP/1.1" 500 141 "http://www.hostname.adv.br/admin/ged/hipossuficiencia/3/change/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"

In my rendered template I have already put the tags:

<!DOCTYPE HTML>
<html lang=”pt-br”>
<head>
<meta charset=”UTF-8”>

But even so if the customer’s name is accented it triggers the error Internal Server Error. What most intrigues is that this error only appears if the client’s name is accentuated, because all other names may accentuate that it does not generate the error.

Even in the admin.py from my app I put # coding: utf-8, but none of that solved.

This is the template line that loads the name variable:

<p style="text-align: justify;">Pela presente e na melhor forma de direito, <strong>{{ obj.cliente|upper }}</strong>, brasileiro(a), {{ obj.cliente.get_estado_civil_display|lower }}, {{ obj.cliente.profissao|lower }}, RG: {{ obj.cliente.rg }}, portador do CPF: {{ obj.cliente.cpf }}, {{ endereco }}, e-mail:&nbsp;<a href="mailto:{{ get_email }}"><u>{{ get_email }}</u></a>,&nbsp;&nbsp;para os fins espec&iacute;ficos do benepl&aacute;cito previsto&nbsp;no inciso LXXIV, do artigo 5&ordm; da Constitui&ccedil;&atilde;o Federal, c/c a Lei n&ordm; 1.060/50, artigo 1&ordm; da Lei n&ordm; 7.115/83 e nos termos do artigo 98 e seguintes da Lei 13.105/2015 (C&oacute;digo de Processo Civil),&nbsp;<strong>DECLARA</strong>, sob as penas da lei, n&atilde;o ter condi&ccedil;&otilde;es financeiras de arcar com custas e despesas processuais, sem preju&iacute;zo do pr&oacute;prio sustento e de sua fam&iacute;lia, raz&atilde;o pela qual requer o deferimento da concess&atilde;o dos benef&iacute;cios da <strong>JUSTI&Ccedil;A GRATUITA</strong>.&nbsp;Requeiro, ainda, que o benef&iacute;cio abranja todos os atos do processo.</p>

Somebody’s been through this problem and they know how to fix it?

From now on, thank you.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.