Is it possible to set a cookie when using jsonify?

@user.route('/login', methods=['POST'])
def check_oauthuser():
    token = request.args.get('token','')
    open_u_id = request.args.get('openUId','')
    _self_expires = 60 * 60 * 24 * 30 * 3

    #re = Response()
    #re.set_cookie('name','1111111')

    if token!='' and open_u_id!='':
        set_user_login_cache(user_id, token)
        return jsonify(state=0,msg='success')

I want to set a cookie in the response header, but I use jsonifyinstead of creating Response. What can I do to add a cookie on return jsonify?

+4
source share
1 answer

jsonifyreturns an object Response, so grab it before returning from your view and add a cookie, then Response.set_cookie.

out = jsonify(state=0, msg='success')
out.set_cookie('my_key', 'my_value')
return out

You might want to simply add a value to the session cookie. Flask sessionwill json encode values ​​and sign cookies for security, which you need to do manually when using set_cookie.

from flask import session

session['my_key'] = 'my_value'
+8

All Articles