python装饰器:有参数、不定长参数的装饰器

先看代码,代码中有两个函数都被testwra装饰器装饰,并且这两个函数一个有参数,一个没有参数,注意参数传递方法:

def users2dict(user):
    userdict = {}
    for name in dir(user):
        value = getattr(user, name)
        if not name.startswith('__') and not callable(value) and not name.startswith('_'):
            userdict[name] = value
    return userdict

def testwra(func):
    @functools.wraps(func)
    def _wrapper(*args, **kwargs):
        alluserlist = []
        allusers = func(*args, **kwargs)
        if type(allusers) == type(users()):
            allusers.password = '******'
            userdict = users2dict(allusers)
            alluserlist.append(userdict)
        else:
            for u in allusers:
                u.password = '******'
                userdict = users2dict(u)
                alluserlist.append(userdict)
        return json.dumps(alluserlist)
    return _wrapper

@app.route('/myinfo/<username>', methods=['GET'])
@testwra
def myinfohtml(username):
    # print "username", username
    if len(username) != 0:
        dbengine.connection(**dbconnect)
        u = users()
        user = u.find_first('name', username)
        dbengine.closeconnection()
    else:
        user = users()
        print "内部错误!"
    return user

@app.route('/users', methods=['GET'])
@testwra
def get_users():
    dbengine.connection(**dbconnect)
    u = users()
    findby = 'order by created_at desc'
    allusers = u.find_by(findby)
    dbengine.closeconnection()
    return allusers

 

转载于:https://my.oschina.net/u/3636678/blog/2218547

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值