flask - 无法在 MethodView 中使用 flask_login 访问当前用户 ID
问题描述
在基于类的视图中访问 POST 请求中的用户 ID 时遇到问题。在 GET 方法中,我可以轻松获取数据。我想问题是因为我的 POST 方法没有用 装饰@login_required
,但是由于出现错误,我无法装饰 POST,访问记录的用户 ID 的解决方法是什么?
验证.py
class Authenticate(MethodView):
def post(self):
...some code
login_user(user, remember=True)
g.user = current_user.id
在这个类中,我想访问用户 id
class User(MethodView):
def post(view):
# not working
print(current_user.id)
print(g.user)
解决方案
When using Flask-Login, you should have user_loader
callback function
from flask_login import LoginManager
app = Flask(__name__)
login_manager = LoginManager(app)
@app.login_manager.user_loader
def load_user(_id):
user = users[_id]
return user
This assumes that your login
or authenticate
endpoint saved the user somewhere before login_user
. For simplicity the above snippet stores it in python dictionary where key is your unique user_id and the value is your user's information.
Now when any of your endpoints are called, this user_loader callback function is called and the current_user object is populated with your the returned user (return user
)
For your code it might work like that
def post(self):
...some code
## New code ##
save_user(user._id, user)
login_user(user, remember=True)
return {"state":"authenticated"}, 200
Of course save_user() should save the user somewhere accessible by the user_loader callback
推荐阅读
- python - 酌情将行从一个数据帧分配到另一个数据帧
- python - 球体上三角形的六边形:从二十面体网格构建六边形/测地线网格(仅限北极)
- vba - 如何将项目添加到包含分号的组合框(使用 AddItem())?
- javascript - 如何编写分组算法,通过具有 3 个或更多相似属性对数据集中的项目进行分组
- r - 计算字符串出现在组列中的次数
- mysql - 如何使用 ORDER BY 计算行数直到某个值
- angular - Angular - Laravel 获得记录最多的前 5 个 ID
- typescript - 在 Typescript 中注释高阶函数
- reactjs - 从 componentWillReceiveProps 迁移到 getDerivedStateFromProps
- java - 以不同的身份膨胀 for 循环中的视图?