Python的Bottle框架基本知识总结

2019-10-17 20:23:32丽君

基本映射

映射使用在根据不同URLs请求来产生相对应的返回内容.Bottle使用route() 修饰器来实现映射.

from bottle import route, run
@route('/hello')
def hello():
  return "Hello World!"
run() # This starts the HTTP server

运行这个程序,访问http://localhost:8080/hello将会在浏览器里看到 "Hello World!".
GET, POST, HEAD, ...

这个射装饰器有可选的关键字method默认是method='GET'. 还有可能是POST,PUT,DELETE,HEAD或者监听其他的HTTP请求方法.

 

from bottle import route, request
@route('/form/submit', method='POST')
def form_submit():
  form_data = request.POST
  do_something(form_data)
  return "Done"

动态映射

你可以提取URL的部分来建立动态变量名的映射.

@route('/hello/:name')
def hello(name):
  return "Hello %s!" % name

默认情况下, 一个:placeholder会一直匹配到下一个斜线.需要修改的话,可以把正则字符加入到#s之间:

@route('/get_object/:id#[0-9]+#')
def get(id):
  return "Object ID: %d" % int(id)

或者使用完整的正则匹配组来实现:

@route('/get_object/(?P<id>[0-9]+)')
def get(id):
  return "Object ID: %d" % int(id)

正如你看到的,URL参数仍然是字符串, 即使你正则里面是数字.你必须显式的进行类型强制转换.
@validate() 装饰器

Bottle 提供一个方便的装饰器validate() 来校验多个参数.它可以通过关键字和过滤器来对每一个URL参数进行处理然后返回请求.

from bottle import route, validate
# /test/validate/1/2.3/4,5,6,7
@route('/test/validate/:i/:f/:csv')
@validate(i=int, f=float, csv=lambda x: map(int, x.split(',')))
def validate_test(i, f, csv):
  return "Int: %d, Float:%f, List:%s" % (i, f, repr(csv))

你可能需要在校验参数失败时抛出ValueError.
返回文件流和JSON

WSGI规范不能处理文件对象或字符串.Bottle自动转换字符串类型为iter对象.下面的例子可以在Bottle下运行, 但是不能运行在纯WSGI环境下.
 

@route('/get_string')
def get_string():
  return "This is not a list of strings, but a single string"
@route('/file')
def get_file():
  return open('some/file.txt','r')

字典类型也是允许的.会转换成json格式,自动返回Content-Type: application/json.
 

@route('/api/status')
def api_status():
  return {'status':'online', 'servertime':time.time()}

你可以关闭这个特性:bottle.default_app().autojson = False
Cookies

Bottle是把cookie存储在request.COOKIES变量中.新建cookie的方法是response.set_cookie(name, value[, **params]). 它可以接受额外的参数,属于SimpleCookie的有有效参数.
 

from bottle import response
response.set_cookie('key','value', path='/', domain='example.com', secure=True, expires=+500, ...)