嘿,Amedrikaner!
看来您的用例很简单,我们可以自己实现。在下面的代码中,我将在用户会话中存储您的令牌,并签入新包装。让我们开始制作自己的包装器,我通常只是将它们放在wrappers.py文件中,但是可以将其放置在所需的位置。
def require_api_token(func): @wraps(func) def check_token(*args, **kwargs): # Check to see if it's in their session if 'api_session_token' not in session: # If it isn't return our access denied message (you can also return a redirect or render_template) return Response("Access denied") # Otherwise just send them where they wanted to go return func(*args, **kwargs) return check_token凉!
现在我们已经实现了包装器,我们只需将其令牌保存到会话中即可。超级简单。让我们修改您的功能…
@main.route("/login", methods=["GET", "POST"])def login(): payload = {"User": "john", "Password": "password123"} url = "http://webserviceexample/api/login" headers = {'content-type': 'application/json'}) #login to web service r = requests.post(url, headers=headers, json=payload) response = r.json() if (r.status_pre is 200): token = response['user']['authentication_token'] # Move the import to the top of your file! from flask import session # Put it in the session session['api_session_token'] = token # allow user into protected view return render_template("login.html", form=form)现在,您可以使用@require_api_token包装器检查受保护的视图,如下所示…
@main.route('/super_secret')@require_api_tokendef super_secret(): return "Sssshhh, this is a secret"编辑 哇!我忘了提到您需要在应用程序配置中设置SECRET_KEY。
只需使用SECRET_KEY =“ SOME_RANDOM_STRING”的config.py文件即可。然后加载…
main.config.from_object(config)



