如何正确读取和编码通过烧瓶发送的文本?

时间:2021-03-01 19:50:20

标签: python python-3.x flask unicode python-unicode

我编写了一个简单的 API 来读取和写入文件。最小版本如下:

import flask

class Web:

    def __init__(self):
        self.app = flask.Flask('web')
        self.app.add_url_rule('/read/<filename>', 'read', self.read)
        self.app.run(host="0.0.0.0", port=6543)

    def read(self, filename: str):
        return open(filename).read()  

Web()

考虑以下文件(将被读取的文件)。它在 Windows 记事本中保存为 UTF-8

ascii
éàçèïê

尝试通过 curl 下载时:

PS > curl http://localhost:6543/read/c5f89f95ef49492c82bdbcc133a5c567
ascii
éàçèïê

我试图将它重定向到一个文件,它也是一团糟:

enter image description here

看起来在“使用 open() 读取文件”→“通过烧瓶返回文件”链中的某个地方,我在编码/解码 Unicode 魔法时犯了一个错误。

1 个答案:

答案 0 :(得分:1)

尝试使用这种结构:

kick