WSGI接口定义非常简单,一个函数就可以响应HTTP请求。
[Hello Word]
定义函数
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return '<h1>Hello, web!</h1>'
start_response('200 OK', [('Content-Type', 'text/html')])
* wsgi application就是一个普通的callable对象,当有请求到来时,wsgi server会调用这个wsgi app。这个对象接收两个参数,通常为environ,start_response。environ就像前面介绍的,可以理解为环境变量,跟一次请求相关的所有信息都保存在了这个环境变量中,包括服务器信息,客户端信息,请求信息。start_response是一个callback函数,wsgi application通过调用start_response*,将response headers/status 返回给wsgi server。
启动服务
# 导入库
from wsgiref.simple_server import make_server
# 创建一个服务器,IP地址为空,端口是8000,处理函数是application:
httpd = make_server('', 8000, application)
print "Serving HTTP on port 8000..."
# 开始启动监听
httpd.serve_forever()
[完整代码]
from wsgiref.simple_server import make_server
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return '
Hello, web!
'
httpd = make_server('', 8000, application)
print "Serving HTTP on port 8000..."
httpd.serve_forever()
运行结果
本文始发于微信公众号(inn0team):打造python web 框架(二): Python WSGI第一个应用
- 左青龙
- 微信扫一扫
-
- 右白虎
- 微信扫一扫
-
评论