简体   繁体   English

无法在 MethodView 中使用 flask_login 访问当前用户 ID

[英]Cannot access current user id using flask_login in MethodView

I have a problem accessing user-id inside a POST request in Class-based views.在基于类的视图中访问 POST 请求中的用户 ID 时遇到问题。 Inside a GET method, I can easily get data.在 GET 方法中,我可以轻松获取数据。 I guess the problem is because my POST method is not decorated with @login_required , but I cannot decorate POST since getting an error, what is a workaround to access logged user id?我想问题是因为我的 POST 方法没有用@login_required ,但是由于出现错误我无法修饰 POST,访问登录用户 ID 的解决方法是什么?

Authenticate.py验证.py

class Authenticate(MethodView):

  def post(self):
    ...some code
    login_user(user, remember=True)
    g.user = current_user.id

In this class, I want to access users id在这个 class 中,我想访问用户 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使用 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

This assumes that your login or authenticate endpoint saved the user somewhere before login_user .这假设您的loginauthenticate端点在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.为简单起见,上面的代码片段将其存储在 python 字典中,其中键是您的唯一 user_id,值是您的用户信息。

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 )现在,当您调用任何端点时,将调用此 user_loader 回调 function 并使用您返回的用户( return user )填充 current_user object

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当然 save_user() 应该将用户保存在 user_loader 回调可以访问的地方

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM