我已经开始学习烧瓶了,我一直在迭代csv。
我想通过一个列出财富500的csv并在页面上打印它们。 CSV包含公司,收入,利润和排名。
我得到的错误是:
File "/Project/FLASK/app/templates/companies.html", line 15, in block "content"
<td> {{ keys.Company }} </td>
UnicodeDecodeError: 'utf8' codec can't decode byte 0x8e in position 3: invalid start byte
以下是companies.html
{% extends "base.html" %}
{% block content %}
<table>
<tr>
<td> Company </td>
<td> Revenues </td>
<td> Profits </td>
<td> Rank </td>
</tr>
{% for keys in companies %}
<tr>
<td> {{ keys.Company }} </td>
<td> {{ keys.Revenues }} </td>
<td> {{ keys.Profits }} </td>
<td> {{ keys.Rank }} </td>
</tr>
{% endfor %}
</table>
{% endblock %}
最后是我的views.py文件:
@app.route('/companies')
def companies():
import csv
with open('companies.csv','rU') as f:
companies = csv.DictReader(f)
return render_template("companies.html",
title='Home',
companies=companies)
如果我将{{keys.Company}}更改为{{keys}},则会显示字典,但是当我更改为keys.Company或keys.Revenues时,我会收到相同的错误
答案 0 :(得分:0)
在Jinja2中,您必须将unicode传递给只包含ASCII字符的渲染函数。所以改变为:
<td> {{ keys.Company.decode('utf-8') }} </td>