Reputation: 172
What is the correct method / syntax for adding headers to a websocket connection request using Python Websockets ?
The server I'm trying to connect to requires headers in the connection request for authentication
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:
Similar question was asked here but did not answer the core of the question: How to send 'Headers' in websocket python
Upvotes: 3
Views: 12498
Reputation: 61
In more recent versions the library's api changed and now they use the argument additional_headers
to add new headers:
async def connect():
async with websockets.connect("wss://site.com/ws", additional_headers=headers) as websocket:
response = await websocket.recv()
print(response)
Reference: https://websockets.readthedocs.io/en/stable/reference/asyncio/client.html#opening-a-connection
Upvotes: 2
Reputation: 126
According to documentation, you can pass headers in extra_headers
param of connect()
function. Details here.
So code should look something like this:
async def connect():
async with websockets.connect("wss://site.com/ws", extra_headers=headers) as websocket:
response = await websocket.recv()
print(response)
Upvotes: 11
Reputation: 1
First create a websocket using websockets.connect
.
Then send the JSON header in websocket.send(header)
And then start processing the responses.
This should work:
async def connect():
async with websockets.connect("wss://site.com/ws") as websocket:
await websocket.send(header)
response = await websocket.recv()
print(response)
Upvotes: -3