用模板渲染实现flask_jwt_extended [英] implementing flask_jwt_extended with templates rendering

查看:198
本文介绍了用模板渲染实现flask_jwt_extended的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这一次(我创建了所有需要的东西并且所有工作都顺利之后)再次尝试创建我的第一个烧瓶应用程序,我试图使用flask_jwt_extended保护某些端点,但是我找不到如何工作文档将它们放在我的页面中,主要是关于显示JSON消息,一些教程使用邮差,而在我的情况下,我使用的是HTML模板.
例如,用户将其凭据从登录页面发送到此端点:

Again fighting trying to make my first flask application, this time, (after I created every I need and all works smoothly) I'm trying to protect some endpoints with flask_jwt_extended, but I can't find how to work with them in my pages, the documentation is mostly about displaying JSON messages and some tutorials use postman while in my case I'm using HTML templates.
For example, a user sends his credentials from the login page to this endpoint :

@app.route('/login', methods=['POST'])
def UserLogin():
    data = parser.parse_args()
    current_user = UserModel.find_by_username(data['username'])
    if not current_user:
        return {'message': 'User {} doesn\'t exist'.format(data['username'])}

    if UserModel.verify_hash(data['password'], current_user.password):
        access_token = create_access_token(identity = data['username'])
        refresh_token = create_refresh_token(identity = data['username'])
        resp = jsonify({'login': True})         #I just added this line from the documentation
        set_access_cookies(resp, access_token)  # and this one
        set_refresh_cookies(resp, refresh_token) # and this one
        return redirect(url_for('results'))

    else:
        return {'message': 'Wrong credentials'}

当然,我在results端点上添加了@jwt_required装饰器:

and of course, I added the @jwt_required decorator the results endpoint:

@app.route('/result',methods = ['POST','GET'])
@jwt_required
def results():
    temp={}
    if request.method == 'POST':
        # some code to fill temp with values
    return render_template('result.html',data=temp)

所以我得到了{ "msg": "Missing cookie \"access_token_cookie\"" }
显然是因为我没有将jwt发送回去,但是如果在return语句中发送它,我该如何重定向用户我想要的页面?
我用app.config['JWT_TOKEN_LOCATION'] = ['cookies']

So I'm getting a { "msg": "Missing cookie \"access_token_cookie\"" }
Obviously because I'm not sending the jwt back but if send it in the return statement how can I redirect the user the page I want ??
And indeed I used app.config['JWT_TOKEN_LOCATION'] = ['cookies']

推荐答案

您可能想要:

resp = make_response(redirect(url_for('results')))
set_access_cookies(resp, access_token)
set_refresh_cookies(resp, refresh_token)
return resp

我认为您不需要此行! -> resp = jsonify({'login': True})

I don't think you need this line! --> resp = jsonify({'login': True})

请我花点时间弄清楚,不确定在文档,那里的大多数示例都直接返回JSON

Took me a while to figure it out, not sure why this part is not clear in the docs, most of the examples there just returns JSON directly

这篇关于用模板渲染实现flask_jwt_extended的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆