目 录CONTENT

文章目录

Api开发利器Bottle

phyger
2022-02-21 / 0 评论 / 0 点赞 / 1,016 阅读 / 2,462 字 / 正在检测是否收录...

前言

前面我们介绍了很多 API 开发框架,比如FastApiHug等。今天我们继续介绍一款超轻的 web 框架 Bottle,它的使用和 FlaskHug 一样简单。

呆猫

安装 Bottle

pip install bottle

Hello World

from bottle import route, run

@route('/hello')
def hello():
    return "Hello World!"

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

wsgi启动成功

页面效果

如上我们已经实现了 hello world,但是这不是面向对象的方式,我们可以使用面向对象的方式,先实例化一个 bottle 对象,然后在这个对象上进行路由等操作。

就像这样:

from bottle import Bottle, run

app = Bottle()

@app.route('/hello')
def hello():
    return "Hello World!"

run(app, host='localhost', port=8080)

如上两种方式都可以实现 api 的开发,你可以根据自己喜好进行选择,但是个人比较推荐面向对象的写法。

路径参数

路径参数就是 URI 中的参数,我们可以通过 URI 进行参数的传递和处理。

from bottle import Bottle, run, template

app = Bottle()

@app.route('/hello')
def hello():
    return "Hello World!"

@app.route('/sayhi/<name>')
def sayhi(name='default'):
    return f'hi,{name}'

run(app, host='localhost', port=8080)

路径参数的传递和接收

请求参数

请求参数就是在 URL 后面拼接的参数,使用?进行连接。

from bottle import Bottle, run,request

app = Bottle()

@app.route('/myinfo')
def myinfo():
    return f"我的姓名是:{request.params['name']},我的年龄是:{request.params['age']}"

run(app, host='localhost', port=8080)

请求参数的传递和接收

模板渲染

和其他 web 框架一样,bottle 的模板渲染也是将 html 内容渲染到浏览器。bottle 渲染支持 tplhtml 两种文件,你可以自由选择。

注意,bottle 是在项目根路径和./views/*两个路径下进行模板文件的扫描,通常建议将模板文件统一放到./views/下。

from bottle import Bottle, run,request,template

app = Bottle()

@app.route('/tm')
def tm(tinfo='template'):
    return template('index',tinfo=tinfo)

run(app, host='localhost', port=8080)

模板渲染效果

bottle 不但支持使用 templates 方法来进行页面渲染,也支持使用 view 装饰器进行渲染。

就像这样:

from bottle import Bottle, run,request,template,view

app = Bottle()

@app.route('/tm')
@view('index')
def tm(tinfo='template-view'):
    return dict(tinfo=tinfo)

run(app, host='localhost', port=8080)

view装饰器模板渲染效果

我们结合请求参数看下效果:

from bottle import Bottle, run,request,template,view

app = Bottle()

from urllib import parse
@app.route('/tm')
@view('index')
def tm():
    a=request.query['gg']
    b = parse.unquote_plus(a)
    print(b)
    return dict(tinfo=request.params['gg'])

run(app, host='localhost', port=8080)

模板结合请求参数的效果

自定义 404 等页面

bottle 支持 error 装饰器来拦截错误码进行统一的错误页面展示。


from bottle import Bottle, run,request,template,view

app = Bottle()

@app.error(404)
def error404(error):
    return f'Python全栈开发提醒您:啥都没找到!{error}'

run(app, host='localhost', port=8080)

自定义404页面

重定向

重定向,顾名思义就是访问 a,然后服务器向浏览器发送的重定向指令,让浏览器去访问 b

from bottle import Bottle, run,request,template,view,redirect

app = Bottle()


@app.route('/hello')
def hello():
    return "Hello World!"

@app.get('/red')
def red():
    redirect('/hello')

run(app, host='localhost', port=8080)

重定向效果

热加载

你可能已经发现前面的操作都是需要手动进行服务器的重启的,其实 bottle 也支持开发服务器的热加载,你只需要在 run 方法中增加 reloader=True 的配置即可。这样当你修改了代码的时候,bottle 就会自动加载了。

总结

内容有限,以上我们只演示了 bottle 的基本功能,从这些演示中我们已经发现 bottle 的使用非常简答,很多的特性一个装饰器就能搞定,感兴趣的同学可以动手试试。更多的内容请关注 bottle 的官方文档:http://bottlepy.org

0

评论区