gpt4 book ai didi

python - asyncio python 3.6 代码到 asyncio python 3.4 代码

转载 作者:太空宇宙 更新时间:2023-11-03 14:49:17 27 4
gpt4 key购买 nike

我有这个 3.6 异步代码:

async def send(command,userPath,token):
async with websockets.connect('wss://127.0.0.1:7000',ssl=ssl.SSLContext(protocol=ssl.PROTOCOL_TLS)) as websocket:
data = json.dumps({"api_command":"session","body":command,"headers": {'X-User-Path': userPath, 'X-User-Token': token}})
await websocket.send(data)
response = await websocket.recv()
response = json.loads(response)
if 'command' in response:
if response['command'] == 'ACK_COMMAND' or response['command'] == 'ACK_INITIALIZATION':
return (response['message'],200)
else:
return(response,400)

我将其转换为 3.4 异步代码

@asyncio.coroutine
def send(command,userPath,token):
with websockets.connect('wss://127.0.0.1:7000',ssl=ssl.SSLContext(protocol=ssl.PROTOCOL_TLS)) as websocket:
data = json.dumps({"api_command":"session","body":command,"headers": {'X-User-Path': userPath, 'X-User-Token': token}})
yield from websocket.send(data)
response = yield from websocket.recv()
response = json.loads(response)
if 'command' in response:
if response['command'] == 'ACK_COMMAND' or response['command'] == 'ACK_INITIALIZATION':
return (response['message'],200)
else:
return(response,400)

虽然解释器运行转换,但当我调用该函数时,会发生此错误:

with websockets.connect('wss://127.0.0.1:7000',ssl=ssl.SSLContext(protocol=ssl.PROTOCOL_TLS)) as websocket:
AttributeError: __enter__

我觉得还有更多的东西需要转换,但我不知道是什么。如何使 3.4 代码工作?

注意:我使用 3.6 python 运行 3.4 代码

最佳答案

可以找到here 与 websockets.connect 异步 你应该这样做:

websocket = yield from websockets.connect('ws://localhost:8765/')
try:
# your stuff
finally:
yield from websocket.close()

在你的情况下,它是:

@asyncio.coroutine
def send(command,userPath,token):
websocket = yield from websockets.connect('wss://127.0.0.1:7000',ssl=ssl.SSLContext(protocol=ssl.PROTOCOL_TLS))
try:
data = json.dumps({"api_command":"session","body":command,"headers": {'X-User-Path': userPath, 'X-User-Token': token}})
yield from websocket.send(data)
response = yield from websocket.recv()
response = json.loads(response)
if 'command' in response:
if response['command'] == 'ACK_COMMAND' or response['command'] == 'ACK_INITIALIZATION':
return (response['message'],200)
else:
return(response,400)
finally:
yield from websocket.close()

关于python - asyncio python 3.6 代码到 asyncio python 3.4 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45999766/

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