a.beno
a.beno

Reputation: 1

Set cookie at make_response()

I'm using flask restful api in python and I would like to send a cookie. in make_response method that looks like that, for example:

return make_response(jsonify(objects_list[0]), 200)

Is it possible to do?

the response is sent back from post def, and the def of making a cookie is in the same class.

This is the set cookie def:

def setcookie(self, userid, code):
    check = str(userid) + code
    resp = make_response('setting cookie')
    resp.set_cookie('cook', check)
    return resp

How can it be done?

Upvotes: 0

Views: 2004

Answers (2)

user3418812
user3418812

Reputation: 33

In case anyone is still looking for a solution to this, I just recently solved mine to support most of the browsers (IE, Chrome, Firefox, etc.)

This is with Flask RESTFul API, let say from a resource perspective:

use these with your imports:

from flask import request, current_app, after_this_request

then on your implementation, example:

class Search(Resource):
      global_cookie_value = None 

      def get(self, variable):
          ....
          global_cookie_value = 1234
          ....

          @after_this_request
          def set_cookie_value(response):
              response.set_cookie('cookie_name', str(global_cookie_value), max_age=44, httponly=True)
              return response        

          return {'message': 'success'} , 200 

In this way, the cookie is set after the processing of the request.

Upvotes: 2

Alex
Alex

Reputation: 2174

Here is an official Flask documentation link describing how to use cookies.

Upvotes: 0

Related Questions