【发布时间】:2018-02-10 11:46:54
【问题描述】:
我有这个 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不能被普通的with替换。另见stackoverflow.com/questions/37465816/async-with-in-python-3-4
标签: python python-asyncio