使用Tornado使用websockets发送cookie

时间:2017-11-17 04:42:13

标签: python tornado

我目前使用龙卷风连接到websockets,有没有办法可以通过websocket连接传递cookie?

import logging

import tornado.httpclient
import tornado.gen
import tornado.options
import tornado.web
import tornado.websocket

@tornado.gen.coroutine
def connect_websocket():

    url = tornado.options.options.ws_host

    try:
        ws_connection = yield tornado.websocket.websocket_connect(url, connect_timeout=5)
        logging.info("Connection established (%s), waiting for output...", url)
    except Exception as conn_err:
        logging.error("Error connecting to %s", conn_err)
        return

    while True:
        output = yield ws_connection.read_message()
        logging.info(output)


if __name__ == '__main__':
    tornado.options.define(name="ws_host", type=str, help="Websocket host address.")
    tornado.options.parse_command_line()

    tornado.ioloop.IOLoop.instance().run_sync(connect_websocket)

谢谢!

1 个答案:

答案 0 :(得分:1)

url中的websocket_connect(url)参数可以是普通的URL字符串,但也可以是tornado.httpclient.HTTPRequest个对象。虽然,它没有记录,但你可以在source code中看到这一点。

因此,您可以创建HTTPRequest的实例并在那里设置Cookie标头,毕竟,cookie只是一个标题。

示例:

from tornado import httpclient

# create an instace of HTTPRequest with the given url
request = httpclient.HTTPRequest(url, headers={'Cookie': 'name=value'})

# connect to ws using the request object
ws_connection = yield tornado.websocket.websocket_connect(request)