[英]Why child threads cannot access the current_user variable in flask_login?
[英]Cannot access current user id using flask_login in MethodView
在基於類的視圖中訪問 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
在這個 class 中,我想訪問用戶 id
class User(MethodView):
def post(view):
# not working
print(current_user.id)
print(g.user)
使用 Flask-Login 時,應該有user_loader
回調 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
這假設您的login
或authenticate
端點在login_user
之前的某個位置保存了用戶。 為簡單起見,上面的代碼片段將其存儲在 python 字典中,其中鍵是您的唯一 user_id,值是您的用戶信息。
現在,當您調用任何端點時,將調用此 user_loader 回調 function 並使用您返回的用戶( return user
)填充 current_user object
對於您的代碼,它可能會像這樣工作
def post(self):
...some code
## New code ##
save_user(user._id, user)
login_user(user, remember=True)
return {"state":"authenticated"}, 200
當然 save_user() 應該將用戶保存在 user_loader 回調可以訪問的地方
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.