如果将上一章的脚本中的返回行改成以下形式的话:
修改前: return [response_body]
修改后: return response_body
然后在运行一次. 如果是在一个比较老的机器上运行的话,你可以明显的感觉到它变慢了. 那是因为服务器一次只向客户端发送要返回的字符串中的一个字节(即在要返回的字符串上进行迭代). 所以不要忘了将返回信息封装到一个性能比较好的迭代器中,如 数组(list).
如果一个迭代器返回不止一条字符串, 那么响应信息的长度则为所有这些字符串长度之和. 见如下脚本:
#! /usr/bin/env python
from wsgiref.simple_server import make_server
def application(environ, start_response):
response_body = [
'%s: %s' % (key, value) for key, value in sorted(environ.items())
]
response_body = '\n'.join(response_body)
# 添加字符串到响应信息载体
response_body = [
'The Beggining\n',
'*' * 30 + '\n',
response_body,
'\n' + '*' * 30 ,
'\nThe End'
]
# 返回信息内容长度是所有字符串长度之和
content_length = sum([len(s) for s in response_body])
status = '200 OK'
response_headers = [
('Content-Type', 'text/plain'),
('Content-Length', str(content_length))
]
start_response(status, response_headers)
return response_body
httpd = make_server('localhost', 8051, application)
httpd.handle_request()
运行脚本并监听
http://localhost:8051/ 试试看.