move from python-opcua to opcua-asyncio

Viewed 454

Now I have a package with a class that looks like this:

class Opc(object):
    def __init__(self):
         client = Client("server_url")
         client.connect()

opc = Opc()

Now I want to use the opcua-asyncio library, so I need to use an async function to connect to the server, but I can't await it from init. How can I connect to the server, using the async connect function, after my package is imported?

2 Answers

There are multiple solutions:

  1. using a classmethod:
    class Opc:
        @classmethod
        async def create(cls):
            self = Opc()
            self.client = Client("server_url")
            await self.client.connect()
    
    opc = await Opc.create()
  1. using an async context manager:
     class Opc:
            def __init__(self) -> None:
                self.client = Client("server_url")
        
            async def __aenter__(self):
                await self.client.connect()
        
            async def __aexit__(self, exc_type, exc, tb):
                await self.client.disconnect()
    
     opc = Opc()
     async with opc:
         ...

Now I want to use the opcua-asyncio library, so I need to use an async function to connect to the server,

opcua-async has sync wrappers so you can just keep the exact same code: https://github.com/FreeOpcUa/opcua-asyncio/blob/master/asyncua/sync.py

https://github.com/FreeOpcUa/opcua-asyncio/blob/master/examples/sync/client-minimal.py

Now if you want to port to async code you can do as in https://stackoverflow.com/a/70631847/2033030

or add a connect method

    class Opc:
        def __init__(self):
            self.client = Client("server_url")
 
        async def connect(self):
            await self.client.connect()
    
    opc = Opc()
    await opc.connect()

Related