设置max-age属性(它不是个有效的Python参数名) 你可以在实例中修改 cookie.SimpleCookie in response.COOKIES.
from bottle import response response.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大致这样:
<h1>Hello {{username}}</h1>
<p>How are you?</p>
模板搜索路径
模板是根据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']
<h1>{{header.title()}}</h1>
<ul>
%for item in items:
<li>
%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
</li>
%end
</ul>
%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()或者离开当前请求.








