在来自 Python 客户端的 Websockets 连接请求中发送 headers
Send headers in Websockets connection request from Python client
使用 Python Websockets 添加 headers 到 websocket 连接请求的正确方法/语法是什么?
我尝试连接的服务器要求 headers 在连接请求中进行身份验证
async def connect():
async with websockets.connect("wss://site.com/ws") as websocket:
response = await websocket.recv()
print(response)
# eg. does not work:
async with websockets.connect(f"wss://site.com/ws, header={headers}") as websocket:
async with websockets.connect(f"wss://site.com/ws, extra_headers:{headers}") as websocket:
这里问了类似的问题但没有回答问题的核心:
首先使用websockets.connect
创建一个websocket。
然后在websocket.send(header)
中发送JSONheader
然后开始处理响应。
这应该有效:
async def connect():
async with websockets.connect("wss://site.com/ws") as websocket:
await websocket.send(header)
response = await websocket.recv()
print(response)
根据文档,您可以在 connect()
函数的 extra_headers
参数中传递 headers。详情:https://websockets.readthedocs.io/en/stable/reference/client.html
所以代码应该是这样的:
async def connect():
async with websockets.connect("wss://site.com/ws", extra_headers=headers) as websocket:
response = await websocket.recv()
print(response)
使用 Python Websockets 添加 headers 到 websocket 连接请求的正确方法/语法是什么?
我尝试连接的服务器要求 headers 在连接请求中进行身份验证
async def connect():
async with websockets.connect("wss://site.com/ws") as websocket:
response = await websocket.recv()
print(response)
# eg. does not work:
async with websockets.connect(f"wss://site.com/ws, header={headers}") as websocket:
async with websockets.connect(f"wss://site.com/ws, extra_headers:{headers}") as websocket:
这里问了类似的问题但没有回答问题的核心:
首先使用websockets.connect
创建一个websocket。
然后在websocket.send(header)
中发送JSONheader
然后开始处理响应。
这应该有效:
async def connect():
async with websockets.connect("wss://site.com/ws") as websocket:
await websocket.send(header)
response = await websocket.recv()
print(response)
根据文档,您可以在 connect()
函数的 extra_headers
参数中传递 headers。详情:https://websockets.readthedocs.io/en/stable/reference/client.html
所以代码应该是这样的:
async def connect():
async with websockets.connect("wss://site.com/ws", extra_headers=headers) as websocket:
response = await websocket.recv()
print(response)