用Python写一个简单的Web框架

开发 后端
本文尝试写一个类似web.py的Web框架。好吧,我承认我夸大其辞了:首先,web.py并不简单;其次,本文只重点实现了 URL调度(URL dispatch)部分。

用Python写一个简单的Web框架

  •  一、概述
  • 二、从demo_app开始
  • 三、WSGI中的application
  • 四、区分URL
  • 五、重构
    • 1、正则匹配URL
    • 2、DRY
    • 3、抽象出框架
  • 六、参考

一、概述

在Python中,WSGI(Web Server Gateway Interface)定义了Web服务器与Web应用(或Web框架)之间的标准接口。在WSGI的规范下,各种各样的Web服务器和Web框架都可以很好的交互。

由于WSGI的存在,用Python写一个简单的Web框架也变得非常容易。然而,同很多其他的强大软件一样,要实现一个功能丰富、健壮高效的Web框架并非易事;如果您打算这么做,可能使用一个现成的Web框架(如 Django、Tornado、web.py 等)会是更合适的选择。

本文尝试写一个类似web.py的Web框架。好吧,我承认我夸大其辞了:首先,web.py并不简单;其次,本文只重点实现了 URL调度(URL dispatch)部分。

二、从demo_app开始

首先,作为一个初步体验,我们可以借助 wsgiref.simple_server 来搭建一个简单无比(trivial)的Web应用:

  1. #!/usr/bin/env python 
  2.  
  3. # -*- coding: utf-8 -*- 
  4.  
  5.   
  6.  
  7. from wsgiref.simple_server import make_server, demo_app 
  8.  
  9.   
  10.  
  11. httpd = make_server('', 8086, demo_app) 
  12.  
  13. sa = httpd.socket.getsockname() 
  14.  
  15. print 'http://{0}:{1}/'.format(*sa) 
  16.  
  17.   
  18.  
  19. # Respond to requests until process is killed 
  20.  
  21. httpd.serve_forever()  

运行脚本:

  1. $ python code.py 
  2.  
  3. http://0.0.0.0:8086/  

打开浏览器,输入http://0.0.0.0:8086/后可以看到:一行”Hello world!” 和 众多环境变量值。

三、WSGI中的application

WSGI中规定:application是一个 可调用对象(callable object),它接受 environ 和 start_response 两个参数,并返回一个 字符串迭代对象。

其中,可调用对象 包括 函数、方法、类 或者 具有__call__方法的 实例;environ 是一个字典对象,包括CGI风格的环境变量(CGI-style environment variables)和 WSGI必需的变量(WSGI-required variables);start_response 是一个可调用对象,它接受两个 常规参数(status,response_headers)和 一个 默认参数(exc_info);字符串迭代对象 可以是 字符串列表、生成器函数 或者 具有__iter__方法的可迭代实例。更多细节参考 Specification Details。

The Application/Framework Side 中给出了一个典型的application实现:

  1. #!/usr/bin/env python 
  2.  
  3. # -*- coding: utf-8 -*- 
  4.  
  5.   
  6.  
  7. """application.py""" 
  8.  
  9.   
  10.  
  11. def simple_app(environ, start_response): 
  12.  
  13.     """Simplest possible application object""" 
  14.  
  15.     status = '200 OK' 
  16.  
  17.     response_headers = [('Content-type''text/plain')] 
  18.  
  19.     start_response(status, response_headers) 
  20.  
  21.     return ['Hello world!\n' 

现在用simple_app来替换demo_app:

  1. #!/usr/bin/env python 
  2.  
  3. # -*- coding: utf-8 -*- 
  4.  
  5.   
  6.  
  7. """code.py""" 
  8.  
  9.   
  10.  
  11. from wsgiref.simple_server import make_server 
  12.  
  13. from application import simple_app as app 
  14.  
  15.   
  16.  
  17. if __name__ == '__main__'
  18.  
  19.     httpd = make_server('', 8086, app) 
  20.  
  21.     sa = httpd.socket.getsockname() 
  22.  
  23.     print 'http://{0}:{1}/'.format(*sa) 
  24.  
  25.   
  26.  
  27.     # Respond to requests until process is killed 
  28.  
  29.     httpd.serve_forever()  

运行脚本code.py后,访问http://0.0.0.0:8086/就可以看到那行熟悉的句子:Hello world!

四、区分URL

倒腾了一阵子后,您会发现不管如何改变URL中的path部分,得到的响应都是一样的。因为simple_app只识别host+port部分。

为了对URL中的path部分进行区分处理,需要修改application.py的实现。

首先,改用 类 来实现application:

  1. #!/usr/bin/env python 
  2.  
  3. # -*- coding: utf-8 -*- 
  4.  
  5.   
  6.  
  7. """application.py""" 
  8.  
  9.   
  10.  
  11. class my_app: 
  12.  
  13.     def __init__(self, environ, start_response): 
  14.  
  15.         self.environ = environ 
  16.  
  17.         self.start = start_response 
  18.  
  19.   
  20.  
  21.     def __iter__(self): 
  22.  
  23.         status = '200 OK' 
  24.  
  25.         response_headers = [('Content-type''text/plain')] 
  26.  
  27.         self.start(status, response_headers) 
  28.  
  29.         yield "Hello world!\n"  

然后,增加对URL中path部分的区分处理:

  1. #!/usr/bin/env python 
  2.  
  3. # -*- coding: utf-8 -*- 
  4.  
  5.   
  6.  
  7. """application.py""" 
  8.  
  9.   
  10.  
  11. class my_app: 
  12.  
  13.     def __init__(self, environ, start_response): 
  14.  
  15.         self.environ = environ 
  16.  
  17.         self.start = start_response 
  18.  
  19.   
  20.  
  21.     def __iter__(self): 
  22.  
  23.         path = self.environ['PATH_INFO'
  24.  
  25.         if path == "/"
  26.  
  27.             return self.GET_index() 
  28.  
  29.         elif path == "/hello"
  30.  
  31.             return self.GET_hello() 
  32.  
  33.         else
  34.  
  35.             return self.notfound() 
  36.  
  37.   
  38.  
  39.     def GET_index(self): 
  40.  
  41.         status = '200 OK' 
  42.  
  43.         response_headers = [('Content-type''text/plain')] 
  44.  
  45.         self.start(status, response_headers) 
  46.  
  47.         yield "Welcome!\n" 
  48.  
  49.   
  50.  
  51.     def GET_hello(self): 
  52.  
  53.         status = '200 OK' 
  54.  
  55.         response_headers = [('Content-type''text/plain')] 
  56.  
  57.         self.start(status, response_headers) 
  58.  
  59.         yield "Hello world!\n" 
  60.  
  61.   
  62.  
  63.     def notfound(self): 
  64.  
  65.         status = '404 Not Found' 
  66.  
  67.         response_headers = [('Content-type''text/plain')] 
  68.  
  69.         self.start(status, response_headers) 
  70.  
  71.         yield "Not Found\n"  

修改code.py中的from application import simple_app as app,用my_app来替换simple_app后即可体验效果。

五、重构

上面的代码虽然奏效,但是在编码风格和灵活性方面有很多问题,下面逐步对其进行重构。

1、正则匹配URL

消除URL硬编码,增加URL调度的灵活性:

  1. #!/usr/bin/env python 
  2.  
  3. # -*- coding: utf-8 -*- 
  4.  
  5.   
  6.  
  7. """application.py""" 
  8.  
  9.   
  10.  
  11. import re ##########修改点 
  12.  
  13.   
  14.  
  15. class my_app: 
  16.  
  17.   
  18.  
  19.     urls = ( 
  20.  
  21.         ("/""index"), 
  22.  
  23.         ("/hello/(.*)""hello"), 
  24.  
  25.     ) ##########修改点 
  26.  
  27.   
  28.  
  29.     def __init__(self, environ, start_response): 
  30.  
  31.         self.environ = environ 
  32.  
  33.         self.start = start_response 
  34.  
  35.   
  36.  
  37.     def __iter__(self): ##########修改点 
  38.  
  39.         path = self.environ['PATH_INFO'
  40.  
  41.         method = self.environ['REQUEST_METHOD'
  42.  
  43.   
  44.  
  45.         for pattern, name in self.urls: 
  46.  
  47.             m = re.match('^' + pattern + '$', path) 
  48.  
  49.             if m: 
  50.  
  51.                 # pass the matched groups as arguments to the function 
  52.  
  53.                 args = m.groups() 
  54.  
  55.                 funcname = method.upper() + '_' + name 
  56.  
  57.                 if hasattr(self, funcname): 
  58.  
  59.                     func = getattr(self, funcname) 
  60.  
  61.                     return func(*args) 
  62.  
  63.   
  64.  
  65.         return self.notfound() 
  66.  
  67.   
  68.  
  69.     def GET_index(self): 
  70.  
  71.         status = '200 OK' 
  72.  
  73.         response_headers = [('Content-type''text/plain')] 
  74.  
  75.         self.start(status, response_headers) 
  76.  
  77.         yield "Welcome!\n" 
  78.  
  79.   
  80.  
  81.     def GET_hello(self, name): ##########修改点 
  82.  
  83.         status = '200 OK' 
  84.  
  85.         response_headers = [('Content-type''text/plain')] 
  86.  
  87.         self.start(status, response_headers) 
  88.  
  89.         yield "Hello %s!\n" % name 
  90.  
  91.   
  92.  
  93.     def notfound(self): 
  94.  
  95.         status = '404 Not Found' 
  96.  
  97.         response_headers = [('Content-type''text/plain')] 
  98.  
  99.         self.start(status, response_headers) 
  100.  
  101.         yield "Not Found\n"  

2、DRY

消除GET_*方法中的重复代码,并且允许它们返回字符串:

  1. #!/usr/bin/env python 
  2.  
  3. # -*- coding: utf-8 -*- 
  4.  
  5.   
  6.  
  7. """application.py""" 
  8.  
  9.   
  10.  
  11. import re 
  12.  
  13.   
  14.  
  15. class my_app: 
  16.  
  17.   
  18.  
  19.     urls = ( 
  20.  
  21.         ("/""index"), 
  22.  
  23.         ("/hello/(.*)""hello"), 
  24.  
  25.     ) 
  26.  
  27.   
  28.  
  29.     def __init__(self, environ, start_response): ##########修改点 
  30.  
  31.         self.environ = environ 
  32.  
  33.         self.start = start_response 
  34.  
  35.         self.status = '200 OK' 
  36.  
  37.         self._headers = [] 
  38.  
  39.   
  40.  
  41.     def __iter__(self): ##########修改点 
  42.  
  43.         result = self.delegate() 
  44.  
  45.         self.start(self.status, self._headers) 
  46.  
  47.   
  48.  
  49.         # 将返回值result(字符串 或者 字符串列表)转换为迭代对象 
  50.  
  51.         if isinstance(result, basestring): 
  52.  
  53.             return iter([result]) 
  54.  
  55.         else
  56.  
  57.             return iter(result) 
  58.  
  59.   
  60.  
  61.     def delegate(self): ##########修改点 
  62.  
  63.         path = self.environ['PATH_INFO'
  64.  
  65.         method = self.environ['REQUEST_METHOD'
  66.  
  67.   
  68.  
  69.         for pattern, name in self.urls: 
  70.  
  71.             m = re.match('^' + pattern + '$', path) 
  72.  
  73.             if m: 
  74.  
  75.                 # pass the matched groups as arguments to the function 
  76.  
  77.                 args = m.groups() 
  78.  
  79.                 funcname = method.upper() + '_' + name 
  80.  
  81.                 if hasattr(self, funcname): 
  82.  
  83.                     func = getattr(self, funcname) 
  84.  
  85.                     return func(*args) 
  86.  
  87.   
  88.  
  89.         return self.notfound() 
  90.  
  91.   
  92.  
  93.     def header(self, name, value): ##########修改点 
  94.  
  95.         self._headers.append((name, value)) 
  96.  
  97.   
  98.  
  99.     def GET_index(self): ##########修改点 
  100.  
  101.         self.header('Content-type''text/plain'
  102.  
  103.         return "Welcome!\n" 
  104.  
  105.   
  106.  
  107.     def GET_hello(self, name): ##########修改点 
  108.  
  109.         self.header('Content-type''text/plain'
  110.  
  111.         return "Hello %s!\n" % name 
  112.  
  113.   
  114.  
  115.     def notfound(self): ##########修改点 
  116.  
  117.         self.status = '404 Not Found' 
  118.  
  119.         self.header('Content-type''text/plain'
  120.  
  121.         return "Not Found\n"  

3、抽象出框架

为了将类my_app抽象成一个独立的框架,需要作出以下修改:

  • 剥离出其中的具体处理细节:urls配置 和 GET_*方法(改成在多个类中实现相应的GET方法)
  • 把方法header实现为类方法(classmethod),以方便外部作为功能函数调用
  • 改用 具有__call__方法的 实例 来实现application

修改后的application.py(最终版本):

  1. #!/usr/bin/env python 
  2.  
  3. # -*- coding: utf-8 -*- 
  4.  
  5.   
  6.  
  7. """application.py""" 
  8.  
  9.   
  10.  
  11. import re 
  12.  
  13.   
  14.  
  15. class my_app: 
  16.  
  17.     """my simple web framework""" 
  18.  
  19.   
  20.  
  21.     headers = [] 
  22.  
  23.   
  24.  
  25.     def __init__(self, urls=(), fvars={}): 
  26.  
  27.         self._urls = urls 
  28.  
  29.         self._fvars = fvars 
  30.  
  31.   
  32.  
  33.     def __call__(self, environ, start_response): 
  34.  
  35.         self._status = '200 OK' # 默认状态OK 
  36.  
  37.         del self.headers[:] # 清空上一次的headers 
  38.  
  39.   
  40.  
  41.         result = self._delegate(environ) 
  42.  
  43.         start_response(self._status, self.headers) 
  44.  
  45.   
  46.  
  47.         # 将返回值result(字符串 或者 字符串列表)转换为迭代对象 
  48.  
  49.         if isinstance(result, basestring): 
  50.  
  51.             return iter([result]) 
  52.  
  53.         else
  54.  
  55.             return iter(result) 
  56.  
  57.   
  58.  
  59.     def _delegate(self, environ): 
  60.  
  61.         path = environ['PATH_INFO'
  62.  
  63.         method = environ['REQUEST_METHOD'
  64.  
  65.   
  66.  
  67.         for pattern, name in self._urls: 
  68.  
  69.             m = re.match('^' + pattern + '$', path) 
  70.  
  71.             if m: 
  72.  
  73.                 # pass the matched groups as arguments to the function 
  74.  
  75.                 args = m.groups() 
  76.  
  77.                 funcname = method.upper() # 方法名大写(如GET、POST) 
  78.  
  79.                 klass = self._fvars.get(name) # 根据字符串名称查找类对象 
  80.  
  81.                 if hasattr(klass, funcname): 
  82.  
  83.                     func = getattr(klass, funcname) 
  84.  
  85.                     return func(klass(), *args) 
  86.  
  87.   
  88.  
  89.         return self._notfound() 
  90.  
  91.   
  92.  
  93.     def _notfound(self): 
  94.  
  95.         self._status = '404 Not Found' 
  96.  
  97.         self.header('Content-type''text/plain'
  98.  
  99.         return "Not Found\n" 
  100.  
  101.   
  102.  
  103.     @classmethod 
  104.  
  105.     def header(cls, name, value): 
  106.  
  107.         cls.headers.append((name, value))  

对应修改后的code.py(最终版本):

  1. #!/usr/bin/env python 
  2.  
  3. # -*- coding: utf-8 -*- 
  4.  
  5.   
  6.  
  7. """code.py""" 
  8.  
  9.   
  10.  
  11. from application import my_app 
  12.  
  13.   
  14.  
  15. urls = ( 
  16.  
  17.     ("/""index"), 
  18.  
  19.     ("/hello/(.*)""hello"), 
  20.  
  21.  
  22.   
  23.  
  24. wsgiapp = my_app(urls, globals()) 
  25.  
  26.   
  27.  
  28. class index
  29.  
  30.     def GET(self): 
  31.  
  32.         my_app.header('Content-type''text/plain'
  33.  
  34.         return "Welcome!\n" 
  35.  
  36.   
  37.  
  38. class hello: 
  39.  
  40.     def GET(self, name): 
  41.  
  42.         my_app.header('Content-type''text/plain'
  43.  
  44.         return "Hello %s!\n" % name 
  45.  
  46.   
  47.  
  48. if __name__ == '__main__'
  49.  
  50.     from wsgiref.simple_server import make_server 
  51.  
  52.     httpd = make_server('', 8086, wsgiapp) 
  53.  
  54.   
  55.  
  56.     sa = httpd.socket.getsockname() 
  57.  
  58.     print 'http://{0}:{1}/'.format(*sa) 
  59.  
  60.   
  61.  
  62.     # Respond to requests until process is killed 
  63.  
  64.     httpd.serve_forever()  

当然,您还可以在code.py中配置更多的URL映射,并实现相应的类来对请求作出响应。

六、参考

本文主要参考了 How to write a web framework in Python(作者 anandology 是web.py代码的两位维护者之一,另一位则是大名鼎鼎却英年早逝的 Aaron Swartz),在此基础上作了一些调整和修改,并掺杂了自己的一些想法。

如果您还觉得意犹未尽,Why so many Python web frameworks? 也是一篇很好的文章,也许它会让您对Python中Web框架的敬畏之心荡然无存:-)

责任编辑:庞桂玉 来源: Python开发者
相关推荐

2015-10-12 16:45:26

NodeWeb应用框架

2016-09-14 17:48:44

2016-12-20 13:55:52

2020-07-20 10:00:52

Python翻译工具命令行

2022-03-24 14:42:19

Python编程语言

2022-04-01 15:18:42

Web 框架网络通信

2018-10-31 10:11:24

Python编程语言语音播放

2010-04-19 17:21:36

Oracle写文件

2019-09-23 09:11:02

Python文本编辑器操作系统

2017-05-18 12:16:03

LinuxPythonNoSql

2021-05-14 10:45:21

PythonNoSQL数据库

2020-09-29 15:08:47

Go UI框架开发

2023-04-07 15:45:13

Emojicode开源编码语言

2021-08-04 11:55:45

Python天气查询PySide2

2023-04-10 14:20:47

ChatGPTRESTAPI

2023-05-10 08:05:41

GoWeb应用

2019-05-14 12:30:07

PythonPygame游戏框架

2009-05-08 09:32:27

JavaWeb编程框架

2020-06-04 12:55:44

PyTorch分类器神经网络

2018-12-04 15:10:56

Python微信备忘录
点赞
收藏

51CTO技术栈公众号