簡體   English   中英

從 Python 客戶端發送 Websockets 連接請求中的標頭

[英]Send headers in Websockets connection request from Python client

使用Python Websockets將標頭添加到 websocket 連接請求的正確方法/語法是什么?

我嘗試連接的服務器需要連接請求中的標頭以進行身份驗證

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:

此處提出了類似的問題,但沒有回答問題的核心: How to send 'Headers' in websocket python

首先使用websockets.connect創建一個 websocket 。
然后在websocket.send(header)中發送 JSON header
然后開始處理響應。

這應該有效:

async def connect():
    async with websockets.connect("wss://site.com/ws") as websocket:
        await websocket.send(header)
        response = await websocket.recv()
        print(response)

根據文檔,您可以在connect() function 的extra_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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM