知行编程网知行编程网  2022-11-22 11:30 知行编程网 隐藏边栏  3 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于Python中实现WSGI的框架的相关知识,希望可以帮到处于编程学习途中的小伙伴

一个用 Python 实现 WSGI 的框架


1、说明

Application类对WSGI做了简单的封装。如前所述,WSGI函数返回一个可迭代对象,所以需要实现一个__iter__方法,控制客户端的请求路由,返回不同的输出。


2、实例

from wsgiref.simple_server import make_server
 
class Application(object):
 
    def __init__(self, environ, start_response):
        self.start_response = start_response
        self.path = environ['PATH_INFO']
 
    def __iter__(self):
        if self.path == '/':
            status = '200 OK'
            response_headers = [('Content-type', 'text/html')]
            self.start_response(status, esponse_headers)
            yield '<h1>Hello,World!</h1>'.encode('utf-8')
 
        elif self.path == '/wsgi':
            status = '200 OK'
            response_headers = [('Content-type', 'text/html')]
            self.start_response(status, response_headers)
            yield '<h1>Hello,WSGI!</h1>'.encode('utf-8')
 
        else:
            status = '404 NOT FOUND'
            response_headers = [('Content-type', 'text/html')]
            self.start_response(status, response_headers)
            yield '<h1>404 NOT FOUND</h1>'.encode('utf-8')
 
if __name__ == "__main__":
    app = make_server('127.0.0.1', 8000, Application)
    print('Serving HTTP on port 8000...')
    app.serve_forever()


本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享