代码改变世界

使用bottle进行web开发(1):hello world

2017-06-16 15:34  很大很老实  阅读(976)  评论(0编辑  收藏  举报

 

 为什么使用bottle?因为简单,就一个py文件,和其他模块没有依赖,3000多行代码。

http://www.bottlepy.org/docs/dev/

 

既然开始学习,就安装它吧。

pip3 install bottle

ok

第一个代码:

from bottle import route,run,template

@route('/hello/<name>')
def index(name):
    return template('<b>Hello {{name}}</b>!',name=name)

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

运行ok

从这段代码可以i看出来,bottle虽小,支持不差,包括route,template等,都支持。

而最后一行代码的run,实际上,就是启动一个内置的web server。3000多行代码,还包括一个这个,厉害。

 

 

处于简单的目的,我们后续学习,大部分时候,都是用一个module-level的装饰器route()去定义路由。这会把routes都加入到一个全局的缺省程序,当第一次调用route()的时候,Bottle的一个进程会被创建。

实际上,更应该代码是这样的;

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

上面的,route基本都是静态的,下面,我们介绍动态路由:

动态路由相对静态路由来说,用的更广泛,一次性匹配更多的url:

比如/hello/<name>可以匹配:/hello/wcf /hello/hanyu /hello/whoami 但是不匹配:/hello /hello/ /hello/wcf/ddd

举例如下;

@route('/wiki/<pagename>') # matches /wiki/Learning_Python
def show_wiki_page(pagename):
...
@route('/<action>/<user>') # matches /follow/defnull
def user_api(action,

这里,还需要关注动态路由的Filters(我称之为匹配器,目前有4种,可以增加更多),具体是:

:int matches (signed) digits only and converts the value to integer.
• :float similar to :int but for decimal numbers.
• :path matches all characters including the slash character in a non-greedy way and can be used to match more
than one path segment.
• :re allows you to specify a custom regular expression in the config field. The matched value is not modified

 

举例

from flask import Flask

app = Flask(__name__)

@app.route('/user/<int:user_id>'
def user(user_id):
    return 'Hello,%d' %user_id

if __name__ == '__main__':
    app.run(debug=True)
#coding:utf-8

from flask import Flask
from werkzeug.routing import BaseConverter

#定义正则转换器的类
class RegexConverter(BaseConverter):
    def __init__(self,url_map,*items):
        super(RegexConverter, self).__init__(url_map)
        self.regex=items[0]

app = Flask(__name__)
#实例化
app.url_map.converters['regex']=RegexConverter

@app.route('/user/<regex("([a-z]|[A-Z]){4}"):username>', methods=['POST', 'GET'])
def user(username):
    return 'Hello,%s' % username

if __name__ == '__main__':
    app.run(debug=True)

 

代码如下;