Python学习-编写一个简单的web框架(二)

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

在上一篇日志中已经讨论和实现了根据url执行相应应用,在我阅读了bottle.py官方文档后,按照bottle的设计重写一遍,主要借鉴大牛们的设计思想。

一个bottle.py的简单实例来看看bottle是如何使用的,代码来自http://www.bottlepy.org/docs/0.12/index.html:

frombottleimportroute, run, template

@route('/hello/<name>')defindex(name):returntemplate('<b>Hello {{name}}</b>!', name=name)

run(host='localhost', port=8080)

很显然,bottle是使用装饰器来路由的。根据bottle的设计,我来写一个简单的框架。

Python装饰器装饰器,顾名思义就是包装一个函数。在不改变函数的同时,动态的给函数增加功能。这里不在探讨更多的细节。

大致的框架根据WSGI的定义,一个WSGI应用必须要是可调用的。所以下面是一个WSGI应用的大致框架:

class WSGIapp(object):

def __init__(self):

pass

def route(self,path=None):

pass

def __call__(self,environ,start_response):

return self.wsgi(environ,start_response)

def wsgi(self,environ,start_response):

pass

其中,route方法就是来保存url->target的。这里为了方便,将url->target保存在字典中:

defroute(self,path=None):defdecorator(func):

self.routes[path]=funcreturnfuncreturndecorator

这里return func注释掉也可以,求大神解释一下啊!!

然后就是实现WSGIapp的每个方法:

classWSGIapp(object):def__init__(self):

self.routes={}defroute(self,path=None):defdecorator(func):

self.routes[path]=funcreturnfuncreturndecoratordef__call__(self,environ,start_response):PRint'call'returnself.wsgi(environ,start_response)defwsgi(self,environ,start_response):

path= environ['PATH_INFO']printpathifpathinself.routes:

status='200 OK'response_headers= [('Content-Type','text/plain')]

start_response(status,response_headers)printself.routes[path]()returnself.routes[path]()else:

status='404 Not Found'response_headers= [('Content-Type','text/plain')]

start_response(status,response_headers)return'404 Not Found!'app=WSGIapp()

@app.route('/')defindex():return['This is index']

@app.route('/hello')defhello():return['hello']fromwsgiref.simple_serverimportmake_server

httpd= make_server('',8000,app)print'start....'httpd.serve_forever()

这样,一个简易的web框架的雏形就实现了,如果对装饰器中的路径加入正则表达式,那么就可以很轻松的应对URL了。下一篇日志就是加入模板引擎jinja2了。

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航