Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python UnicodeDecodeError:Django使用weasyprint生成PDF_Python_Django_Django Models_Django Templates_Weasyprint - Fatal编程技术网

Python UnicodeDecodeError:Django使用weasyprint生成PDF

Python UnicodeDecodeError:Django使用weasyprint生成PDF,python,django,django-models,django-templates,weasyprint,Python,Django,Django Models,Django Templates,Weasyprint,我正在用Django制作一个应用程序。我想在浏览选择链接时生成pdf。因此,我使用了weasyprint模块来转换我的pdf。我导入weasyprint模块。但是当我运行那个应用程序时,我发现了一些错误。 这是views.py文件 def customersProfile(request, customer_id, sys_type): sys_type=sys_type area="profile" site_credit = site_credit1 time

我正在用Django制作一个应用程序。我想在浏览选择链接时生成pdf。因此,我使用了weasyprint模块来转换我的pdf。我导入weasyprint模块。但是当我运行那个应用程序时,我发现了一些错误。 这是views.py文件

def customersProfile(request, customer_id, sys_type):
    sys_type=sys_type
    area="profile"
    site_credit = site_credit1
    time_now=timezone.now()
    customers=get_object_or_404(CustomerInfo, pk=customer_id)

    html_string = render_to_string('shop/profile.html', {'customers': customers, 'todaydate': today_date,'site_name': 'Moon Telecom', 'time_now': time_now, 'site_credit': site_credit, 'area': area})
    html = HTML(string=html_string)
    result = html.write_pdf()


    response = HttpResponse(content_type='application/pdf;')
    response['Content-Disposition'] = 'inline; filename=list_people.pdf'
    response['Content-Transfer-Encoding'] = 'binary'
    with tempfile.NamedTemporaryFile(delete=True) as output:
        output.write(result)
        output.flush()
        output = open(output.name, 'r')
        response.write(output.read())

    return response
这是HTML文件。我想创建pdf这个html文件

<!DOCTYPE html>
<html>

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body style>

    <div class="container">
        <div class="row">
            <div class="col-lg-12">
                <div class="site_title" style="text-align:center; margin:0 auto">
                    <h3>মুন টেলিকম</h3>
                    <h3>
                        <a href="{% url 'shop:index' %}" target="_blank">{{site_name}}</a>
                    </h3>
                    <div class="invoice_info_one" style="width:100%; text-align:center">
                        <p>সকল প্রকার মোবাইল সেট, সীম কার্ড, মেমোরী কার্ড, MP-3, সোলার চার্জার, সোলার ফ্যান, মোবাইল ফোনের ব্যাটারী, চার্জার, ক্যাচিং,কাভার,হেডফোন, রেবন, ডিসপ্লে এবং ইলেট্রিক মালামাল বিক্রেতা</p>
                    </div>
                    <div class="invoice_location">
                        <p>জাহাঙ্গীর সুপার মার্কেট, ব্রীজ রোড, ফুলহাতা বাজার, মোডেলগঞ্জ।</p>
                    </div>
                    <div class="invoice_contact">
                        <p>01717-051200(সুকান্ত) 01828-163858(দোকান)</p>
                        <p><b>Email:</b> moontelecom2008@gmail.com</p>
                    </div>
                    <div class="copy_right">
                        {% if site_credit %}
                         <p>{{site_credit}}</p>
                        {% else %}
                            <a href="{% url 'shop:nothing' %}">#</a>
                        {% endif %}
                        <p></p>
                    </div>


                    <hr>
                </div>
            </div>
        </div>
        <div class="container">
            <div class="row">
                <div class="col-lg-12">
                    <div class="customer_info">
                        {% if customers.customer_name %}
                        <h2 style="font-size:15px">Customer Name:
                            <b> {{customers.customer_name}}</b>
                        </h2>
                        {% else %} <p> Name: দেওয়া হয়নি</p> {% endif %}

                        <p style="font-size:14px">Phone Number:
                            {% if customers.customer_mobile_no %}
                             {{customers.customer_mobile_no}}
                            {% else %}
                            No Mobile Number
                            {% endif %}
                        </p>
                        <p style="font-size:14px">Purchase Time: {{customers.customer_sell_date}}</p>
                        <p style="font-size:14px">invoice id: <b>{{customers.customer_uid}}</b></p>
                        <p>{{customers.product_warrenty}}</p>
                    </div>

                </div>
            </div>
        </div>
        <div class="table table-bordered">

            <table class="table">
                <thead>
                    <tr>


                        <th>Product Name</th>
                        <th>Product ID</th>
                        <th>Warrenty</th>
                        <th>QN</th>
                        <th>Price</th>

                    </tr>
                </thead>
                <tbody>
                    <tr>


                        <td>{{customers.customer_product_name}}</td>
                        <td>{{customers.customer_product_id}}</td>

                        <td>{% if customers.customer_product_warrenty == '' %}
                        <b>No Warrenty</b>
                        {% else %}
                        <b> {{customers.customer_product_warrenty}}</b> Month</td>
                        {% endif %}
                        <td>{{customers.customer_product_quantity}}</td>

                        <td>{{customers.customer_price}} Taka</td>


                    </tr>

                </tbody>
                <tr>
                    <td colspan="3"></td>

                    <td colspan="1">
                        <b>Total Amount</b>
                    </td>
                    <td colspan="1">
                        <b>{{customers.customer_price}}</b> Taka</td>
                </tr>
            </table>
             {% if customers.customer_conditions %}
            <div class="warning">
                <p style="font-size:8px; width:500px;line-height:15px;"><i>{{customers.customer_product_name}} {{customers.customer_conditions}}</i></p>
            </div>
            {% else %} {% endif %}




        </div>
    </div>

    <div class="footer">
        <div class="footer_info">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                       <div class="footer_info">
                        <p>Print date: {{time_now}}</p>
                            <p>
                                <b>বিঃদ্রঃ ডেলিভারির সময় মাল বুঝিয়া নিবেন। পরে কোন আপত্তী গ্রহনযোগ্য নয়</b>
                            </p>
                            <h5>বিক্রিত মাল ফেরত নেওয়া হয় না</h5>
                       </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</body>
这是完整的跟踪系统 环境:

Request Method: GET
Request URL: http://127.0.0.1:8000/shop/1/customerpage/customerprofile/

Django Version: 1.11.6
Python Version: 3.5.2
Installed Applications:
['shop.apps.ShopConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'crispy_forms',
 'wkhtmltopdf']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/asad/Desktop/smartshop/django-app/shop/views.py" in customersProfile
  333.         response.write(output.read())

File "/usr/lib/python3.5/codecs.py" in decode
  321.         (result, consumed) = self._buffer_decode(data, self.errors, final)

Exception Type: UnicodeDecodeError at /shop/1/customerpage/customerprofile/
Exception Value: 'utf-8' codec can't decode byte 0xe2 in position 10: invalid continuation byte

您正在以文本模式阅读pdf文件(
'r'


调用
HttpResponse.write
时,检查其输入是
str
还是
bytes
;如果输入是
str
,它将尝试对其进行编码,在这种情况下会导致错误。通过以二进制模式打开文件,您可以确保输入是
字节
,并且不会尝试编码。

非常好。但是创建pdf有点慢。我想快点。我该怎么做?如果我有UTF-8,它就可以工作了。但这个过程是缓慢的。response['Content-Transfer-Encoding']='UTF-8',tempfile.NamedTemporaryFile(delete=True)作为输出:output.write(result)output.flush()output=open(output.name,'rb')response.write(output.read())如何更快是一个不同的问题-你需要问一个新问题,而不是这个问题。+1,为我节省了一些宝贵的时间。奇怪的是,-r标志在Python2.7中工作正常,但在我升级到3.5时坏了,-rb修复了它。
Request Method: GET
Request URL: http://127.0.0.1:8000/shop/1/customerpage/customerprofile/

Django Version: 1.11.6
Python Version: 3.5.2
Installed Applications:
['shop.apps.ShopConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'crispy_forms',
 'wkhtmltopdf']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/asad/Desktop/smartshop/django-app/shop/views.py" in customersProfile
  333.         response.write(output.read())

File "/usr/lib/python3.5/codecs.py" in decode
  321.         (result, consumed) = self._buffer_decode(data, self.errors, final)

Exception Type: UnicodeDecodeError at /shop/1/customerpage/customerprofile/
Exception Value: 'utf-8' codec can't decode byte 0xe2 in position 10: invalid continuation byte
>>> response = HttpResponse(content_type='application/pdf')
>>> output = open('example.pdf', 'r')
>>> response.write(output.read())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  ...
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe2 in position 10: invalid continuation byte
>>> response = HttpResponse(content_type='application/pdf')
>>> output = open('example.pdf', 'rb')
>>> response.write(output.read())