Python中实现WSGI的框架
发布时间:2024-08-27 13:25:39

1、说明
Application对WSGI进行了简单的包装,因为WSGI函数返回是一个可迭代的对象,所以需要实现__iter__方法,控制客户端的请求路由,并返回不同的输出。
2、实例
fromwsgiref.simple_serverimportmake_server
classApplication(object):
def__init__(self,environ,start_response):
self.start_response=start_response
self.path=environ['PATH_INFO']
def__iter__(self):
ifself.path=='/':
status='200OK'
response_headers=[('Content-type','text/html')]
self.start_response(status,esponse_headers)
yield'<h1>Hello,World!</h1>'.encode('utf-8')
elifself.path=='/wsgi':
status='200OK'
response_headers=[('Content-type','text/html')]
self.start_response(status,response_headers)
yield'<h1>Hello,WSGI!</h1>'.encode('utf-8')
else:
status='404NOTFOUND'
response_headers=[('Content-type','text/html')]
self.start_response(status,response_headers)
yield'<h1>NOTFOUND404404</h1>'.encode('utf-8')
if__name__=="__main__":
app=make_server('127.0.0.1',8000,Application)
print('ServingHTPontport80000...')
app.serve_forever()以上是Python中实现WSGI的框架,希望对大家有所帮助。更多Python学习推荐:python教学
本文教程操作环境:windows7系统Python 3.9.1,DELL G3电脑。
下一篇 Python中WSGI的使用
