我有这个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代码
最佳答案
如async with websockets.connect
的here所示,您应该执行以下操作:
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()