1. 程式人生 > >Bottle 框架源碼學習 一

Bottle 框架源碼學習 一

python bottle

# -*- coding=utf-8 -*-
from bottle import route, run, template,Bottle

app = Bottle()

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


run(app, host="localhost", port=8080, reloader=True)

以上是官方一個簡單示例,

route 裝飾器的作用是將瀏覽器請求的路徑綁定到指定的函數(index)中,瀏覽器訪問http://localhost:8080/hello/youname 時,實際上就是調用了index函數。

下面看看route源碼

def make_default_app_wrapper(name):
    ‘‘‘ Return a callable that relays calls to the current default app. ‘‘‘
    @functools.wraps(getattr(Bottle, name))
    def wrapper(*a, **ka):
        return getattr(app(), name)(*a, **ka)
    return wrapper

route     = make_default_app_wrapper(‘route‘)


route是make_default_app_wrapper的別名,作者這樣寫的目的是為了簡化用戶輸入,而make_default_app_wrapper是是一個裝飾器,裝飾器的用法可以參考一下這些文章:

http://blog.scjia.cc/article/search/?wd=%E8%A3%85%E9%A5%B0%E5%99%A8


分析make_default_app_wrapper裝飾器函數

1.

  @functools.wraps(getattr(Bottle, name))

functools一python的標準庫之一,wraps的作用是讓被裝飾的函數能保留原來的__name__、__doc

看functools.wraps的簡單例子

import functools

def make_decorator(f):
    @functools.wraps(f)
    def wrapper(*args, **kws):
        """this is wrapper doc"""
        print ‘calling  decorator function‘
        return f(*args, **kws)
    return wrapper
    
@make_decorator
def example():
    """ this is my doc """
    print ‘this is example‘

example()
>>calling  decorator function
>>this is example

example.__name__
>>‘example‘
example.__doc__
>>‘ this is my doc ‘

如果去除@functools.wraps這段,__name__ 將輸出wrapper, __doc__將輸出this is wrapper doc


2. 再看

getattr(Bottle, name)

獲取Bottle的route,因為Bottle是類,得到的是<unbound method Bottle.route>

return getattr(app(), name)(*a, **ka)

app()裏面怎麽實現暫時不看,意思是獲取app()對象的route方法,接著傳遞參數調用

相當於,app()->route("/hello/yourname")

route的內部實現先不看


本文出自 “nickylans” 博客,請務必保留此出處http://378359.blog.51cto.com/368359/1959355

Bottle 框架源碼學習 一