python - 使用 Tornado 通过 websocket 发送 cookie

标签 python tornado

我目前正在使用 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/

相关文章:

python - Skimage - 调整大小功能的奇怪结果

apache - 如何使用apache重定向到docker容器

documentation - 从 Tornado Web 服务器代码生成交互式 API 文档

python - 使用正则表达式在python中解析消息通知索引

python - 使用 numpy 读/写 Fortran 顺序数组的正确方法

python - 格式化tornado.access 的默认Python 日志记录

nginx - 在 Ubuntu 10.04 上使用 Nginx 设置 Tornado 以供生产使用

python - 从docker中的另一个容器连接到redis

python - 在 Google App Engine 上创建大量数据存储对象的最节省内存的方法是什么?

Python 类型错误 : unsupported operand type(s) for/: 'NoneType' and 'float'