首页 技术 正文
技术 2022年11月16日
0 收藏 961 点赞 5,018 浏览 1748 个字

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

一个bottle.py的简单实例

来看看bottle是如何使用的,代码来自http://www.bottlepy.org/docs/0.12/index.html:

from bottle import route, run, template@route('/hello/<name>')
def index(name):
return template('<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保存在字典中:

    def route(self,path=None):
def decorator(func):
self.routes[path] = func
return func
return decorator

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

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

class WSGIapp(object):    def __init__(self):
self.routes = {} def route(self,path=None):
def decorator(func):
self.routes[path] = func
return func
return decorator def __call__(self,environ,start_response):
print 'call'
return self.wsgi(environ,start_response) def wsgi(self,environ,start_response):
path = environ['PATH_INFO']
print path
if path in self.routes:
status = '200 OK'
response_headers = [('Content-Type','text/plain')]
start_response(status,response_headers)
print self.routes[path]()
return self.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('/')
def index():
return ['This is index']
@app.route('/hello')
def hello():
return ['hello']from wsgiref.simple_server import make_server
httpd = make_server('',8000,app)
print 'start....'
httpd.serve_forever()

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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,493
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,294