溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Bottle 框架源碼學習 一

發(fā)布時間:2020-06-11 21:20:52 來源:網(wǎng)絡 閱讀:613 作者:落寞三少 欄目:開發(fā)技術
# -*- 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 裝飾器的作用是將瀏覽器請求的路徑綁定到指定的函數(shù)(index)中,瀏覽器訪問http://localhost:8080/hello/youname 時,實際上就是調(diào)用了index函數(shù)。

下面看看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裝飾器函數(shù)

1.

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

  functools一python的標準庫之一,wraps的作用是讓被裝飾的函數(shù)能保留原來的__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()里面怎么實現(xiàn)暫時不看,意思是獲取app()對象的route方法,接著傳遞參數(shù)調(diào)用

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

  route的內(nèi)部實現(xiàn)先不看


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI