这是我的代码
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客户端。当我获取请求时,我想用cookie发送它 该文档没有关于httpclient cookie的任何信息。 http://tornado.readthedocs.org/en/latest/httpclient.html
答案 0 :(得分:5)
您可以将Cookie放在headers
所需的fetch
关键字参数中。
客户端:
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
答案 1 :(得分:0)
https://pypi.python.org/pypi/tornado-httpclient-session 这是一个图书馆:
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