Google 云存储 API 写入具有特殊字符的文件与常规 python 文件
Google Cloud Storage API write files with special characters vs regular python files
我正在使用 Google App Engine 将新文件写入 Google 云存储桶,以便最终在浏览器中提供服务。通常在我的本地计算机上,这会写一个很好的文本文件,我可以打开它并按预期查看测试字符:
with open('new_file.txt', 'w') as f:
f.write(u'é'.encode('utf-8'))
当我在记事本中打开 new_file.txt
时,它正确显示为 é
。
但是当我在 Google 云存储上尝试类似的过程时:
with gcs.open('/mybucket/newfile.txt', 'w', content_type='text/html') as f:
f.write(u'é'.encode('utf-8'))
我的文件在浏览器中提供,所有特殊字符都乱七八糟,在这种情况下它输出 é
.
HTTP 1.1 的默认字符集是 ISO-8859-1。
如果您希望浏览器将您的文本解释为 UTF-8,您应该设置 content-type header 以包含字符集,如下所示:
with gcs.open('/mybucket/newfile.txt', 'w', content_type='text/html; charset=utf-8') as f:
我正在使用 Google App Engine 将新文件写入 Google 云存储桶,以便最终在浏览器中提供服务。通常在我的本地计算机上,这会写一个很好的文本文件,我可以打开它并按预期查看测试字符:
with open('new_file.txt', 'w') as f:
f.write(u'é'.encode('utf-8'))
当我在记事本中打开 new_file.txt
时,它正确显示为 é
。
但是当我在 Google 云存储上尝试类似的过程时:
with gcs.open('/mybucket/newfile.txt', 'w', content_type='text/html') as f:
f.write(u'é'.encode('utf-8'))
我的文件在浏览器中提供,所有特殊字符都乱七八糟,在这种情况下它输出 é
.
HTTP 1.1 的默认字符集是 ISO-8859-1。
如果您希望浏览器将您的文本解释为 UTF-8,您应该设置 content-type header 以包含字符集,如下所示:
with gcs.open('/mybucket/newfile.txt', 'w', content_type='text/html; charset=utf-8') as f: