Recipes — Bottle 0.13-dev documentation

Recipes

This is a collection of code snippets and examples for common use cases.

Keeping track of Sessions

There is no built-in support for sessions because there is no right way to do it (in a micro framework). Depending on requirements and environment you could use beaker middleware with a fitting backend or implement it yourself. Here is an example for beaker sessions with a file-based backend:

import bottle
from beaker.middleware import SessionMiddleware session_opts = {
'session.type': 'file',
'session.cookie_expires': 300,
'session.data_dir': './data',
'session.auto': True
}
app = SessionMiddleware(bottle.app(), session_opts) @bottle.route('/test')
def test():
s = bottle.request.environ.get('beaker.session')
s['test'] = s.get('test',0) + 1
s.save()
return 'Test counter: %d' % s['test'] bottle.run(app=app)

Debugging with Style: Debugging Middleware

Bottle catches all Exceptions raised in your app code to prevent your WSGI server from crashing. If the built-in debug() mode is not enough and you need exceptions to propagate to a debugging middleware, you can turn off this behaviour:

import bottle
app = bottle.app()
app.catchall = False #Now most exceptions are re-raised within bottle.
myapp = DebuggingMiddleware(app) #Replace this with a middleware of your choice (see below)
bottle.run(app=myapp)

Now, bottle only catches its own exceptions (HTTPError, HTTPResponse and BottleException) and your middleware can handle the rest.

The werkzeug and paste libraries both ship with very powerful debugging WSGI middleware. Look at werkzeug.debug.DebuggedApplication for werkzeug and paste.evalexception.middleware.EvalException for paste. They both allow you do inspect the stack and even execute python code within the stack context, so do not use them in production.

Unit-Testing Bottle Applications

Unit-testing is usually performed against methods defined in your web application without running a WSGI environment.

A simple example using Nose:

import bottle

@bottle.route('/')
def index():
return 'Hi!' if __name__ == '__main__':
bottle.run()

Test script:

import mywebapp

def test_webapp_index():
assert mywebapp.index() == 'Hi!'

In the example the Bottle route() method is never executed - only index() is tested.

Functional Testing Bottle Applications

Any HTTP-based testing system can be used with a running WSGI server, but some testing frameworks work more intimately with WSGI, and provide the ability the call WSGI applications in a controlled environment, with tracebacks and full use of debugging tools. Testing tools for WSGI is a good starting point.

Example using WebTest and Nose:

from webtest import TestApp
import mywebapp def test_functional_login_logout():
app = TestApp(mywebapp.app) app.post('/login', {'user': 'foo', 'pass': 'bar'}) # log in and get a cookie assert app.get('/admin').status == '200 OK' # fetch a page successfully app.get('/logout') # log out
app.reset() # drop the cookie # fetch the same page, unsuccessfully
assert app.get('/admin').status == '401 Unauthorized'

Embedding other WSGI Apps

This is not the recommend way (you should use a middleware in front of bottle to do this) but you can call other WSGI applications from within your bottle app and let bottle act as a pseudo-middleware. Here is an example:

from bottle import request, response, route
subproject = SomeWSGIApplication() @route('/subproject/:subpath#.*#', method='ANY')
def call_wsgi(subpath):
new_environ = request.environ.copy()
new_environ['SCRIPT_NAME'] = new_environ.get('SCRIPT_NAME','') + '/subproject'
new_environ['PATH_INFO'] = '/' + subpath
def start_response(status, headerlist):
response.status = int(status.split()[0])
for key, value in headerlist:
response.add_header(key, value)
return app(new_environ, start_response)

Again, this is not the recommend way to implement subprojects. It is only here because many people asked for this and to show how bottle maps to WSGI.

Ignore trailing slashes

For Bottle, /example and /example/ are two different routes [1]. To treat both URLs the same you can add two @route decorators:

@route('/test')
@route('/test/')
def test(): return 'Slash? no?'

or add a WSGI middleware that strips trailing slashes from all URLs:

class StripPathMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, e, h):
e['PATH_INFO'] = e['PATH_INFO'].rstrip('/')
return self.app(e,h) app = bottle.app()
myapp = StripPathMiddleware(app)
bottle.run(app=myapp)

Footnotes

[1] Because they are. See <http://www.ietf.org/rfc/rfc3986.txt>

Keep-alive requests

Note

For a more detailed explanation, see Primer to Asynchronous Applications.

Several “push” mechanisms like XHR multipart need the ability to write response data without closing the connection in conjunction with the response header “Connection: keep-alive”. WSGI does not easily lend itself to this behavior, but it is still possible to do so in Bottle by using the gevent async framework. Here is a sample that works with either the gevent HTTP server or the paste HTTP server (it may work with others, but I have not tried). Just change server='gevent' to server='paste' to use the paste server:

from gevent import monkey; monkey.patch_all()

import time
from bottle import route, run @route('/stream')
def stream():
yield 'START'
time.sleep(3)
yield 'MIDDLE'
time.sleep(5)
yield 'END' run(host='0.0.0.0', port=8080, server='gevent')

If you browse to http://localhost:8080/stream, you should see ‘START’, ‘MIDDLE’, and ‘END’ show up one at a time (rather than waiting 8 seconds to see them all at once).

Gzip Compression in Bottle

Note

For a detailed discussion, see compression

A common feature request is for Bottle to support Gzip compression, which speeds up sites by compressing static resources (like CSS and JS files) during a request.

Supporting Gzip compression is not a straightforward proposition, due to a number of corner cases that crop up frequently. A proper Gzip implementation must:

  • Compress on the fly and be fast doing so.
  • Do not compress for browsers that don’t support it.
  • Do not compress files that are compressed already (images, videos).
  • Do not compress dynamic files.
  • Support two differed compression algorithms (gzip and deflate).
  • Cache compressed files that don’t change often.
  • De-validate the cache if one of the files changed anyway.
  • Make sure the cache does not get to big.
  • Do not cache small files because a disk seek would take longer than on-the-fly compression.

Because of these requirements, it is the recommendation of the Bottle project that Gzip compression is best handled by the WSGI server Bottle runs on top of. WSGI servers such as cherrypy provide a GzipFilter middleware that can be used to accomplish this.

Using the hooks plugin

For example, if you want to allow Cross-Origin Resource Sharing for the content returned by all of your URL, you can use the hook decorator and setup a callback function:

from bottle import hook, response, route

@hook('after_request')
def enable_cors():
response.headers['Access-Control-Allow-Origin'] = '*' @route('/foo')
def say_foo():
return 'foo!' @route('/bar')
def say_bar():
return {'type': 'friendly', 'content': 'Hi!'}

You can also use the before_request to take an action before every function gets called.

Using Bottle with Heroku

Heroku, a popular cloud application platform now provides support for running Python applications on their infastructure.

This recipe is based upon the Heroku Quickstart, with Bottle specific code replacing the Write Your App section of the Getting Started with Python on Heroku/Cedar guide:

import os
from bottle import route, run @route("/")
def hello_world():
return "Hello World!" run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000)))

Heroku’s app stack passes the port that the application needs to listen on for requests, using the os.environ dictionary.

Recipes — Bottle 0.13-dev documentation的更多相关文章

  1. 【Linux】【MySQL】CentOS7安装最新版MySQL8.0.13(最新版MySQL从安装到运行)

    1.前言 框框博客在线报时:2018-11-07 19:31:06 当前MySQL最新版本:8.0.13 (听说比5.7快2倍) 官方之前表示:MySQL 8.0 正式版 8.0.11 已发布,MyS ...

  2. 使用yum源的方式单机部署MySQL8.0.13

    使用yum源的方式单机部署MySQL8.0.13 作者:尹正杰  版权声明:原创作品,谢绝转载!否则将追究法律责任. 基本上开源的软件都支持三种安装方式,即rmp方式安装,源码安装和二进制方式安装.在 ...

  3. MySQL入门介绍(mysql-8.0.13)

    MySQL入门介绍(mysql-8.0.13单机部署) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.MySQL数据库介绍 1>.MySQL是一种开放源代码的关系型数据库 ...

  4. 64位 windows10,安装配置MYSQL8.0.13

    MySQL的安装配置过程,一查网上一大堆,但是每个人在安装配置的过程中都会碰到一些问题,因为安装的版本不一样,有些命令可能就不适用了.所以安装之前一定先确认好你的版本号. 下面开始安装MYSQL8.0 ...

  5. win10下安装配置mysql-8.0.13

    1.下载mysql-8.0.13安装包 https://dev.mysql.com/downloads/mysql/ 选择zip安装包下载就好. 2.解压到你要安装的目录 3.创建my.ini配置文件 ...

  6. mysql8.0.13安装、使用教程图解

    mysql8.0.13安装.使用教程图解 MySQL是最流行的关系型数据库管理系统之一,在 WEB 应用方面,MySQL是最好的 RDBMS (Relational Database Manageme ...

  7. Mac卸载mysql并安装mysql升级到8.0.13版本

    引言 今天mysql升级到8.0.13版本,遇到了很多问题,在此进行总结方便以后查看. 卸载mysql brew uninstall mysql sudo rm /usr/local/mysql su ...

  8. dbt 0.13.0 新添加特性sources 试用

    dbt 0.13 添加了一个新的功能sources 我呢可以用来做以下事情 从基础模型的源表中进行数据选择 测试对于源数据的假设 计算源数据的freshness source 操作 定义source ...

  9. mysql8.0.13下载与安装图文教程

    一.进入mysql网站:https://dev.mysql.com/downloads/mysql/ 二.进入Community选择MySQL Communtiy Server 三.将页面拉到最下面选 ...

随机推荐

  1. STL insert()使用

    下面我以vector的insert()为例: c++ 98: single element (1) iterator insert (iterator position, const value_ty ...

  2. 点菜系统 pickview的简单实用

    使用pickview的时候多想想tableview的使用,观察两者的相同之处 pickview的主要用途用于选择地区  生日年月日  和点餐 示例代码 简单的pickview点餐系统//  ViewC ...

  3. cacti气象图调整(批量位置调整、更改生成图大小等)

    cacti气象图能够非常直观的看到各个节点的流量.这里用的是CactiEZ中文版 V10 1.调整气象图大小 默认有一个1024像素的背景图可选, 这里我们须要新增一个1600像素的背景图. 背景图自 ...

  4. DescribingDesign Patterns 描述设计模式

    DescribingDesign Patterns 描述设计模式 How do we describe design patterns?Graphical notations, while impor ...

  5. git 使用过程(四、回退版本)

    1.查看修改历史 命令:git log  如果嫌内容太多 可以加参数  --pretty=oneline (图一) 2.回退 命令:git reset --hard HEAD^    HEAD:代表本 ...

  6. 写一方法计算实现任意个整数之和.在主调函数中调用该函数,实现任意个数之和。(使用params参数)

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  7. 浙江大学2015年校赛F题 ZOJ 3865 Superbot BFS 搜索

    不知道为什么比赛的时候一直想着用DFS 来写 一直想剪枝结果还是TLE = = 这题数据量不大,又是问最优解,那么一般来说是用 BFS 来写 int commandi[4] = {1, 2, 3, 4 ...

  8. 什么时候需要交换Top Level ?

    什么时候需要交换Top Level ? 上一篇中提到,如果采用仿真的时候,运用门级仿真就需要进行顶层交换,RTL仿真不需要,那么什么时候需要呢? QuartusII 向下包含,在Project Nav ...

  9. 使用webservice实现App与服务器端数据交互

    What? webservice曾经认为是解决异构系统间整合的最佳解决方案,不依赖于第三方任何系统的支持(不需要部署RDBMS服务器),大家只需要按照官方的规范,即可完成相互之间的数据交互. Why? ...

  10. Failed to retrieve procctx from ht. constr

    给一个客户巡检时发生这样的少见的集群报错: [  OCRSRV][1220598112]th_select_handler: Failed to retrieve procctx from ht. c ...