下面第一段代码是用于返回当前时间的原始WSGI可调用对象。
- #!/usr/bin/env python3
- # A simple HTTP service built directly against the low-level WSGI spec.
-
- import time
-
- def app(environ, start_response):
- host = environ.get('HTTP_HOST', '127.0.0.1')
- path = environ.get('PATH_INFO', '/')
- if ':' in host:
- host, port = host.split(':', 1)
- if '?' in path:
- path, query = path.split('?', 1)
- headers = [('Content-Type', 'text/plain; charset=utf-8')]
- if environ['REQUEST_METHOD'] != 'GET':
- start_response('501 Not Implemented', headers)
- yield b'501 Not Implemented'
- elif host != '127.0.0.1' or path != '/':
- start_response('404 Not Found', headers)
- yield b'404 Not Found'
- else:
- start_response('200 OK', headers)
- yield time.ctime().encode('ascii')
第一段比较冗长。下面使用第三方库简化原始WGSI的模式方法。
第一个示例是使用WebOb编写的可调用对象返回当前时间。
- #!/usr/bin/env python3
- # A WSGI callable built using webob.
-
- import time, webob
-
- def app(environ, start_response):
- request = webob.Request(environ)
- if environ['REQUEST_METHOD'] != 'GET':
- response = webob.Response('501 Not Implemented', status=501)
- elif request.domain != '127.0.0.1' or request.path != '/':
- response = webob.Response('404 Not Found', status=404)
- else:
- response = webob.Response(time.ctime())
- return response(environ, start_response)
- 第二个是使用Werkzeug编写的WSGI可调用对象返回当前时间。
第二个是使用Werkzeug编写的WSGI可调用对象返回当前时间。
- #!/usr/bin/env python3
- # A WSGI callable built using Werkzeug.
-
- import time
- from werkzeug.wrappers import Request, Response
-
- @Request.application
- def app(request):
- host = request.host
- if ':' in host:
- host, port = host.split(':', 1)
- if request.method != 'GET':
- return Response('501 Not Implemented', status=501)
- elif host != '127.0.0.1' or request.path != '/':
- return Response('404 Not Found', status=404)
- else:
- return Response(time.ctime())
大家可以对比这两个库在简化操作时的不同之处,Werkzeug是Flask框架的基础。 (编辑:PHP编程网 - 黄冈站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|