译者: smallfish (smallfish.xy@gmail.com)

更新日期: 2009-09-25

原文地址: http://bottle.paws.de/page/docs (已失效)

译文地址: http://pynotes.appspot.com/static/bottle/docs.htm (需翻墙)


这份文档会不断更新。

假设在文档里没有找到答案。请在版本号跟踪中提出 issue

基本映射

映射使用在依据不同 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, ...

这个映射装饰器有可选的keyword 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<id>[0-9]+)')
def get(id):
return "Object ID: %d" % int(id)

正如你看到的,URL 參数仍然是字符串。即使你正则里面是数字。 你必须显式的进行类型强制转换。

@validate() 装饰器

Bottle 提供一个方便的装饰器 validate() 来校验多个參数。

它能够通过keyword和过滤器来对每个 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 response
response.set_cookie('key','value', path='/', domain='example.com', secure=True, expires=+500, ...)

设置 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 </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></h1>
<ul>
%for item in items:
<li>
%if isinstance(item, int):
Zahl:
%else:
%try:
Other type: ()
%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() 和 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, run
app = default_app()
newapp = YourMiddleware(app)
run(app=newapp)

默认 default_app() 工作

Bottle 创建一个 bottle.Bottle() 对象和装饰器,调用 bottle.run() 执行。 bottle.default_app()是默认。当然你能够创建自己的 bottle.Bottle() 实例。

from bottle import Bottle, run
mybottle = Bottle()
@mybottle.route('/')
def index():
return 'default_app'
run(app=mybottle)

公布

Bottle 默认使用 wsgiref.SimpleServer 公布。 这个默认单线程server是用来早期开发和測试,可是后期可能会成为性能瓶颈。

有三种方法能够去改动:

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

多线程server

最简单的方法是安装一个多线程和 WSGI 规范的 HTTP server比方 Paste, flup, cherrypy or fapws3 并使用对应的适配器。

from bottle import PasteServer, FlupServer, FapwsServer, CherryPyServer
bottle.run(server=PasteServer) # Example

假设缺少你喜欢的server和适配器。你能够手动改动 HTTP server并设置 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)

多server进程

一个 Python 程序仅仅能使用一次一个 CPU,即使有很多其它的 CPU。

关键是要利用 CPU 资源来负载平衡多个独立的 Python 程序。

单实例 Bottle 应用,你能够通过不同的port来启动(localhost:8080, 8081, 8082, ...)。

高性能负载作为反向代理和远期每个随机瓶进程的新要求。平衡器的行为,传播全部可用的支持与server实例的负载。 这样。您就能够使用全部的 CPU 核心。甚至分散在不同的物理server之间的负载。

但也有点缺点:

  • 多个 Python 进程里不能共享数据。
  • 同一时间可能须要大量内存来执行 Python 和 Bottle 应用和副本。
  • 最快的一个负载是 pound 当然其它一些 HTTP server相同能够做的非常好。

不久我会增加 lighttpd 和 Apache 使用。

Apache mod_wsgi

公布你的应用当然不是用 Bottle 自带的方法,你能够再 Apache server 使用 mod_wsgi 模板和 Bottles WSGI 接口。

你须要建立 app.wsgi 文件并提供 application 对象。

这个对象是用使用 mod_wsgi 启动你的程序并遵循 WSGI 规范可调用。

# /var/www/yourapp/app.wsgi
import bottle
# ... add or import your bottle app code here ...
# import myapp
application = bottle.default_app()
# Do NOT use bottle.run() with mod_wsgi

Apache 配置可能例如以下:

<VirtualHost *>
ServerName example.com WSGIDaemonProcess yourapp user=www-data group=www-data processes=1 threads=5
WSGIScriptAlias / /var/www/yourapp/app.wsgi <Directory /var/www/yourapp>
WSGIProcessGroup yourapp
WSGIApplicationGroup %{GLOBAL}
Order deny,allow
Allow from all
</Directory>
</VirtualHost>

Google AppEngine

import bottle
from google.appengine.ext.webapp import util
# ... add or import your bottle app code here ...
# import myapp
# Do NOT use bottle.run() with AppEngine
util.run_wsgi_app(bottle.default_app())

CGI模式

执行缓缓,但能够正常工作。

import bottle
# ... add or import your bottle app code here ...
bottle.run(server=bottle.CGIServe

Bottle 中文文档的更多相关文章

  1. Phoenix综述(史上最全Phoenix中文文档)

    个人主页:http://www.linbingdong.com 简书地址:http://www.jianshu.com/users/6cb45a00b49c/latest_articles 网上关于P ...

  2. Chart.js中文文档-雷达图

    雷达图或蛛网图(Radar chart) 简介 A radar chart is a way of showing multiple data points and the variation bet ...

  3. Knockout中文开发指南(完整版API中文文档) 目录索引

    a, .tree li > span { padding: 4pt; border-radius: 4px; } .tree li a { color:#46cfb0; text-decorat ...

  4. ReactNative官方中文文档0.21

    整理了一份ReactNative0.21中文文档,提供给需要的reactnative爱好者.ReactNative0.21中文文档.chm  百度盘下载:ReactNative0.21中文文档 来源: ...

  5. java中文文档官方下载

    一直在寻找它,今天无意之间终于发现它了! http://download.oracle.com/technetwork/java/javase/6/docs/zh/api/overview-summa ...

  6. Spring中文文档

    前一段时间翻译了Jetty的一部分文档,感觉对阅读英文没有大的提高(*^-^*),毕竟Jetty的受众面还是比较小的,而且翻译过程中发现Jetty的文档写的不是很好,所以呢翻译的兴趣慢慢就不大了,只能 ...

  7. jQuery 3.1 API中文文档

    jQuery 3.1 API中文文档 一.核心 1.1 核心函数 jQuery([selector,[context]]) 接收一个包含 CSS 选择器的字符串,然后用这个字符串去匹配一组元素. jQ ...

  8. jQuery EasyUI API 中文文档 - ComboGrid 组合表格

    jQuery EasyUI API 中文文档 - ComboGrid 组合表格,需要的朋友可以参考下. 扩展自 $.fn.combo.defaults 和 $.fn.datagrid.defaults ...

  9. jQuery EasyUI API 中文文档 - ValidateBox验证框

    jQuery EasyUI API 中文文档 - ValidateBox验证框,使用jQuery EasyUI的朋友可以参考下.   用 $.fn.validatebox.defaults 重写了 d ...

随机推荐

  1. 安装PHP过程中,make步骤报错:(集合网络上各种解决方法)

    安装PHP过程中,make步骤报错:(集合网络上各种解决方法) (1)-liconv -o sapi/fpm/php-fpm /usr/bin/ld: cannot find -liconv coll ...

  2. 自定义控件出现“loaded nib but the view outlet was not set”

    我出现这个错误是因为我的自定义控件的名字和项目中一个控制器的名字很像 控制器 DDGuessYourLikeViewController 自定义控件 DDGuessYourLikeView 默认的, ...

  3. MySQL 选择数据库

    MySQL 选择数据库 在你连接到 MySQL 数据库后,可能有多个可以操作的数据库,所以你需要选择你要操作的数据库. 从命令提示窗口中选择MySQL数据库 在 mysql> 提示窗口中可以很简 ...

  4. 再谈CMake与RPATH

    之前写过一篇<探讨CMake中关于RPATH的使用>,只要针对的方面是在编译生成之后(不包括安装的make install)如何去除RPATH的问题.今天给大家主要介绍一下如何让CMake ...

  5. java面试题及答案(基础题122道,代码题19道)

    JAVA相关基础知识 1.面向对象的特征有哪些方面 1.抽象: 抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面.抽象并不打算了解全部问题,而只是选择其中的一部分, ...

  6. 自定义JQuery插件之 beforeFocus

    <html> <head> <title></title> <script type="text/javascript" sr ...

  7. AutoMapper DynamicMap天坑

    如果调用Mapper.DynamicMap该方法,会将所有映射重置为默认映射,即以字段名匹配映射.

  8. PHP程序异常处理实现方法

    一个异常(Exception)则是在一个程序执行过程中出现一个例外或是一个事件,它中断了指令的运行,跳转到其他程序模块继续执行.所以异常处理经常被当作程序的控制流程使用.无论是错误还是异常,应用程序都 ...

  9. 微信小程序开发之大坑记之post请求

    原文:http://blog.csdn.net/walkingmanc/article/details/54237961 在微信小程序开发过程中,如果你完全按照官方文档来,那么恭喜你,90%的可能性你 ...

  10. jquery ajax用例样板

    $.ajax({ url: '${managerPath}/customer/updateOrder.do', type: 'POST', async: false, data: { id: date ...