GAE Python - CSV写入器出现ascii编码错误
我有一个Google App Engine的应用程序,它可以存储多种语言的数据,比如德语和俄语。为了做到这一点,我需要把字符串存储为UTF-8格式。幸运的是,因为我使用了webapp2.request处理器,这个过程是自动完成的。作为一个初学者,这让我避免了处理编码和解码数据时的复杂问题。
不过现在我想把内容写入一个CSV文件,似乎在使用csv.writer命令时,编码是必须的。我现在不太确定是应该解码还是编码,但目前我遇到的错误是:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-9: ordinal not in range(128)
我使用的代码是:
import csv, webapp2, codecs
class AdminShopExport(webapp2.RequestHandler):
def get(self):
shops = Shop.all()
shops.order('name')
self.response.headers['Content-Type'] = 'application/csv'
writer = csv.writer(self.response.out)
writer.writerow(["id", "name", "domain", "category"])
for shop in shops:
writer.writerow([shop.keyname, shop.name, shop.url, shop.category])
关于内容,错误目前是来自一个用俄语给出的类别。不过如前所述,这些字段中的任何一个都可能包含UTF-8字符。处理这个问题的最佳方法是什么呢?谢谢你的帮助!