如何向Tornado HttpClient添加Cookie

6 投票
2 回答
5627 浏览
提问于 2025-04-18 09:34

这是我的代码

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()

我想使用异步的HTTP客户端。当我发送请求的时候,我希望能带上cookies。
但是文档里没有关于httpclient cookies的内容。http://tornado.readthedocs.org/en/latest/httpclient.html

2 个回答

0

这是一个专门用来做这个的库:

from tornado.httpclient import HTTPClient

from httpclient_session import Session

s = Session(HTTPClient) # AsyncHTTPClient default

r = s.fetch('https://github.com')
print(r.headers['set-cookie']) # Inspect cookies returnd from Github

r = s.fetch('https://github.com') # Fetching carrys cookies
print(r.request.headers['cookie']) # Inspect cookies attached
6

你可以把 cookie 放在 fetch 函数的 headers 这个参数里。

客户端:

import tornado.httpclient

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

服务器:

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()

如果你先运行服务器,然后再运行客户端,服务器会输出以下内容:

got cookie heyhey

撰写回答