简洁的web框架Bottle

简介

Bottle是一个非常简洁,轻量web框架,与django形成鲜明的对比,它只由一个单文件组成,文件总共只有3700多行代码,依赖只有python标准库。但是麻雀虽小五脏俱全,基本的功能都有实现,很适合做一些小的web应用

开始使用

首先使用pip install bottle安装
然后是一个官方文档中的例子:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

from bottle import route, run  @route('/hello') def hello(): return "Hello World!" run(host='localhost', port=8080, debug=True)

what? 只有5行代码,只有一个文件,就能跑了?
这真是太简洁了,我觉得非常适合我们写一些小的web页面应用,比起使用django要快速的多
还可以用下边这种方式启动:


from bottle import  Bottle
bt = Bottle()
@bt.route('/hello')
def hello():
    return "Hello World!"

bt.run(host='localhost', port=8080, debug=True)

Bottle的实例对象同样拥有这些方法

url路由

静态路由

通过上面的例子可以看到,Bottle框架的路由方式是通过装饰器来实现的,像这样@bt.route(‘/hello’),这种方式和和flask的路由方式一样,同django就有大不同了
如果习惯了django的路由方式,再看到Bottle这种装饰器路由的方式,一定会觉得这样真是很快速,至少这是在同一个文件里
刚才的例子当中的路由方式是静态路由,下面是动态路由的方式

动态路由

我们看一下几种动态路由的方式


@route ('/ wiki / <pagename>' )    # pagename会成为参数  
       def show_wiki_page (pagename):     

@route('/object/<id:int>')         # 使用过滤器,id为名称,int是匹配方式,并且会自动转为int型
 def callback(id):     assert isinstance(id, int) 

 @route('/show/<name:re:[a-z]+>')    # 可以使用正则表达式
 def callback(name):     assert name.isalpha() 

 @route('/static/<path:path>')   # path的意义为以非贪婪的方式匹配包括斜杠字符在内的所有字符,并且可用于匹配多个路径段。
 def callback(path):     return static_file(path, ...)

# 等等

HTTP请求方法路由

这意味只匹配允许的请求方式


from bottle import get, post

@get('/login') # get方式的login

@post('/login') # post方式的login

#get(),post(),put(),delete()或patch()

@route('/hello/', method='POST') #通过参数决定,

内置模板

我们返回给客户端的内容不仅仅是字符串,更多的是html文件,如何返回html文件呢?


from bottle import  Bottle,template
bt = Bottle()
@bt.route('/hello')
def hello():

    return template('hello.html')

bt.run(host='localhost', port=8080, debug=True)

引入template后就可以使用模板了,那么hello.html是在哪里呢?
查看源码
轻量的web框架Bottle Python 第1张
TEMPLATE_PATH默认是/与/views下,当然也可以配置bottle.TEMPLATE_PATH来改变默认路径
除此之外模板同样允许在html中使用传入的参数,比如这样:


return template('hello.html',name='sfencs')

hello.html中:


hello{{name}}

不仅如此,模板还支持:

  • % x = “sfencs” 一行python代码
  • <% %> 之间是代码块
  • % if True: if语句
    % end
  • % for i in name: for循环语句
    % end

使用函数

有一些内置函数可以直接在模板中使用

  • include(sub_template, **variables)
    可以导入其他的模板文件,例如:

% include('header.html', title='Page Title')
 Page Content
 % include('footer.html')

来导入header与footer,并且可以传入参数

  • rebase(name, **variables)
    例如:index.html中写:

% rebase('hello.html', title='Page Title')
<p>Page Content ...</p>

hello.html中写:


<html>
<head>
  <title>{{title or 'No title'}}</title>
</head>
<body>
  {{!base}}
</body>
</html>

作用相当于把index.html变为变量名为base的变量在hello.html中使用,并且可以传入参数,在服务的返回的页面还是index.html


from bottle import  Bottle,template
bt = Bottle()
@bt.route('/hello')
def hello():

    return template('index.html')

bt.run(host='localhost', port=8080, debug=True)
  • defined(name)
    检查变量是否被定义
  • get(name, default=None)
    获取变量的值
  • setdefault(name, default)
    变量设置默认值
  • 自定义函数
    也就是把函数传给模板使用

from bottle import  Bottle,template
bt = Bottle()
@bt.route('/hello')
def hello():

    return template('index.html',func=myfunc)

def myfunc():
    return 'my func'

bt.run(host='localhost', port=8080, debug=True)

index.html中:


{{func()}}

request与response

http请求必然有request与response对象
使用request对象需要引入request


from bottle import request

这时在请求中便可获取request对象中的内容,例如:


from bottle import  Bottle,template
from bottle import request,response
bt = Bottle()
@bt.route('/hello')
def hello():
    print(request.headers)
    return template('index.html')

bt.run(host='localhost', port=8080, debug=True)

request对象中还有很多属性

  • request.headers请求头信息
  • request.query get请求信息
  • request.forms post请求信息
  • request.files 上传文件信息
  • request.params get和post请求信息
  • request.GET get请求信息
  • request.POST post和上传信息
  • request.cookies cookie信息
  • 等等
    response对象使用是类似的:

from bottle import  Bottle,template
from bottle import request,response
bt = Bottle()
@bt.route('/hello')
def hello():

    response.add_header('sss','aaa')
    return template('index.html')

bt.run(host='localhost', port=8080, debug=True)

这时在浏览器中能够找到响应头中多了sss
轻量的web框架Bottle Python 第2张
response的属性有:

  • response.status_line 状态行
  • response.status_code 状态码
  • response.headers 响应头
  • response.charset 编码
  • response.set_cookie 在浏览器上设置cookie
  • response.delete_cookie 在浏览器上删除cookie
  • 等等

http错误与重定向

使用abort()来返回错误:


from bottle import route, abort @route('/restricted') def restricted(): abort(401, "Sorry, access denied.")

使用redirect()来重定向


from bottle import redirect @route('/wrong/url') def wrong(): redirect("/right/url")

服务器的使用

在执行run方法时,bottle默认使用wsgiref,wsgiref是开发时默认使用的单线程服务器,但通过指定参数可以改变服务器:


run(host='localhost', port=8080,server='paste')

具体可以使用哪些服务器可以参考http://www.bottlepy.org/docs/dev/deployment.html,
这里放一个截图
轻量的web框架Bottle Python 第3张

总结

在这里只是对Bottle框架的使用做了一个简单的介绍,具体学习还要参考官方文档
对于简单的web应用使用与web框架源码的学习,我认为Bottle是一个不错的选择。

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄