0

我是 Python 新手。我正在运行以下简单的 Web 服务器:

from wsgiref.simple_server import make_server
from io import BytesIO

def message_wall_app(environ, start_response):
    output = BytesIO()
    status = '200 OK' # HTTP Status
    headers = [('Content-type', 'text/html; charset=utf-8')]
    start_response(status, headers)
    print(b"<h1>Message Wall</h1>",file=output)
##    if environ['REQUEST_METHOD'] == 'POST': 
##        size = int(environ['CONTENT_LENGTH'])
##        post_str = environ['wsgi.input'].read(size)
##        print(post_str,"<p>", file=output)
##    print('<form method="POST">User: <input type="text" '
##          'name="user">Message: <input type="text" '
##          'name="message"><input type="submit" value="Send"></form>', 
##           file=output)         
    # The returned object is going to be printed
    return [output.getvalue()]     

httpd = make_server('', 8000, message_wall_app)
print("Serving on port 8000...")

# Serve until process is killed
httpd.serve_forever()

不幸的是,我收到以下错误:

Traceback (most recent call last):
  File "C:\Users\xxx\Python36\lib\wsgiref\handlers.py", line 137, in run
    self.result = application(self.environ, self.start_response)
  File "C:/xxx/Python/message_wall02.py", line 9, in message_wall_app
    print("<h1>Message Wall</h1>".encode('ascii'),file=output)
TypeError: a bytes-like object is required, not 'str'....

请建议我做错了什么。谢谢。

4

1 回答 1

3

您不能用于print()写入二进制文件。在写入文本文件对象之前print() 将参数转换为。str()

print()功能文档

将对象打印到文本流 文件,以sep分隔,后跟end。[...]

所有非关键字参数都像 dos 一样转换为字符串str()写入流,由sep分隔,后跟end

大胆强调我的。请注意,文件对象必须是文本流,而不是二进制流。

要么写入包装对象的对象TextIOWrapper()BytesIO()调用对象直接写入对象,要么写入对象并在最后对结果字符串值进行编码。.write()BytesIO()bytesStringIO()

于 2019-03-04T20:19:40.740 回答