首页 > 为一个变量设置代理

为一个变量设置代理

由于sae上不能使用flask-login,所以我只能自己写一个flask-login里的current_user

现在有一个函数get_current_user
调用后会返回一个User对象
如:

user = get_current_user()

怎么样给变量current_user设置一个代理使每一次调用这个对象都会是get_current_user的返回值

仿照flask-login源码,找到一个方法:

    from flask import (session,
                       redirect,
                       url_for)
    from ..models import User
    from werkzeug.local import LocalProxy
    def get_current_user():
        current_user = User.query.get(session.get('current_user_id'))
        return current_user
    current_user = LocalProxy(get_current_user)
    
在别的地方导入current_user即可

如果问题引申为为一个变量设置代理呢,有没有简单的写法呢,不用到库

@cppprimer 的答案给我了思路

class Proxy(object):
    def __init__(self, local):
        self._local= local

    def __getattribute__(self,args):
        return object.__getattribute__(self,'_local')().__dict__[args]

class User(object):
    def __init__(self):
        self.num = 1

user= User()

def get_current_user():
    return user

current_user = Proxy(get_current_user)
print(current_user.num)
user.num = 2
print(current_user.num)

输出
1
2

但是这样直接调用current_user的返回值不是一个User对象,而是一个Proxy对象


flask_login 不是已经做了嘛

@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)

这样设置了之后,每次调用current_user都会返回当前用户的user对象。当然,User 需要实现get_id()方法。
参考:flask_login


想要用最简单的方法就是写一个代理类

def User(object):
    def function1(self):
        #some code

    def function2(self):
        #some code

class UserProxy(User):
    def function1(self):
        return get_current_user().function1()

    def function1(self):
        return get_current_user().function1()

current_user = UserProxy()

那如果是這樣你願意嗎? (用 random 只是用來測試, 你可以忽略他...)

import random

class Current:

    @property
    def user(self):
        return random.randint(1, 10)

current = Current()
print(current.user)
print(current.user)
print(current.user)
print(current.user)

current.usercurrent_user 要打的字數一樣多

結果:

7
2
9
1

我覺得

呼叫 function 沒什麼不好的阿...
不過這題有高手知道怎麼做的話(不需要使用 object 的 trick) 也請告訴我!!


我回答過的問題: Python-QA


from flask import session, redirect, url_for
from ..models import User
from werkzeug.local import LocalProxy
def get_current_user():

current_user = User.query.get(session.get('current_user_id'))
return current_user 

current_user = LocalProxy(get_current_user)

这里的current_user就是current_user啊, LocalProxy代理多次一举了.

【热门文章】
【热门文章】