我目前正在使用 Tornado 连接到 websocket,有没有办法可以通过 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)
谢谢!
最佳答案
websocket_connect(url)
中的 url
参数可以是纯 URL 字符串,但也可以是 tornado.httpclient.HTTPRequest
目的。虽然没有记录,但您可以在 source code 中看到这一点.
因此,您可以创建一个 HTTPRequest
实例并在那里设置 Cookie header ,毕竟 cookie 只是一个 header 。
示例:
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)
关于python - 使用 Tornado 通过 websocket 发送 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47343413/