Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask RESTFUL, creating a cookie from an endpoint (restful.Resource)

I'm currently working on creating a Cookie from an endpoint. As my backend and frontend only interacts via RESTful endpoints, is there anyway I can create a cookie when the frontend calls my backend's endpoint?

flask.make_response.set_cookie() doesn't seem to work for me. Also, I can't use app.route('/') to set my cookie either.

like image 302
max goh Avatar asked Feb 09 '17 05:02

max goh


2 Answers

You can do this with Set-Cookie header returning with a response.

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)


class HelloWorld(Resource):
    def get(self):
        return {'task': 'Hello world'}, 200, {'Set-Cookie': 'name=Nicholas'}

api.add_resource(HelloWorld, '/')

if __name__ == '__main__':
    app.run(debug=True)
like image 126
Piotr Dawidiuk Avatar answered Sep 27 '22 22:09

Piotr Dawidiuk


Setting the header in the response tuple is one of the standard approaches. However, keep in mind that the Set-Cookie header can be specified multiple times, which means that a python Dictionary won't be the most effective way to set the cookies in the response.

According to the flask docs the header object can also be initialized with a list of tuples, which might be more convenient in some cases.

Example:

from flask import Flask
from flask_restful import Api, Resource

app = Flask(__name__, static_url_path='')
api = Api(app)

class CookieHeaders(Resource):
    def get(self):
        # Will only set one cookie "age = 23"
        return { 'message' : 'Made with dict'}, 200, { 'Set-Cookie':'name=john', 'Set-Cookie':'age=23' }

    def post(self):
        # Will set both cookies "name = john" and "age = 23"
        headers = [ ('Set-Cookie', 'name=john'), ('Set-Cookie', 'age=23') ]
        return { 'message' : ' Made with a list of tuples'}, 200, headers

api.add_resource(CookieHeaders, '/')

if __name__ == '__main__':
    app.run(debug=True)

The GET call will only set 1 cookie (due to the lack of multi-key support in python dictionaries), but the POST call will set both.

like image 43
ivcuello Avatar answered Sep 27 '22 23:09

ivcuello