译者: 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() 修饰器来实现映射。

  1. from bottle import route, run
  2. @route('/hello')
  3. def hello():
  4. return "Hello World!"
  5. run() # This starts the HTTP server

执行这个程序。訪问 http://localhost:8080/hello 将会在浏览器里看到 "Hello World!"。

GET, POST, HEAD, ...

这个映射装饰器有可选的keyword method 默认是 method='GET'。 还有可能是 POST,PUT。DELETE,HEAD 或者监听其它的 HTTP 请求方法。

  1. from bottle import route, request
  2. @route('/form/submit', method='POST')
  3. def form_submit():
  4. form_data = request.POST
  5. do_something(form_data)
  6. return "Done"

动态映射

你能够提取 URL 的部分来建立动态变量名的映射。

  1. @route('/hello/:name')
  2. def hello(name):
  3. return "Hello %s!" % name

默认情况下,一个 :placeholder 会一直匹配到下一个斜线。 须要改动的话,能够把正则字符增加到 #s 之间:

  1. @route('/get_object/:id#[0-9]+#')
  2. def get(id):
  3. return "Object ID: %d" % int(id)

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

  1. @route('/get_object/(?P<id>[0-9]+)')
  2. def get(id):
  3. return "Object ID: %d" % int(id)

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

@validate() 装饰器

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

它能够通过keyword和过滤器来对每个 URL 參数进行处理然后返回请求。

  1. from bottle import route, validate
  2. # /test/validate/1/2.3/4,5,6,7
  3. @route('/test/validate/:i/:f/:csv')
  4. @validate(i=int, f=float, csv=lambda x: map(int, x.split(',')))
  5. def validate_test(i, f, csv):
  6. return "Int: %d, Float:%f, List:%s" % (i, f, repr(csv))

你可能须要在校验參数失败时抛出 ValueError。

返回文件流和 JSON

WSGI 规范不能处理文件对象或字符串。 Bottle 自己主动转换字符串类型为 iter 对象。

以下的样例能够在 Bottle 下执行,可是不能执行在纯 WSGI 环境下。

  1. @route('/get_string')
  2. def get_string():
  3. return "This is not a list of strings, but a single string"
  4. @route('/file')
  5. def get_file():
  6. return open('some/file.txt','r')

字典类型也是同意的。 会转换成 json 格式。自己主动返回 Content-Type: application/json。

  1. @route('/api/status')
  2. def api_status():
  3. return {'status':'online', 'servertime':time.time()}

你能够关闭这个特性 :bottle.default_app().autojson = False

Cookies

Bottle 是把 cookie 存储在 request.COOKIES 变量中。 新建 cookie 的方法是 response.set_cookie(name, value[, **params])。 它能够接受额外的參数。属于 SimpleCookie 的有有效參数。

  1. from bottle import response
  2. response.set_cookie('key','value', path='/', domain='example.com', secure=True, expires=+500, ...)

设置 max-age 属性(它不是个有效的 Python 參数名) 你能够在实例中改动 cookie.SimpleCookie in response.COOKIES。

  1. from bottle import response
  2. response.COOKIES['key'] = 'value'
  3. response.COOKIES['key']['max-age'] = 500

模板

Bottle 使用自带的小巧的模板。 你能够使用调用 template(template_name, **template_arguments) 并返回结果。

  1. @route('/hello/:name')
  2. def hello(name):
  3. return template('hello_template', username=name)

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

hello_template.tpl 大致这样:

  1. <h1>Hello </h1>
  2. <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:

  1. %header = 'Test Template'
  2. %items = [1,2,3,'fly']
  3. %include http_header title=header, use_js=['jquery.js', 'default.js']
  4. <h1></h1>
  5. <ul>
  6. %for item in items:
  7. <li>
  8. %if isinstance(item, int):
  9. Zahl:
  10. %else:
  11. %try:
  12. Other type: ()
  13. %except:
  14. Error: Item has no string representation.
  15. %end try-block (yes, you may add comments here)
  16. %end
  17. </li>
  18. %end
  19. </ul>
  20. %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

  1. from bottle import route, db
  2. @route('/db/counter')
  3. def db_counter():
  4. if 'hits' not in db.counter:
  5. db.counter.hits = 0
  6. db['counter']['hits'] += 1
  7. return "Total hits: %d!" % db.counter.hits

使用 WSGI 和中间件

bottle.default_app() 返回一个 WSGI 应用。

假设喜欢 WSGI 中间件模块的话,你仅仅须要声明bottle.run() 去包装应用。而不是使用默认的。

  1. from bottle import default_app, run
  2. app = default_app()
  3. newapp = YourMiddleware(app)
  4. run(app=newapp)

默认 default_app() 工作

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

  1. from bottle import Bottle, run
  2. mybottle = Bottle()
  3. @mybottle.route('/')
  4. def index():
  5. return 'default_app'
  6. run(app=mybottle)

公布

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

有三种方法能够去改动:

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

多线程server

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

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

假设缺少你喜欢的server和适配器。你能够手动改动 HTTP server并设置 bottle.default_app() 来訪问你的 WSGI 应用。

  1. def run_custom_paste_server(self, host, port):
  2. myapp = bottle.default_app()
  3. from paste import httpserver
  4. 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 规范可调用。

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

Apache 配置可能例如以下:

  1. <VirtualHost *>
  2. ServerName example.com
  3.  
  4. WSGIDaemonProcess yourapp user=www-data group=www-data processes=1 threads=5
  5. WSGIScriptAlias / /var/www/yourapp/app.wsgi
  6.  
  7. <Directory /var/www/yourapp>
  8. WSGIProcessGroup yourapp
  9. WSGIApplicationGroup %{GLOBAL}
  10. Order deny,allow
  11. Allow from all
  12. </Directory>
  13. </VirtualHost>

Google AppEngine

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

CGI模式

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

  1. import bottle
  2. # ... add or import your bottle app code here ...
  3. 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. C#敏感关键词过滤代码

    System.Text.StringBuilder sb = new System.Text.StringBuilder(text.Length);             string filter ...

  2. JQuery中根据属性或属性值获得元素

    根据属性获得元素 1.比如要获取页面p标签中属性有id的元素 $("p[id]").css("color","red"); 根据属性值获得元 ...

  3. cas sso单点登录系列2:cas客户端和cas服务端交互原理动画图解,cas协议终极分析

    转:http://blog.csdn.net/ae6623/article/details/8848107 1)PPT流程图:ppt下载:http://pan.baidu.com/s/1o7KIlom ...

  4. http请求头响应头大全

    转:http://www.jb51.net/article/51951.htm 本文为多篇“HTTP请求头相关文章”及<HTTP权威指南>一书的阅读后个人汇总整理版,以便于理解. 通常HT ...

  5. 解决java访问.netWebService的常见问题

    到公司没多久,写了一个java调用.net写的webService结果期间用各种方法测试都没有完成,总是抛出异常,最后直接使用SOAP消息去进行调用才成功了,具体代码如下,仅供参考:import ja ...

  6. PHP Predefined Interfaces 预定义接口

    SPL提供了6个迭代器接口: Traversable 遍历接口(检测一个类是否可以使用 foreach 进行遍历的接口) Iterator 迭代器接口(可在内部迭代自己的外部迭代器或类的接口) Ite ...

  7. javascript写的ajax请求

    <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> &l ...

  8. jquery animate函数实现

    jquery animate 函数 实现动画效果 参数一 比如高度宽度 之类的:'-=50' 参数二 速度之类 <html xmlns="http://www.w3.org/1999/ ...

  9. JLRoutes--处理复杂的URL schemes-备

    关键字:URL,URL schemes,Parse  代码类库:网络(Networking) GitHub链接:https://github.com/joeldev/JLRoutes   JLRout ...

  10. ubuntu下MySQL安装配置及基本操作

    在linux下安装方法: 分为四种:一: 直接用软件仓库自动安装(如:ubuntu下,sudo apt-get install mysql-server; Debain下用yum安装): 二:官网下载 ...