我在flask_login上遇到问题。但是在测试时,我意识到当我请求一个login_required路由时,我得到了401未经授权的错误。我确定我已经登录。
任何帮助表示赞赏。谢谢!
这是我的登录功能:
@app.route('/login', methods=['POST'])
def login():
req = request.values
_id = req['id']
_password = req['password']
if _id not in USERS:
return {'message': 'Invalid credentials'}, 401
elif not USERS[_id].can_login(_password):
return {'message': 'Invalid credentials'}, 401
else:
USERS[_id].authenticated = True
login_user(USERS[_id], remember=True)
return {'message': 'Logged in'}, 200
这是我的用户模型(如果需要)
class User:
def __init__(self, _id, _password, _score=0,
authenticated=False):
self._id = _id
self._password = _password
self._score = _score
self.authenticated = authenticated
def __repr__(self):
r = {
'id': self._id,
'password': self._password,
'score': self._score,
}
return str(r)
def can_login(self, _password):
return self._password == _password
def is_active(self):
return True
def get_id(self):
return self._id
def is_authenticated(self):
return self.authenticated
def is_anonymous(self):
return False
这是我的user_loader函数
@login_manager.user_loader
def user_loader(_id):
return USERS[_id]
我通过请求模块对其进行了测试
>>> print(requests.post(url+"login", data={"id":"test", "password":"1"}).content)
b'{\n "message": "Logged in"\n}\n'
>>> print(requests.get(url+"users").content)
b'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n<title>401 Unauthorized</title>\n<h1>Unauthorized</h1>\n<p>The server could not verify that you are authorized to access the URL requested. You either supplied the wrong credentials (e.g. a bad password), or your browser doesn\'t understand how to supply the credentials required.</p>\n'
我的问题是我没有在请求中存储cookie。通过发出request.Session,我得以使其工作。
s = request.Session()
>>> print(s.post(url+"login", data={"id":"test", "password":"1"}).content)
>>> print(requests.get(url+"users").content)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句