加入收藏 | 设为首页 | 会员中心 | 我要投稿 鞍山站长网 (https://www.0412zz.com/)- 应用安全、运维、云计算、5G、云通信!
当前位置: 首页 > 站长资讯 > 外闻 > 正文

Python 中的 HTTP 服务器

发布时间:2019-07-07 00:28:16 所属栏目:外闻 来源:Python中文社区
导读:David Wheeler有一句名言:计算机科学中的任何问题,都可以通过加上另一层间接的中间层解决。 为了提高Python网络服务的可移植性,Python社区在PEP 333中提出了Web服务器网关接口(WSGI,Web Server Gateway Interface)。 WSGL标准就是添加了一层中间层。通

下面第一段代码是用于返回当前时间的原始WSGI可调用对象。

  1. #!/usr/bin/env python3 
  2. # A simple HTTP service built directly against the low-level WSGI spec. 
  3.  
  4. import time 
  5.  
  6. def app(environ, start_response): 
  7.     host = environ.get('HTTP_HOST', '127.0.0.1') 
  8.     path = environ.get('PATH_INFO', '/') 
  9.     if ':' in host: 
  10.         host, port = host.split(':', 1) 
  11.     if '?' in path: 
  12.         path, query = path.split('?', 1) 
  13.     headers = [('Content-Type', 'text/plain; charset=utf-8')] 
  14.     if environ['REQUEST_METHOD'] != 'GET': 
  15.         start_response('501 Not Implemented', headers) 
  16.         yield b'501 Not Implemented' 
  17.     elif host != '127.0.0.1' or path != '/': 
  18.         start_response('404 Not Found', headers) 
  19.         yield b'404 Not Found' 
  20.     else: 
  21.         start_response('200 OK', headers) 
  22.         yield time.ctime().encode('ascii') 

第一段比较冗长。下面使用第三方库简化原始WGSI的模式方法。

第一个示例是使用WebOb编写的可调用对象返回当前时间。

  1. #!/usr/bin/env python3 
  2. # A WSGI callable built using webob. 
  3.  
  4. import time, webob 
  5.  
  6. def app(environ, start_response): 
  7.     request = webob.Request(environ) 
  8.     if environ['REQUEST_METHOD'] != 'GET': 
  9.         response = webob.Response('501 Not Implemented', status=501) 
  10.     elif request.domain != '127.0.0.1' or request.path != '/': 
  11.         response = webob.Response('404 Not Found', status=404) 
  12.     else: 
  13.         response = webob.Response(time.ctime()) 
  14.     return response(environ, start_response) 
  15. 第二个是使用Werkzeug编写的WSGI可调用对象返回当前时间。 

第二个是使用Werkzeug编写的WSGI可调用对象返回当前时间。

  1. #!/usr/bin/env python3 
  2. # A WSGI callable built using Werkzeug. 
  3.  
  4. import time 
  5. from werkzeug.wrappers import Request, Response 
  6.  
  7. @Request.application 
  8. def app(request): 
  9.     host = request.host 
  10.     if ':' in host: 
  11.         host, port = host.split(':', 1) 
  12.     if request.method != 'GET': 
  13.         return Response('501 Not Implemented', status=501) 
  14.     elif host != '127.0.0.1' or request.path != '/': 
  15.         return Response('404 Not Found', status=404) 
  16.     else: 
  17.         return Response(time.ctime()) 

大家可以对比这两个库在简化操作时的不同之处,Werkzeug是Flask框架的基础。

(编辑:鞍山站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

推荐文章
    热点阅读