Python的WEB框架

Bottle

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

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

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

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

框架的基本使用

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bottle import template, Bottle
root = Bottle()

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

root.run(host='localhost', port=8080)

一、路由系统

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

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

1、静态路由

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

2、动态路由

@root.route('/wiki/<pagename>')
def callback(pagename):
    ...

@root.route('/object/<id:int>')
def callback(id):
    ...

@root.route('/show/<name:re:[a-z]+>')
def callback(name):
    ...

@root.route('/static/<path:path>')
def callback(path):
    return static_file(path, root='static')

3、请求方法路由

@root.route('/hello/', method='POST')
def index():
    ...

@root.get('/hello/')
def index():
    ...

@root.post('/hello/')
def index():
    ...

@root.put('/hello/')
def index():
    ...

@root.delete('/hello/')
def index():
    ...

4、二级路由

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bottle import template, Bottle

app01 = Bottle()

@app01.route('/hello/', method='GET')
def index():
    return template('<b>App01</b>!')
app01.py

相关文章: