Update README example to async code (#331)

This commit is contained in:
Lasse Blaauwbroek
2023-10-12 16:13:27 +02:00
committed by GitHub
parent 941f018092
commit ae965128de

View File

@@ -174,6 +174,7 @@ if __name__ == '__main__':
Also, pycapnp has gained RPC features that include pipelining and a promise style API. Refer to the calculator example in the examples directory for a much better demonstration: Also, pycapnp has gained RPC features that include pipelining and a promise style API. Refer to the calculator example in the examples directory for a much better demonstration:
```python ```python
import asyncio
import capnp import capnp
import socket import socket
@@ -185,31 +186,33 @@ class Server(test_capability_capnp.TestInterface.Server):
def __init__(self, val=1): def __init__(self, val=1):
self.val = val self.val = val
def foo(self, i, j, **kwargs): async def foo(self, i, j, **kwargs):
return str(i * 5 + self.val) return str(i * 5 + self.val)
def server(write_end): async def client(read_end):
server = capnp.TwoPartyServer(write_end, bootstrap=Server(100))
def client(read_end):
client = capnp.TwoPartyClient(read_end) client = capnp.TwoPartyClient(read_end)
cap = client.bootstrap() cap = client.bootstrap()
cap = cap.cast_as(test_capability_capnp.TestInterface) cap = cap.cast_as(test_capability_capnp.TestInterface)
remote = cap.foo(i=5) remote = cap.foo(i=5)
response = remote.wait() response = await remote
assert response.x == '125' assert response.x == '125'
async def main():
if __name__ == '__main__': client_end, server_end = socket.socketpair(socket.AF_UNIX)
read_end, write_end = socket.socketpair(socket.AF_UNIX)
# This is a toy example using socketpair. # This is a toy example using socketpair.
# In real situations, you can use any socket. # In real situations, you can use any socket.
server(write_end) client_end = await capnp.AsyncIoStream.create_connection(sock=client_end)
client(read_end) server_end = await capnp.AsyncIoStream.create_connection(sock=server_end)
_ = capnp.TwoPartyServer(server_end, bootstrap=Server(100))
await client(client_end)
if __name__ == '__main__':
asyncio.run(capnp.run(main()))
``` ```