当前位置: 移动技术网 > IT编程>脚本编程>Python > 轻量的web框架Bottle

轻量的web框架Bottle

2019年03月25日  | 移动技术网IT编程  | 我要评论

唐山教育局,水晶头骨,没想到116岁老人每天竟然吃这个!

简洁的web框架bottle

简介

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

开始使用

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

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是在哪里呢?
查看源码

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)
    例如:中写:
% 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>

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

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

    return template('')

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('',func=myfunc)

def myfunc():
    return 'my func'

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

中:

{{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('')

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('')

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

这时在浏览器中能够找到响应头中多了sss

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')

具体可以使用哪些服务器可以参考
这里放一个截图

总结

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网