Bottle

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

1 pip install bottle
2 easy_install bottle
3 apt-get install python-bottle
4 wget http://bottlepy.org/bottle.py

Bottle框架大致可以分为以下部分:

  • 路由系统,将不同请求交由指定函数处理
  • 模板系统,将模板中的特殊语法渲染成字符串,值得一说的是Bottle的模板引擎可以任意指定:Bottle内置模板、makojinja2cheetah
  • 公共组件,用于提供处理请求相关的信息,如:表单数据、cookies、请求头等
  • 服务,Bottle默认支持多种基于WSGI的服务,如:
 1 server_names = {
 2     'cgi': CGIServer,
 3     'flup': FlupFCGIServer,
 4     'wsgiref': WSGIRefServer,
 5     'waitress': WaitressServer,
 6     'cherrypy': CherryPyServer,
 7     'paste': PasteServer,
 8     'fapws3': FapwsServer,
 9     'tornado': TornadoServer,
10     'gae': AppEngineServer,
11     'twisted': TwistedServer,
12     'diesel': DieselServer,
13     'meinheld': MeinheldServer,
14     'gunicorn': GunicornServer,
15     'eventlet': EventletServer,
16     'gevent': GeventServer,
17     'geventSocketIO':GeventSocketIOServer,
18     'rocket': RocketServer,
19     'bjoern' : BjoernServer,
20     'auto': AutoServer,
21 }

框架的基本使用

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 from bottle import template, Bottle
 4 root = Bottle()
 5  
 6 @root.route('/hello/')
 7 def index():
 8     return "Hello World"
 9     # return template('<b>Hello {{name}}</b>!', name="Alex")
10  
11 root.run(host='localhost', port=8080)

一、路由系统

路由系统是的url对应指定函数,当用户请求某个url时,就由指定函数处理当前请求,对于Bottle的路由系统可以分为一下几类:

  • 静态路由
  • 动态路由
  • 请求方法路由
  • 二级路由

1、静态路由

1 @root.route('/hello/')
2 def index():
3     return template('<b>Hello {{name}}</b>!', name="Alex")

2、动态路由

 1 @root.route('/wiki/<pagename>')
 2 def callback(pagename):
 3     ...
 4  
 5 @root.route('/object/<id:int>')
 6 def callback(id):
 7     ...
 8  
 9 @root.route('/show/<name:re:[a-z]+>')
10 def callback(name):
11     ...
12  
13 @root.route('/static/<path:path>')
14 def callback(path):
15     return static_file(path, root='static')

3、请求方法路由

 1 @root.route('/hello/', method='POST')
 2 def index():
 3     ...
 4  
 5 @root.get('/hello/')
 6 def index():
 7     ...
 8  
 9 @root.post('/hello/')
10 def index():
11     ...
12  
13 @root.put('/hello/')
14 def index():
15     ...
16  
17 @root.delete('/hello/')
18 def index():
19     ...

 

posted @ 2017-05-11 23:22  LaniLai  阅读(368)  评论(0编辑  收藏  举报