1

I have this 3.6 async code:

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)

which I converted to this 3.4 async code

@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)

Although the interpreter runs the conversion, when I call the function this error occurs:

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

I feel like there is more stuff to convert, but I don't know what. How can I make the 3.4 code work?

Note: I run the 3.4 code with a 3.6 python

Tasos
  • 1,575
  • 5
  • 18
  • 44
  • 1
    `async with` cannot be replaced by plain `with`. See also https://stackoverflow.com/questions/37465816/async-with-in-python-3-4 – VPfB Sep 01 '17 at 12:11

1 Answers1

1

As can be found here of async with websockets.connect you should do:

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

In your case it would be:

@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()
Mikhail Gerasimov
  • 36,989
  • 16
  • 116
  • 159