简单介绍python的轻便web框架bottle

基本映射

映射使用在根据不同urls请求来产生相对应的返回内容.bottle使用route() 修饰器来实现映射.

from bottle import route, run@route(‘/hello’)def hello():
return “hello world!”run() # this starts the http server

运行这个程序,访问http://localhost:8080/hello将会在浏览器里看到 “hello world!”.
get, post, head, …

这个映射装饰器有可选的关键字method默认是method=’get’. 还有可能是post,put,delete,head或者监听其他的http请求方法.

from bottle import route, request@route(‘/form/submit’, method=’post’)def form_submit():
form_data = request.post
do_something(form_data)
return “done”

动态映射

你可以提取url的部分来建立动态变量名的映射.

@route(‘/hello/:name’)def hello(name):
return “hello %s!” % name

默认情况下, 一个:placeholder会一直匹配到下一个斜线.需要修改的话,可以把正则字符加入到#s之间:

@route(‘/get_object/:id#[0-9]+#’)def get(id):
return “object id: %d” % int(id)

或者使用完整的正则匹配组来实现:

@route(‘/get_object/(?p[0-9]+)’)def get(id):
return “object id: %d” % int(id)

正如你看到的,url参数仍然是字符串, 即使你正则里面是数字.你必须显式的进行类型强制转换.
@validate() 装饰器

bottle 提供一个方便的装饰器validate() 来校验多个参数.它可以通过关键字和过滤器来对每一个url参数进行处理然后返回请求.

from bottle import route, validate# /test/validate/1/2.3/4,5,6,7@route(‘/test/validate/:i/:f/:csv’)@validate(i=int, f=float, csv=lambda x: map(int, x.split(‘,’)))def validate_test(i, f, csv):
return “int: %d, float:%f, list:%s” % (i, f, repr(csv))

你可能需要在校验参数失败时抛出valueerror.
返回文件流和json

wsgi规范不能处理文件对象或字符串.bottle自动转换字符串类型为iter对象.下面的例子可以在bottle下运行, 但是不能运行在纯wsgi环境下.

@route(‘/get_string’)def get_string():
return “this is not a list of strings, but a single string”@route(‘/file’)def get_file():
return open(‘some/file.txt’,’r’)

字典类型也是允许的.会转换成json格式,自动返回content-type: application/json.

@route(‘/api/status’)def api_status():
return {‘status’:’online’, ‘servertime’:time.time()}

你可以关闭这个特性:bottle.default_app().autojson = false
cookies

bottle是把cookie存储在request.cookies变量中.新建cookie的方法是response.set_cookie(name, value[, **params]). 它可以接受额外的参数,属于simplecookie的有有效参数.

from bottle import responseresponse.set_cookie(‘key’,’value’, path=’/’, domain=’example.com’, secure=true, expires=+500, …)

设置max-age属性(它不是个有效的python参数名) 你可以在实例中修改 cookie.simplecookie inresponse.cookies.

from bottle import responseresponse.cookies[‘key’] = ‘value’response.cookies[‘key’][‘max-age’] = 500

模板

bottle使用自带的小巧的模板.你可以使用调用template(template_name, **template_arguments)并返回结果.

@route(‘/hello/:name’)def hello(name):
return template(‘hello_template’, username=name)

这样就会加载hello_template.tpl,并提取url:name到变量username,返回请求.

hello_template.tpl大致这样:

hello {{username}}

how are you?

模板搜索路径

模板是根据bottle.template_path列表变量去搜索.默认路径包含[‘./%s.tpl’, ‘./views/%s.tpl’].
模板缓存

模板在编译后在内存中缓存.修改模板不会更新缓存,直到你清除缓存.调用bottle.templates.clear().
模板语法

模板语法是围绕python很薄的一层.主要目的就是确保正确的缩进块.下面是一些模板语法的列子:

%…python代码开始.不必处理缩进问题.bottle会为你做这些.
%end关闭一些语句%if …,%for …或者其他.关闭块是必须的.
{{…}}打印出python语句的结果.
%include template_name optional_arguments包括其他模板.
每一行返回为文本.

example:

%header = ‘test template’
%items = [1,2,3,’fly’]
%include http_header title=header, use_js=[‘jquery.js’, ‘default.js’]{{header.title()}}%for item in items:
%if isinstance(item, int):
zahl: {{item}}
%else:
%try:
other type: ({{type(item).__name__}}) {{repr(item)}}
%except:
error: item has no string representation.
%end try-block (yes, you may add comments here)
%end
%end%include http_footer

key/value数据库

bottle(>0.4.6)通过bottle.db模块变量提供一个key/value数据库.你可以使用key或者属性来来存取一个数据库对象.调用 bottle.db.bucket_name.key_name和bottle.db[bucket_name][key_name].

只要确保使用正确的名字就可以使用,而不管他们是否已经存在.

存储的对象类似dict字典, keys和values必须是字符串.不支持 items() and values()这些方法.找不到将会抛出keyerror.
持久化

对于请求,所有变化都是缓存在本地内存池中. 在请求结束时,自动保存已修改部分,以便下一次请求返回更新的值.数据存储在bottle.db_path文件里.要确保文件能访问此文件.
race conditions

一般来说不需要考虑锁问题,但是在多线程或者交叉环境里仍是个问题.你可以调用 bottle.db.save()或者botle.db.bucket_name.save()去刷新缓存,但是没有办法检测到其他环境对数据库的操作,直到调用bottle.db.save()或者离开当前请求.
example

from bottle import route, db@route(‘/db/counter’)def db_counter():
if ‘hits’ not in db.counter:
db.counter.hits = 0
db[‘counter’][‘hits’] += 1
return “total hits: %d!” % db.counter.hits

使用wsgi和中间件

bottle.default_app()返回一个wsgi应用.如果喜欢wsgi中间件模块的话,你只需要声明bottle.run()去包装应用,而不是使用默认的.

from bottle import default_app, runapp = default_app()newapp = yourmiddleware(app)run(app=newapp)

默认default_app()工作

bottle创建一个bottle.bottle()对象和装饰器,调用bottle.run()运行. bottle.default_app()是默认.当然你可以创建自己的bottle.bottle()实例.

from bottle import bottle, runmybottle = bottle()@mybottle.route(‘/’)def index():
return ‘default_app’run(app=mybottle)

发布

bottle默认使用wsgiref.simpleserver发布.这个默认单线程服务器是用来早期开发和测试,但是后期可能会成为性能瓶颈.

有三种方法可以去修改:

使用多线程的适配器
负载多个bottle实例应用
或者两者

多线程服务器

最简单的方法是安装一个多线程和wsgi规范的http服务器比如paste, flup, cherrypy or fapws3并使用相应的适配器.

from bottle import pasteserver, flupserver, fapwsserver, cherrypyserverbottle.run(server=pasteserver) # example

如果缺少你喜欢的服务器和适配器,你可以手动修改http服务器并设置bottle.default_app()来访问你的wsgi应用.

def run_custom_paste_server(self, host, port):
myapp = bottle.default_app()
from paste import httpserver
httpserver.serve(myapp, host=host, port=port)

多服务器进程

一个python程序只能使用一次一个cpu,即使有更多的cpu.关键是要利用cpu资源来负载平衡多个独立的python程序.

单实例bottle应用,你可以通过不同的端口来启动(localhost:8080, 8081, 8082, …).高性能负载作为反向代理和远期每一个随机瓶进程的新要求,平衡器的行为,传播所有可用的支持与服务器实例的负载.这样,您就可以使用所有的cpu核心,甚至分散在不同的物理服

Posted in 未分类

发表评论