由于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对象
The simplest way is to write a proxy class
If that’s the case, are you willing? (Use
random
just for testing, you can ignore it...)current.user
跟current_user
The number of words to type is the sameResult:
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?
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
The current_user here is the current_user, LocalProxy agent has done it many times.