Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add cookies to tornado httpclient

Tags:

python

tornado

Here is my code

class MainHandler(tornado.web.RequestHandler):

    @tornado.web.asynchronous
    def get(self):
        http_client = tornado.httpclient.AsyncHTTPClient()
        http_client.fetch("http://www.example.com",
                          callback=self.on_fetch)

    def on_fetch(self, response):
        self.write('hello')
        self.finish()

I want to use asynchronous HTTP client. When I fetch the request, I want to send it with the cookies.
The Document has nothing about httpclient cookies. http://tornado.readthedocs.org/en/latest/httpclient.html

like image 607
alexis Avatar asked Jun 12 '14 16:06

alexis


1 Answers

You can put the cookie in the headers keyword argument that fetch takes.

client:

import tornado.httpclient

http_client = tornado.httpclient.HTTPClient()
cookie = {"Cookie" : 'my_cookie=heyhey'}
http_client.fetch("http://localhost:8888/cook",
                  headers=cookie)

server:

from tornado.ioloop import IOLoop
import tornado.web

class CookHandler(tornado.web.RequestHandler):
    def get(self):
        cookie = self.get_cookie("my_cookie")
        print "got cookie %s" % (cookie,)


if __name__ == "__main__":
    app = tornado.web.Application([
        (r"/cook", CookHandler),
    ])

    app.listen(8888)
    IOLoop.instance().start()

If you run the server, followed by the client, the server will output this:

got cookie heyhey
like image 67
dano Avatar answered Sep 19 '22 04:09

dano