• 技术文章 >Python技术 >Python基础教程

    Python中实现WSGI的框架

    小妮浅浅小妮浅浅2021-05-25 09:40:04原创2785

    1、说明

    Application类对WSGI又做了一层简单的封装,由于上面说过WSGI函数返回的是一个可以迭代对象,所以需要实现一个__iter__方法,里面控制了客户端的请求路由并且返回不同的输出。

    2、实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    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()

    以上就是Python中实现WSGI的框架,希望对大家有所帮助。更多Python学习推荐:python教学

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

    专题推荐:python wsgi
    上一篇:Python中WSGI的使用 下一篇:Python迭代器的基本方法有几个

    相关文章推荐

    • python BytesIO操作二进制数据• Python对象转换为JSON• Python中Impala的使用• Python中pdb设置断点• Python3.8有哪些新特性?• Python中WSGI的使用

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网