Python轻量级web框架bottle使用方法解析

时间:2022-07-27
本文章向大家介绍Python轻量级web框架bottle使用方法解析,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Bottle是一个轻量级的Web框架,此框架只由一个 bottle.py 文件构成,不依赖任何第三方模块。

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

app = Bottle()


@app.route('/say')
def index():
  return "Hello World"
  # return template('<b Hello {{name}}</b !', name="bottle")

if __name__ == '__main__':

  app.run(server="tornado",host='0.0.0.0', port=8888)

1、路由系统

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

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

1.1静态路由

@app.route("/login") # 默认为get请求
def hello():
  return """
  <form action="/login" method="post" 
  Username:<input name="username" type="text" / 
  Password:<input name="password" type="password" / 
  <input value="Login" type="submit"/ 
  </form 
  """

@app.route("/login",method="POST")
def do_login():
  username = request.forms.get("username")
  password = request.forms.get("password")
  print(username,password)
  if username and password:
    return "<p login success</p "
  else:
    return "<p login failure</p "

1.2动态路由

@app.route('/say/<name ')
def callback(name):
  return template('<b Hello {{name}}</b !')
 
@app.route('/say/<id:int ')
def callback(id):
  return template('<b Hello {{id}}</b !')
 
@app.route('/say/<name:re:[a-z]+ ')
def callback(name):
  return template('<b Hello {{name}}</b !')
 
@app.route('/static/<path:path ')
def callback(path):
  return static_file(path, root='static')

1.3请求方法路由

@app.route('/hello/', method='POST')  # 等同于@app.post('/hello/')
def index():
  ...
 
@app.get('/hello/')  # 等同于@app.route('/hello/',method='GET')
def index():
  ...
 
@app.post('/hello/')  # 等同于@app.route('/hello/',method='POST')
def index():
  ...
 
@app.put('/hello/') # 等同于@app.route('/hello/',method='PUT')
def index():
  ...
 
@app.delete('/hello/') 
def index():
  ...

1.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
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bottle import template, Bottle

app02 = Bottle()
@app02.route('/hello/', method='GET')
def index():
  return template('<b App02</b !')
app02.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bottle import template, Bottle
from bottle import static_file
app = Bottle()
 
@app.route('/hello/')
def index():
  return template('<b Root {{name}}</b !', name="bottle")
 
from root_dir import app01
from root_dir import app02
 
app.mount('app01', app01.app01)
app.mount('app02', app02.app02)
 
app.run(host='localhost', port=8888)

1.5静态文件映射,static_file()函数用于响应静态文件的请求

# 静态文件映射,static_file()函数用于响应静态文件 的请求
@app.route("/static/<filename:re:.*.jpg ")
def send_image(filename):
  return static_file(filename, root=os.getcwd(), mimetype="image/jpg")

@app.route("/static/<filename:path ")  # 可匹配路径
def send_image(filename):
  return static_file(filename, root=os.getcwd(), mimetype="image/jpg")

# 强制下载
@app.route("/static/<filename:path ")  # 可匹配路径
def download(filename):
  return static_file(filename, root=os.getcwd(), download=filename)

1.6使用error()函数自定义错误页面

@app.error(404) def error404(error): return “我找不到目标了,我发生错误了”

1.7HTTP错误和重定向

abort()函数是生成HTTP错误的页面的一个捷径

@app.route("/restricted")
def restricted()
  abort(401,"Sorry, access denied")
# 将url重定向到其他url,可以在location中设置新的url,接着返回一个303 # redirect()函数可以帮助我们做这件事

@app.route("/wrong/url")
def wrong()
  redirect("/right/url")

其他异常

除了HTTPResponse或者HTTPError以外的其他异常,都会导致500错误,因此不会造成WSGI服务器崩溃

将bottle.app().catchall的值设为False来关闭这种行为,以便在中间件中处理异常

2.cookies

@app.route("/login", method="POST")
def do_login():
  username = request.forms.get("username")
  password = request.forms.get("password")
  print(username, password)
  if username and password:
    response.set_cookie("name",username, secret= 'some-secret-key')  # 设置cookie
    return "<p login success</p "
  else:
    return "<p login failure</p "
@app.route("/static/<filename:re:.*.jpg ")
def send_image(filename):
  username = request.get_cookie("name", secret= 'some-secret-key')  # 获取cookie
  if username:
    return static_file(filename, root=os.getcwd(), mimetype="image/jpg")
  else:
    return "verify failed"

bottle就的 set_cookie 的默认 path 是当前路径,也就是说,在这个页面上存入的 cookie 在别的页面通常是取不到的,不熟悉这点的人几乎都要栽在这里。而且更坑的是:set_cookie 有 path 参数可以指定 path ,但 get_cookie 却没有这个 path 参数可选——也就是说,你即使设置了其它 path ,如果 get_cookie 的时候不是刚好在那个 path 下的话,也取不到……

解决方法:把所有的 cookie 都放到”/”下面,至少目前用下来感觉没问题。

注:request.query 或 request.forms 都是一个 FormDict 类型,

其特点是:当以属性方式访问数据时——如 request.query.name,返回的结果是 unicode ,当以字典试访问数据时,如 :request.query[‘name’]或者request.query.get(“name”),则返回的结果是原编码字符串

以上就是本文的全部内容,希望对大家的学习有所帮助。