我正在使用Flask構建一個RESTful應用程序,它將使用會話來跟蹤登錄的用戶。下面是我改編自這個Flask tutorialIn Flask如何使用安全會話以curl驗證用戶?
@mod.route('/login/', methods=['GET', 'POST'])
def login():
user = User.query.filter_by(email=request.json['email']).first()
# we use werkzeug to validate user's password
if user and check_password_hash(user.password, request.json['password']):
# the session can't be modified as it's signed,
# it's a safe place to store the user id
session['user_id'] = user.id
resp = jsonify({'status':'authenticated'})
else:
resp = jsonify({'status':'Invalid usernam/password'})
resp.status_code = 401
return resp
的登錄密碼,當用戶第一次登錄時,我存儲他們的用戶ID在會話中,這樣當同一個用戶請求資源,該數據是定製對他們說:
@mod.route('/address/')
@requires_login
def user_data():
user = User.query.filter_by(id=session['usr_id']).first
resp = jsonify(user.address)
return resp
如果我在登錄後發出此命令:
curl http://localhost:5000/address/
我收到:
{"status": 401, "message": "Unauthorized"}
而不是我登錄的用戶的地址信息。 任何人都可以告訴我如何在隨後的捲曲調用中使用會話來返回特定於cookie中存儲的用戶標識的數據?
真棒!謝謝@DazWorrall – ChiliConSql