WSGI底层HTTP请求接口处理

来源:互联网 发布:数据库部门英语简写 编辑:程序博客网 时间:2024/06/05 04:24

1. hello.py 负责编写网页显示的函数代码

#coding=utf-8__author__ = 'mac'#WSGI#application()函数就是符合WSGI标准的一个HTTP处理函数,它接收两个参数:#.environ:一个包含所有HTTP请求信息的dict对象#.start_response:一个发送HTTP响应的函数def application(environ,start_response):    #start_respnse接收两个参数,一个响应码,一个是一组list表示HTTP Header    start_response('200 ok',[('content-type','text/html')])    #添加参数作为url的返回值,即http://localhost:8000/www会显示Hello,www!    body='<h1>Hello,%s!</h1>' % (environ['PATH_INFO'][1:] or 'web')    #函数的返回值    # return [b'<h1>Hello,web!</h1>']    return [body.encode('utf-8')]
2.server.py服务启动服务端
#coding=utf-8__author__ = 'mac'#负责启动WSGI服务器,加载application()函数from wsgiref.simple_server import make_server#导入我们自己编写的application函数from hello import application#创建一个服务器,IP地址为空,端口是8000,处理函数是applicationhttpd=make_server('',8000,application)print ('Serving HTTP on port 8000...')httpd.serve_forever()

3.运行server.py,打开localhost:8000的网页查看显示信息