Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a cookie be set 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 into the response header, but I use jsonify instead of creating a Response. What can I do to add a cookie when returning jsonify?

like image 695
Oceanseas Avatar asked Oct 27 '14 12:10

Oceanseas


1 Answers

jsonify returns a Response object, so capture it before returning from your view and add the cookie then with Response.set_cookie.

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

You might want to just add the value to the session cookie. Flask's session will json encode values and sign the cookie for security, something you have to manually do when using set_cookie.

from flask import session

session['my_key'] = 'my_value'
like image 75
davidism Avatar answered Sep 19 '22 12:09

davidism