Skip to main content
 首页 » 编程设计

python之Python 速成书 message_wall01.py

2025年05月04日10lori

我想知道是否有人可以帮我弄清楚为什么我一直收到错误 AssertionError: Header names/values must be of type str (got b'Content-type') 127.0.0.1 - - [26/Mar/2015 20:50:52] "GET/favicon.ico HTTP/1.1"500 59. 代码来自 Manning 出版社的“The Quick Python Book”。

from wsgiref.simple_server import make_server 
 
def message_wall_app(environ, start_response): 
    status = b'200 OK' # HTTP Status 
    headers = [(b'Content-type', b'text/html; charset=utf-8')]        
    start_response(status, headers) 
 
    # The returned object is going to be printed 
    return ["<h1>Message Wall</h1>"] 
 
httpd = make_server('', 8000, message_wall_app) 
print("Serving on port 8000...") 
 
# Serve until process is killed 
httpd.serve_forever() 

请您参考如下方法:

从以下位置删除 b:

status = '200 OK' # HTTP Status 
headers = [('Content-type', 'text/html; charset=utf-8')] 

并添加到return ["<h1>Message Wall</h1>"] .你读了unicode/str然后写bytes .

旧文档有一个错误,其中示例使用了 b'200 OK'等..这本书可能是基于什么的,有一个旧的错误报告here .当前docs显示正确的用法。

完成后,您将在 http://localhost:8000/ 处看到输出并且没有错误。