温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Bottle 框架源码学习 一

发布时间:2020-06-11 21:20:52 来源:网络 阅读:595 作者:落寞三少 栏目:开发技术
# -*- 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的内部实现先不看


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI