gpt4 book ai didi

python-3.x - 无法让 SSL 用于安全 Websocket 连接

转载 作者:太空宇宙 更新时间:2023-11-03 12:52:16 26 4
gpt4 key购买 nike

我是 Python 新手,但必须为工作构建 Websocket API。websockets 模块的网站说这段代码应该适用于安全的 websocket 连接(https://websockets.readthedocs.io/en/stable/intro.html)

但是,我无法使提供的代码正常工作。

import websockets
import asyncio
import pathlib
import ssl

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ssl_context.load_verify_locations(pathlib.Path(__file__).with_name('localhost.pem'))

我得到错误:

追溯(最近的调用最后):

文件“/Applications/Python 3.7/apii.py”,第 7 行,在模块中> ssl_context.load_verify_locations(pathlib.Path(__ file__).with_name('localhost.pem'))

FileNotFoundError: [Errno 2] 没有那个文件或目录

你能帮帮我吗?

附言。我根本不明白这个 ssl_context 代码。有人可以解释一下它背后的逻辑吗?

最佳答案

我从 docker 容器中测试 websockets。我有 NAT ips(不能使用 LetsEncrypt),但没有 * 域证书。如果我直接在 Firefox 中测试,它可以在没有任何证书的情况下正常工作。因此,应该允许出于测试目的在防火墙内禁用 SSL。

摘录:

import asyncio
import websockets
import ssl
:
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE

async def logIn(uri, myjson):
async with websockets.connect(uri) as websocket:
await websocket.send(myjson)

async def logIn(uri, myjson):
async with websockets.connect(uri, ssl=ssl_context) as websocket:
await websocket.send(myjson)
resp = await websocket.recv()
print(resp)

myurl = f"wss://{args.server}:{args.port}"
print("connection url:{}".format(myurl))

# logdef is the json string I send in
asyncio.get_event_loop().run_until_complete(
logIn(myurl, logdef)
)

关于python-3.x - 无法让 SSL 用于安全 Websocket 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52068442/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com