bottle是一个轻量级的python web框架, 可以适配各种web服务器,包括python自带的wsgiref(默认),gevent, cherrypy,gunicorn等等。bottle是单文件形式发布,源码在这里可以下载,代码量不多,可以用来学习web框架。这里也有官方文档的中文翻译。
 
  首先我们来运行一下bottle的hello world
from bottle import run

if __name__ == '__main__':
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return ['<h1>Hello world!</h1>'] run(host='localhost', port=8080, app=application)
  上面的代码看起来也非常符合wsgi的接口规范。启动改代码,可以看到输出
        Bottle v0.13-dev server starting up (using WSGIRefServer())...
        Listening on http://localhost:8080/
        Hit Ctrl-C to quit.
  
  输出中加粗部分表明使用的web服务器是python自带的wsgiref。也可以使用其他web server,比如gevent,前提是需要安装gevent,修改后的代码如下:
from bottle import run
import gevent.monkey
gevent.monkey.patch_all() if __name__ == '__main__':
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return ['<h1>Hello world!</h1>'] run(host='localhost', port=8080, app=application, server = 'gevent')

通过server关键字指定web服务器为‘gevent’,输出的第一行变成了:

    Bottle v0.13-dev server starting up (using GeventServer())...
 
不管bottle用什么web服务器启动,在浏览器输入127.0.0.1:8080,都可以看到
    
 
 
 
下面介绍bottle中部分类和接口
bottle.Bottle
    代表一个独立的wsgi应用,由一下部分组成:routes, callbacks, plugins, resources and configuration。
    __call__: Bottle定义了__call__函数, 使得Bottle的实例能成为一个callable。在前文提到,web框架(或Application)需要提供一个callbale对象给web服务器,bottle提供的就是Bottle实例
    def __call__(self, environ, start_response):
  """ Each instance of :class:'Bottle' is a WSGI application. """
return self.wsgi(environ, start_response)
    下面是Bottle.wsgi函数的核心代码,主要调用两个比较重要的函数:_handle, _cast
    def wsgi(self, environ, start_response):
""" The bottle WSGI-interface. """
try:
out = self._cast(self._handle(environ))
# rfc2616 section 4.3
if response._status_code in (100, 101, 204, 304)\
or environ['REQUEST_METHOD'] == 'HEAD':
if hasattr(out, 'close'): out.close()
out = []
start_response(response._status_line, response.headerlist)
return out

  _handle:处理请求,最终调用到application ,简化后的代码如下:

   def _handle(self, environ):
self.trigger_hook('before_request')
route, args = self.router.match(environ)
out = route.call(**args)
self.trigger_hook('after_request')
return out
  
  _cast: 
       标准的wsgi接口对Application的返回值要求严格,必须迭代返回字符串。bottle做了一些扩展,可以允许App返回更加丰富的类型,比如dict,File等。 _cast函数对_handle函数返回值进行处理,使之符合wsgi规范
 
bottle.Route
    封装了路由规则与对应的回调
 
bottle.Router
    A Router is an ordered collection of route->target pairs. It is used to  efficiently match WSGI requests against a number of routes and return the first target that satisfies the request.
 
ServerAdapter
    所有bottle适配的web服务器的基类,子类只要实现run方法就可以了,bottle里面有大量的Web服务器的适配。下表来自官网,介绍了bottle支持的各种web服务器,以及各自的特性。

Name Homepage Description
cgi
 
Run as CGI script
flup flup Run as FastCGI process
gae gae Helper for Google App Engine deployments
wsgiref wsgiref Single-threaded default server
cherrypy cherrypy Multi-threaded and very stable
paste paste Multi-threaded, stable, tried and tested
rocket rocket Multi-threaded
waitress waitress Multi-threaded, poweres Pyramid
gunicorn gunicorn Pre-forked, partly written in C
eventlet eventlet Asynchronous framework with WSGI support.
gevent gevent Asynchronous (greenlets)
diesel diesel Asynchronous (greenlets)
fapws3 fapws3 Asynchronous (network side only), written in C
tornado tornado Asynchronous, powers some parts of Facebook
twisted twisted Asynchronous, well tested but... twisted
meinheld meinheld Asynchronous, partly written in C
bjoern bjoern Asynchronous, very fast and written in C
auto
 
Automatically selects an available server adapter

    可以看到,bottle适配的web服务器很丰富。工作模式也很全面,有多线程的(如paste)、有多进程模式的(如gunicorn)、也有基于协程的(如gevent)。具体选择哪种web服务器取决于应用的特性,比如是CPU bound还是IO bound
 
bottle.run
    启动wsgi服务器。几个比较重要的参数
    app: wsgi application,即可以是bottle.Bottle 也开始是任何满足wsgi 接口的函数
    server: wsgi http server,字符串
    host:port: 监听端口
    
    核心逻辑:
    ServerAdapter.run(app)。
 
最后,bottle源码中有一些使用descriptor的例子,实现很巧妙,值得一读,前文也有介绍。
 
references;

python bottle 简介的更多相关文章

  1. python bottle框架

    python bottle框架 简介: Bottle是一个快速.简洁.轻量级的基于WSIG的微型Web框架,此框架只由一个 .py 文件,除了Python的标准库外,其不依赖任何其他模块. Bottl ...

  2. python bottle框架(WEB开发、运维开发)教程

    教程目录 一:python基础(略,基础还是自己看书学吧) 二:bottle基础 python bottle web框架简介 python bottle 框架环境安装 python bottle 框架 ...

  3. Python+Bottle+Sina SAE快速构建网站

    Bottle是新生一代Python框架的代表,利用Bottle构建网站将十分简单. Sina SAE是国内较出名的云平台之一,十分适用于个人网站的开发或创业公司网站开发. 下面将介绍如果通过Pytho ...

  4. Python的简介以及安装和第一个程序以及用法

    Python的简介: 1.Python是一种解释型.面向对象.动态数据类型的高级程序设计语言.自从20世纪90年代初Python语言诞生至今,它逐渐被广泛应用于处理系统管理任务和Web编程.Pytho ...

  5. 解决基于BAE python+bottle开发上的一系列问题 - artwebs - 博客频道 - CSDN.NET

    解决基于BAE python+bottle开发上的一系列问题 - artwebs - 博客频道 - CSDN.NET 解决基于BAE python+bottle开发上的一系列问题 分类: python ...

  6. [Python] heapq简介

    [Python] heapq简介 « Lonely Coder [Python] heapq简介 judezhan 发布于 2012 年 8 月 8 日 暂无评论 发表评论 假设你需要维护一个列表,这 ...

  7. 让python bottle框架支持jquery ajax的RESTful风格的PUT和DELETE等请求

    这两天在用python的bottle框架开发后台管理系统,接口约定使用RESTful风格请求,前端使用jquery ajax与接口进行交互,使用POST与GET请求时都正常,而Request Meth ...

  8. Python单元测试简介及Django中的单元测试

    Python单元测试简介及Django中的单元测试 单元测试负责对最小的软件设计单元(模块)进行验证,unittest是Python自带的单元测试框架. 单元测试与功能测试都是日常开发中必不可少的部分 ...

  9. Python列表简介和遍历

    一.Python3列表简介 1.1.Python列表简介 序列是Python中最基本的数据结构 序列中的每个值都有对应的位置值,称之为索引,第一个索引是0,第二个索引是1,以此类推. Python有6 ...

随机推荐

  1. java中instanceof的用法

    java 中的instanceof 运算符是用来在运行时指出对象是否是特定类的一个实例.instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例. 用法:resu ...

  2. Ajax 下拉加载数据

    $(document).scroll(function() { var pageHeight = $(document).height()-$(window).height(); var bodySc ...

  3. highcharts第一篇---简介和使用

    Highcharts 是一个用纯JavaScript编写的一个图表库, 能够很简单便捷的在web网站或是web应用程序添加有交互性的图表,并且免费提供给个人学习.个人网站和非商业用途使用.HighCh ...

  4. php中__clone() shallow copy 只是浅复制

    什么是浅复制呢? 简单一点,就是说复制一个对象的时候,如果对象$Obj的一个属性的类型是引用类型的,比如 $person这个属性,指向的是一个 叫做 $objPerson的一个引用, 那么复制$Obj ...

  5. php 安装php5-mysql 拓展

    Your PHP installation appears to be missing the MySQL extension which is required by WordPress Error ...

  6. 中文字符 unicode转utf-8函数 python实现

    unicode编码范围 00000000-0000007F的字符,用单个字节来表示: 00000080-000007FF的字符用两个字节表示 (中文的编码范围) 00000800-0000FFFF的字 ...

  7. IIS发布WebService的一些常见问题

    安装IIS过程,在控制面板程序à程序功能à打开或关闭windows功能. 将Internet信息服务中的选项全部选中,点击确定. 验证IIS是否正确安装,等待几分钟后IIS配置完成在浏览器输入http ...

  8. WINDOWS动态链接库--MFC规则动态链接库

    第一代window程序员使用windows api进行编程,到了后来,微软推出MFC类库,于是,动态链接库进行了升级,可以在动态连接库中使用MFC的API,这就叫做MFC动态链接库, 其中MFC动态链 ...

  9. storybody中页面跳转

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ if ([segue.destinationViewCont ...

  10. jQuery修改css属性

    jQuery CSS 操作jQuery 拥有三种用于 CSS 操作的重要函数:$(selector).css(name,value)$(selector).css({properties})$(sel ...