python - 为一个变量设置代理
PHP中文网
PHP中文网 2017-04-18 09:07:06
0
4
691

由于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对象

PHP中文网
PHP中文网

认证0级讲师

reply all(4)
巴扎黑

The simplest way is to write a proxy class

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()
Peter_Zhu

If that’s the case, are you willing? (Use random just for testing, you can ignore it...)

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 The number of words to type is the same

Result:

7
2
9
1

I think

There is nothing wrong with calling function...
But if there is an expert who knows how to do this (without using the object trick), please tell me!!


Questions I answered: Python-QA

阿神

flask_login Isn’t it already done?

@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)
After setting it like this, each time current_user is called, the user object of the current user will be returned. Of course, User needs to implement the get_id() method.

Reference: 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)

The current_user here is the current_user, LocalProxy agent has done it many times.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template