python bottle框架

python bottle框架

  • 简介:

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

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

路由系统,将不同请求交由指定函数处理
模板系统,将模板中的特殊语法渲染成字符串,值得一说的是Bottle的模板引擎可以任意指定:Bottle内置模板、mako、jinja2、cheetah
公共组件,用于提供处理请求相关的信息,如:表单数据、cookies、请求头等
服务,Bottle默认支持多种基于WSGI的服务

 

  • 安装

pip install bottle

easy_install bottle

框架基本使用,例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

from bottle import Bottle
root = Bottle()
 
@root.route('/index/')
def index():
    return "Hello World"
 
root.run(host='localhost', port=8080)

 效果:

 

一、路由系统

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

静态路由
动态路由, 正则表达式
请求方法路由, POST、GET、PUT等
二级路由, 分发至其它入口

1、静态路由

@root.route('/index/')
def index():
    return "welcome index page"

2、动态路由

输入的URL跟参数

@root.route('/index/<pagename>')
def index(pagename):
    return pagename

 

 

输入的参数为数字

@root.route('/index/<id:int>')
def index(id):
    return str(id)

 

 

正则表达式

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

 

静态文件

#!/usr/bin/env python
# -*- coding:utf-8 -*-

from bottle import Bottle, static_file
root = Bottle()

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

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

 3、请求方法路由

@root.route('/index/', method='POST')
def index():
    return "post"
 
@root.get('/index/')
def index():
    return "get"
 
@root.post('/index/')
def index():
    return "post"
 
@root.put('/index/')
def index():
    return "put"
 
@root.delete('/index/')
def index():
    return "delete"

 4、二级路由

index.py

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

root = Bottle()

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

import sub_index01
import sub_index02

root.mount('index01', sub_index01.index01_obj)
root.mount('index02', sub_index02.index02_obj)

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

sub_index01.py

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

index01_obj = Bottle()

@index01_obj.route('/sub_index01/', method='GET')
def index():
    return "sub_index01"

sub_index02.py

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

index02_obj = Bottle()

@index02_obj.route('/sub_index02/', method='GET')
def index():
    return "sub_index02"

访问主页

访问sub_index01子应用和sub_index02子应用

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值