2015-09-03 60 views
0

我想访问MySQL数据库,检索一些数据,使用模板和Jinja2及更高版本创建HTML文档,使用weasyprint将其转换为PDF。Jinja的模板变形

#!/usr/bin/python 
# -*- coding: utf-8 -*- 
import MySQLdb 
from jinja2 import Environment, FileSystemLoader 
from weasyprint import HTML 
import sys 


# Open database connection 
db = MySQLdb.connect("localhost","haritz","haritz","appglass") 

# prepare a cursor object using cursor() method 
cursor = db.cursor() 

# Prepare SQL query to INSERT a record into the database. 
sql = "A BIG SELECT" 

try: 
    # Execute the SQL command 
    cursor.execute("USE myDB;") 
    cursor.execute(sql) 
    # Fetch all the rows in a list of lists. 
    results = cursor.fetchall() 
    for row in results: 
     cantidad = row[0] 
     Fecha_pedido = row[1] 
     descripcion = row[2] 
     Precio_unitario = row[3] 
     Referencia_interna = row[4] 
     referencia_proveedor = row[5] 
     Unidad_de_medida = row[6] 
     razon_social = row[7] 
     direccion = row[8] 
     Nombre_persona_contacto = row[9] 
     # Now print fetched result 
     print "env" 
     env = Environment(loader=FileSystemLoader('.')) 
     print "template" 
     template = env.get_template("plantilla.html") 
     print "template_vars" 
     template_vars = { "razonSocial": str(razon_social), 
         "personaContacto": str(Nombre_persona_contacto), 
         "direccion": str(direccion), 
         "numPedido": "AAAAAAAAA", 
         "refExtena": str(referencia_proveedor), 
         "descripcion": str(descripcion), 
         "refInterna": str(Referencia_interna), 
         "cantidad" : str(cantidad), 
         "unid": str(Unidad_de_medida), 
         "costeUnit": str(Precio_unitario), 
         "importe": "0"} 

     print "html_out" 
     html_out = template.render(template_vars) 

     print "write_pdf" 
     HTML(string=html_out).write_pdf("Pedido.pdf") 
except: 
    print "Error: unable to fecth data", sys.exc_info()[0] 

# disconnect from server 
db.close() 

我得到的输出如下:

env 
template 
template_vars 
html_out 
Error: unable to fecth data <type 'exceptions.UnicodeDecodeError'> 

如果我代替所有的模板通过字符串中使用“东西”瓦尔,它工作得很好。但我需要使用从数据库中检索的数据。任何想法,为什么它不工作?

回答

0

我修好了! http://blog.rastersoft.com/?p=15这里是解决方案。 这是西班牙文,所以我会简单地告诉你问题是什么。

MySQL使用Latin1,但Python使用UTF-8。所以,我必须将表转换为utf8,然后使用utf8将python连接到数据库。您可以在网页中看到这些命令。