我想访问MySQL数据库,检索一些数据,使用模板和Jinja2及更高版本创建HTML文档,使用weasyprint将其转换为PDF。
#!/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'>
如果我使用&#34;&#34;来代替所有模板变量,那么效果很好。但我需要使用从数据库中检索到的数据。任何想法为什么它不起作用?
答案 0 :(得分:0)
我修好了! http://blog.rastersoft.com/?p=15这是解决方案。 它是用西班牙语写的,所以我将简要地告诉你这是什么问题。
MySQL使用Latin1但Python使用UTF-8。所以,我必须将表转换为utf8,然后使用utf8将python连接到数据库。您可以在网页中看到命令。