Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update README example to async code #331

Merged
merged 1 commit into from
Oct 12, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 15 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

```python
import asyncio
import capnp
import socket

Expand All @@ -185,31 +186,33 @@ class Server(test_capability_capnp.TestInterface.Server):
def __init__(self, val=1):
self.val = val

def foo(self, i, j, **kwargs):
async def foo(self, i, j, **kwargs):
return str(i * 5 + self.val)


def server(write_end):
server = capnp.TwoPartyServer(write_end, bootstrap=Server(100))


def client(read_end):
async def client(read_end):
client = capnp.TwoPartyClient(read_end)

cap = client.bootstrap()
cap = cap.cast_as(test_capability_capnp.TestInterface)

remote = cap.foo(i=5)
response = remote.wait()
response = await remote

assert response.x == '125'


if __name__ == '__main__':
read_end, write_end = socket.socketpair(socket.AF_UNIX)
async def main():
client_end, server_end = socket.socketpair(socket.AF_UNIX)
# This is a toy example using socketpair.
# In real situations, you can use any socket.

server(write_end)
client(read_end)
client_end = await capnp.AsyncIoStream.create_connection(sock=client_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()))
```
Loading