python裝飾器:有參數、不定長參數的裝飾器

先看代碼,代碼中有兩個函數都被testwra裝飾器裝飾,而且這兩個函數一個有參數,一個沒有參數,注意參數傳遞方法:html

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
相關文章
相關標籤/搜索