### Clone pycapnp and install from source Source: https://github.com/capnproto/pycapnp/blob/master/README.md Clone the pycapnp repository and install it using pip. By default, this will use a locally installed Cap'n Proto or bundle it if not found. ```bash git clone https://github.com/capnproto/pycapnp.git cd pycapnp pip install . ``` -------------------------------- ### Install Benchmark Dependencies Source: https://github.com/capnproto/pycapnp/blob/master/benchmark/bin/README.md Installs necessary Python packages for running benchmarks, particularly if profiling against protobufs. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install pycapnp from Local Source Source: https://github.com/capnproto/pycapnp/blob/master/docs/install.rst Installs pycapnp after cloning the repository and navigating into the directory. This is typically used for development builds. ```bash cd pycapnp pip install . ``` -------------------------------- ### Install pycapnp with Pip Source: https://github.com/capnproto/pycapnp/blob/master/docs/install.rst Standard installation of pycapnp using pip. This will use pre-compiled binary versions if available. ```bash pip install pycapnp ``` -------------------------------- ### Create pycapnp Asyncio Server with SSL/TLS Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Setup an SSL context and pass it to create_server for secure communication. Ensure the certificate and key files are correctly specified. ```python # Setup SSL context ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ctx.load_cert_chain( os.path.join(this_dir, "selfsigned.cert"), os.path.join(this_dir, "selfsigned.key"), ) server = await capnp.AsyncIoStream.create_server( new_connection, host, port, ssl=ctx, family=socket.AF_INET ) ``` -------------------------------- ### Implement Calculator Server Methods Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Example implementation of a Calculator server interface. Methods can either match the interface exactly or have '_context' appended. Use `**kwargs` for future compatibility. ```python class CalculatorImpl(calculator_capnp.Calculator.Server): """Implementation of the Calculator Cap'n Proto interface.""" def evaluate(self, expression, _context, **kwargs): return evaluate_impl(expression).then(lambda value: setattr(_context.results, 'value', ValueImpl(value))) def defFunction_context(self, context): params = context.params context.results.func = FunctionImpl(params.paramCount, params.body) def getOperator(self, op, **kwargs): return OperatorImpl(op) ``` -------------------------------- ### Run pycapnp Asyncio Server Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Main function to start the pycapnp asyncio server, bind it to a host and port, and keep it running. ```python async def main(): host = 'localhost' port = '6000' server = await capnp.AsyncIoStream.create_server(new_connection, host, port) async with server: await server.serve_forever() if __name__ == "__main__": asyncio.run(capnp.run(main())) ``` -------------------------------- ### Install pycapnp enforcing system libcapnp Source: https://github.com/capnproto/pycapnp/blob/master/README.md Install pycapnp using pip, forcing the use of the Cap'n Proto library installed on the system. Ensure that the system-installed Cap'n Proto meets the version requirements. ```bash pip install . -C force-system-libcapnp=True ``` -------------------------------- ### Install Python Dependencies for Development Source: https://github.com/capnproto/pycapnp/blob/master/docs/install.rst Installs Python dependencies required for development using either pipenv or a requirements file. ```bash pipenv install ``` ```bash pip install -r requirements.txt ``` -------------------------------- ### Install pycapnp with pip Source: https://github.com/capnproto/pycapnp/blob/master/README.md Install pycapnp using pip. You can specify the C++ compiler using the CC environment variable. ```bash pip install pycapnp ``` ```bash CC=gcc-8.2 pip install pycapnp ``` -------------------------------- ### Install pycapnp with latest upstream libcapnp Source: https://github.com/capnproto/pycapnp/blob/master/README.md Install pycapnp using pip, forcing the use of the bundled Cap'n Proto library and specifying the URL for the latest upstream source. ```bash pip install . \ -C force-bundled-libcapnp=True \ -C libcapnp-url="https://github.com/capnproto/capnproto/archive/master.tar.gz" ``` -------------------------------- ### RPC with Pipelining and Promises in pycapnp Source: https://github.com/capnproto/pycapnp/blob/master/README.md Illustrates pycapnp's RPC features, including pipelining and a promise-style API, using a calculator example. Requires 'test_capability_capnp' schema. ```python import asyncio import capnp import socket import test_capability_capnp class Server(test_capability_capnp.TestInterface.Server): def __init__(self, val=1): self.val = val async def foo(self, i, j, **kwargs): return str(i * 5 + self.val) 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 = await remote assert response.x == '125' 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. 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())) ``` -------------------------------- ### Run pycapnp Tests with Pipenv Source: https://github.com/capnproto/pycapnp/blob/master/README.md Use this command to install dependencies and run tests within a Pipenv environment. Ensure Pipenv is installed first. ```bash pip install pipenv pipenv install pipenv run pytest ``` -------------------------------- ### Install pycapnp enforcing bundled libcapnp Source: https://github.com/capnproto/pycapnp/blob/master/README.md Install pycapnp using pip, forcing the use of the bundled Cap'n Proto library. This is useful if you want to ensure a specific version of Cap'n Proto is used. ```bash pip install . -C force-bundled-libcapnp=True ``` -------------------------------- ### Force pycapnp Pip Installation from Source Source: https://github.com/capnproto/pycapnp/blob/master/docs/install.rst Forces pip to build the pycapnp package from source, ignoring any available binary wheels. Useful for development or when binary wheels are not compatible. ```bash pip install --no-binary :all: pycapnp ``` -------------------------------- ### Install pycapnp on Older Linux with LDFLAGS Source: https://github.com/capnproto/pycapnp/blob/master/docs/install.rst For older Linux distributions, you may need to set specific LDFLAGS to ensure proper linking. This command forces a source build. ```bash LDFLAGS="-Wl,--no-as-needed -lrt" pip install --no-binary :all: pycapnp ``` -------------------------------- ### Run Asyncio Coroutine with kj_loop Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Executes an asyncio coroutine within the capnp.kj_loop context. This is the basic setup for running capnp RPC operations. ```python import capnp import asyncio async def main(): async with capnp.kj_loop(): # RPC calls here asyncio.run(main()) ``` -------------------------------- ### Cap'n Proto Schema Definition Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Example of a Cap'n Proto schema definition for an address book, including Person and AddressBook structures. ```capnp # addressbook.capnp @0x934efea7f017fff0; const qux :UInt32 = 123; struct Person { id @0 :UInt32; name @1 :Text; email @2 :Text; phones @3 :List(PhoneNumber); struct PhoneNumber { number @0 :Text; type @1 :Type; enum Type { mobile @0; home @1; work @2; } } employment :union { unemployed @4 :Void; employer @5 :Text; school @6 :Text; selfEmployed @7 :Void; # We assume that a person is only one of these. } } struct AddressBook { people @0 :List(Person); } ``` -------------------------------- ### Run All Benchmarks Source: https://github.com/capnproto/pycapnp/blob/master/benchmark/bin/README.md Executes all available benchmarks. Use the -l flag to specify the language implementations to test, such as 'pyproto' and 'pyproto_cpp'. ```bash ./run_all -l pyproto -l pyproto_cpp ``` -------------------------------- ### Clean Build Artifacts with setup.py Source: https://github.com/capnproto/pycapnp/blob/master/docs/install.rst Removes compiled files and other build artifacts generated by setup.py. Useful before rebuilding the package. ```bash python setup.py clean ``` -------------------------------- ### Establish Asyncio Client Connection Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Connects to a server at a specified host and port using capnp.AsyncIoStream.create_connection. This is a wrapper around asyncio.get_running_loop().create_connection() that adds Protocol handling. ```python async def main(): host = 'localhost' port = '6000' connection = await capnp.AsyncIoStream.create_connection(host=host, port=port) asyncio.run(capnp.run(main())) ``` -------------------------------- ### Write and Print Address Book with pycapnp Source: https://github.com/capnproto/pycapnp/blob/master/README.md Demonstrates how to define, write, and read a Cap'n Proto schema using pycapnp. Ensure the 'addressbook_capnp' schema is defined and imported. ```python import os import capnp import addressbook_capnp def writeAddressBook(file): addresses = addressbook_capnp.AddressBook.new_message() people = addresses.init('people', 2) alice = people[0] alice.id = 123 alice.name = 'Alice' alice.email = 'alice@example.com' alicePhones = alice.init('phones', 1) alicePhones[0].number = "555-1212" alicePhones[0].type = 'mobile' alice.employment.school = "MIT" bob = people[1] bob.id = 456 bob.name = 'Bob' bob.email = 'bob@example.com' bobPhones = bob.init('phones', 2) bobPhones[0].number = "555-4567" bobPhones[0].type = 'home' bobPhones[1].number = "555-7654" bobPhones[1].type = 'work' bob.employment.unemployed = None addresses.write(file) def printAddressBook(file): addresses = addressbook_capnp.AddressBook.read(file) for person in addresses.people: print(person.name, ':', person.email) for phone in person.phones: print(phone.type, ':', phone.number) which = person.employment.which() print(which) if which == 'unemployed': print('unemployed') elif which == 'employer': print('employer:', person.employment.employer) elif which == 'school': print('student at:', person.employment.school) elif which == 'selfEmployed': print('self employed') print() if __name__ == '__main__': f = open('example', 'w') writeAddressBook(f) f = open('example', 'r') printAddressBook(f) ``` -------------------------------- ### Create Asyncio Server with capnp Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Creates an asyncio server using capnp.AsyncIoStream.create_server. This function forwards arguments to the underlying asyncio create_server function. ```python # Server setup code would go here, using capnp.AsyncIoStream.create_server ``` -------------------------------- ### Create pycapnp Asyncio Server Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Callback for new connections to a pycapnp server. It should create a TwoPartyServer instance and handle disconnects. ```python async def new_connection(stream): await capnp.TwoPartyServer(stream, bootstrap=CalculatorImpl()).on_disconnect() ``` -------------------------------- ### Import pycapnp Library Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Import the pycapnp library to begin using its functionalities. ```python import capnp ``` -------------------------------- ### Specify libcapnp URL for Bundling Source: https://github.com/capnproto/pycapnp/blob/master/docs/install.rst Allows specifying a custom URL for downloading libcapnp when building from source. Use with caution as compatibility is not guaranteed. ```bash pip install --no-binary :all: -C force-bundled-libcapnp=True -C libcapnp-url="https://github.com/capnproto/capnproto/archive/master.tar.gz" ``` -------------------------------- ### Load Cap'n Proto Schema Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Load a Cap'n Proto schema file. This can be done automatically via import or manually. ```python import addressbook_capnp ``` ```python capnp.remove_import_hook() addressbook_capnp = capnp.load('addressbook.capnp') ``` -------------------------------- ### Importing and Printing Struct Module Type Source: https://github.com/capnproto/pycapnp/blob/master/docs/capnp.rst Demonstrates how to import a Cap'n Proto schema file and print the type of a generated struct module. This is useful for understanding the structure of generated code. ```python import capnp import addressbook_capnp print type(addressbook_capnp.Person) # capnp.capnp._StructModule ``` -------------------------------- ### Release pycapnp to PyPI Source: https://github.com/capnproto/pycapnp/blob/master/README.md Steps to tag a new release, push it to origin, and then use the release script to upload artifacts to PyPI. This process relies on GitHub Actions for building wheels and the 'release-pypi.sh' script for uploading. ```bash git tag v2.2.1 git push origin v2.2.1 # wait for the "Build" workflow run to finish successfully on GitHub # Download artifacts and upload to PyPI (creates dist_221/ by default). scripts/release-pypi.sh v2.2.1 # Or, target a specific Actions run id: scripts/release-pypi.sh 1234567890 # Dry run: upload to TestPyPI (https://test.pypi.org) instead of real PyPI. # Useful for validating the release flow end-to-end before pushing to # production. Requires a TestPyPI account + API token configured in # ~/.pypirc under a [testpypi] section. See # https://packaging.python.org/en/latest/guides/using-testpypi/ . scripts/release-pypi.sh v2.2.1 --test ``` -------------------------------- ### Simplified Asyncio Coroutine Execution with capnp.run Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Uses the capnp.run helper function to execute an asyncio coroutine within the capnp.kj_loop context, simplifying the boilerplate. ```python import capnp import asyncio async def main(): # RPC calls here asyncio.run(capnp.run(main())) ``` -------------------------------- ### Initialize New Cap'n Proto Message Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Create a new Cap'n Proto message object from a schema. Keyword arguments can be used to set initial fields. ```python addresses = addressbook_capnp.AddressBook.new_message() ``` ```python person = addressbook_capnp.Person.new_message(name='alice') # is equivalent to: person = addressbook_capnp.Person.new_message() person.name = 'alice' ``` -------------------------------- ### Create TwoPartyClient Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Creates a TwoPartyClient object by passing the established connection. This client is used to interact with the server's capabilities. ```python async def main(): host = 'localhost' port = '6000' connection = await capnp.AsyncIoStream.create_connection(host=host, port=port) client = capnp.TwoPartyClient(connection) ## Bootstrap Here ## asyncio.run(capnp.run(main())) ``` -------------------------------- ### Create Message with Nested Lists/Dicts Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Demonstrates creating a Cap'n Proto message with nested Python lists and dictionaries, which are automatically converted to their Cap'n Proto equivalents. ```python book = addressbook_capnp.AddressBook.new_message(people=[{'name': 'Alice'}]) ... book = addressbook_capnp.AddressBook.new_message() book.init('people', 1) book.people[0] = {'name': 'Bob'} ``` -------------------------------- ### Write Message to File Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Serialize a Cap'n Proto message and write it to a binary file. Ensure the file is opened in binary write mode ('wb'). ```python with open('example.bin', 'wb') as f: addresses.write(f) ``` -------------------------------- ### Initialize Asyncio Client for Python 3.8 Bug Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst A workaround for a bug in Python 3.8 asyncio that requires a slightly different initialization method for the client. ```python if __name__ == '__main__': loop = asyncio.new_event_loop() loop.run_until_complete(capnp.run(main(parse_args().host))) ``` -------------------------------- ### Utility Functions Source: https://github.com/capnproto/pycapnp/blob/master/docs/capnp.rst Functions for managing import hooks and global schema parsers. ```APIDOC ## add_import_hook ### Description Adds a hook to the import system for Cap'n Proto modules. ### Function `capnp.add_import_hook` ``` ```APIDOC ## remove_import_hook ### Description Removes a hook from the import system for Cap'n Proto modules. ### Function `capnp.remove_import_hook` ``` ```APIDOC ## cleanup_global_schema_parser ### Description Cleans up the global schema parser instance. ### Function `capnp.cleanup_global_schema_parser` ``` ```APIDOC ## kj_loop ### Description Runs the underlying KJ event loop. ### Function `capnp.kj_loop` ``` ```APIDOC ## run ### Description Runs a Cap'n Proto application or event loop. ### Function `capnp.run` ``` ```APIDOC ## load ### Description Loads a Cap'n Proto schema or module. ### Function `capnp.load` ``` -------------------------------- ### Verbose RPC Method Call with capnp Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Initiates an RPC method call using the 'request' syntax. This involves creating a request object, setting parameters, and sending the request, returning a promise. ```python request = calculator.evaluate_request() request.expression.literal = 123 eval_promise = request.send() ``` -------------------------------- ### Interface Method Return Handling Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Demonstrates how return values are handled in pycapnp server implementations. Returning a promise is handled automatically. Other return values populate the results struct. ```python # capability.capnp file interface TestInterface { foo @0 (i :UInt32, j :Bool) -> (x: Text, i:UInt32); } # python code class TestInterface(capability_capnp.TestInterface.Server): def foo(self, i, j, **kwargs): return str(j), i ``` -------------------------------- ### Write Multiple Messages to File Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Writes multiple Cap'n Proto messages sequentially to a binary file. ```python addresses = addressbook_capnp.AddressBook.new_message() ... with open('example.bin', 'wb') as f: addresses.write(f) addresses.write(f) addresses.write(f) # write 3 messages ``` -------------------------------- ### Force Bundled or System libcapnp with Pip Source: https://github.com/capnproto/pycapnp/blob/master/docs/install.rst Control whether pip bundles libcapnp or uses a system-installed version. Use `--no-binary :all:` to ensure the build process respects these flags. ```bash pip install --no-binary :all: -C force-bundled-libcapnp=True ``` ```bash pip install --no-binary :all: -C force-system-libcapnp=True ``` -------------------------------- ### Bootstrap Server Capability Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Retrieves and casts the server's bootstrap capability. Casting is necessary because capabilities are dynamic and lack runtime type information. ```python calculator = client.bootstrap().cast_as(calculator_capnp.Calculator) ``` -------------------------------- ### Build Python Wheel Distribution Source: https://github.com/capnproto/pycapnp/blob/master/README.md Command to build a Python wheel distribution for the pycapnp package. This is useful for creating distributable packages. ```bash pip wheel . ``` -------------------------------- ### Initialize List Field Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Initialize a list field within a Cap'n Proto message using the 'init' function. Avoid calling 'init' more than once on the same field. ```python people = addresses.init('people', 2) alice = people[0] ``` -------------------------------- ### Miscellaneous Classes Source: https://github.com/capnproto/pycapnp/blob/master/docs/capnp.rst Utility classes for exceptions, schema parsing, and loading. ```APIDOC ## KjException ### Description Represents exceptions originating from the underlying KJ library. ### Class `capnp.KjException` ### Members Includes all public and inherited members. ``` ```APIDOC ## SchemaParser ### Description Provides functionality for parsing Cap'n Proto schema files. ### Class `capnp.SchemaParser` ### Members Includes all public and inherited members. ``` ```APIDOC ## SchemaLoader ### Description Provides functionality for loading Cap'n Proto schemas. ### Class `capnp.SchemaLoader` ### Members Includes all public and inherited members. ``` -------------------------------- ### Use KJ Event Loop for RPC Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Ensures proper creation, usage, and cleanup of the KJ event loop for RPC calls by using the capnp.kj_loop context manager. All RPC calls must be made within this context. ```python # All RPC calls must be made within this context:: # with capnp.kj_loop(): # # RPC calls here ``` -------------------------------- ### Write Message to File (Packed) Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Write a Cap'n Proto message to a file in a space-efficient packed format. Use `read_packed` to deserialize. ```python with open('example.bin', 'wb') as f: addresses.write_packed(f) ``` -------------------------------- ### Read Message from File Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Deserialize a Cap'n Proto message from a binary file. The file must have been written using `write()` or `write_packed()`. ```python with open('example.bin', 'rb') as f: addresses = addressbook_capnp.AddressBook.read(f) ``` -------------------------------- ### Internal Builder Classes Source: https://github.com/capnproto/pycapnp/blob/master/docs/capnp.rst Internal classes for building Cap'n Proto data structures. ```APIDOC ## Dynamic Resizable List Builder ### Description Internal class for building dynamic resizable lists. ### Class `capnp.lib.capnp._DynamicResizableListBuilder` ### Members Includes all public and inherited members. ``` ```APIDOC ## Dynamic List Builder ### Description Internal class for building dynamic lists. ### Class `capnp.lib.capnp._DynamicListBuilder` ### Members Includes all public and inherited members. ``` ```APIDOC ## Dynamic Struct Builder ### Description Internal class for building dynamic structs. ### Class `capnp.lib.capnp._DynamicStructBuilder` ### Members Includes all public and inherited members. ``` ```APIDOC ## Malloc Message Builder ### Description Internal class for building messages using malloc. ### Class `capnp.lib.capnp._MallocMessageBuilder` ### Members Includes all public and inherited members. ``` -------------------------------- ### Create Message from Dictionary Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Creates a Cap'n Proto message by passing keyword arguments derived from a Python dictionary to the new_message constructor. ```python my_dict = {'name' : 'alice'} alice = addressbook_capnp.Person.new_message(**my_dict) # equivalent to: alice = addressbook_capnp.Person.new_message(name='alice') ``` -------------------------------- ### SSL/TLS Client Connection with capnp Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Establishes an SSL/TLS encrypted connection to the server. Requires an SSL context, typically created with ssl.create_default_context(). ```python import ssl import socket import os async def main(): host = 'localhost' port = '6000' # Setup SSL context ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=os.path.join(this_dir, "selfsigned.cert")) connection = await capnp.AsyncIoStream.create_connection(host=host, port=port, ssl=ctx, family=socket.AF_INET) client = capnp.TwoPartyClient(connection) ## Bootstrap Here ## asyncio.run(capnp.run(main())) ``` -------------------------------- ### Read Multiple Messages from File Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Iterates through multiple Cap'n Proto messages serialized sequentially in a binary file. ```python with open('example.bin', 'rb') as f: for addresses in addressbook_capnp.AddressBook.read_multiple(f): print(addresses) ``` -------------------------------- ### Run pycapnp Tests Source: https://github.com/capnproto/pycapnp/blob/master/docs/install.rst Executes the test suite for pycapnp using pytest. You can run all tests or specify a particular test file. ```bash cd pycapnp pytest ``` ```bash pytest test/test_rpc_calculator.py ``` -------------------------------- ### Write Message to Async Socket Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Send a Cap'n Proto message asynchronously over a network socket. Requires an active asyncio event loop. ```python stream = await capnp.AsyncIoStream.create_connection(host="localhost", port=6000) await addresses.write_async(stream) ``` -------------------------------- ### Clone pycapnp Repository Source: https://github.com/capnproto/pycapnp/blob/master/docs/install.rst Clones the pycapnp repository from GitHub to obtain the latest development version. ```bash git clone https://github.com/capnproto/pycapnp.git ``` -------------------------------- ### Internal Module Classes Source: https://github.com/capnproto/pycapnp/blob/master/docs/capnp.rst Internal classes representing Cap'n Proto modules. ```APIDOC ## Interface Module ### Description Internal representation of a Cap'n Proto interface module. ### Class `capnp.capnp._InterfaceModule` ### Members Includes all public and inherited members. ``` ```APIDOC ## Struct Module ### Description Internal representation of a Cap'n Proto struct module. ### Class `capnp.capnp._StructModule` ### Members Includes all public and inherited members. ``` -------------------------------- ### Read Multiple Packed Messages from File Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Iterates through multiple packed Cap'n Proto messages serialized sequentially in a binary file. ```python for addresses in addressbook_capnp.AddressBook.read_multiple_packed(f): print addresses ``` -------------------------------- ### Communication Classes Source: https://github.com/capnproto/pycapnp/blob/master/docs/capnp.rst Classes for handling communication streams and connections. ```APIDOC ## TwoPartyClient ### Description Represents a client for two-party Cap'n Proto communication. ### Class `capnp.TwoPartyClient` ### Members Includes all public and inherited members. ``` ```APIDOC ## TwoPartyServer ### Description Represents a server for two-party Cap'n Proto communication. ### Class `capnp.TwoPartyServer` ### Members Includes all public and inherited members. ``` ```APIDOC ## AsyncIoStream ### Description Represents an asynchronous I/O stream for Cap'n Proto communication using asyncio. ### Class `capnp.AsyncIoStream` ### Members Includes all public and inherited members. ``` ```APIDOC ## Internal AsyncIoStream ### Description Internal implementation of an asynchronous I/O stream. ### Class `capnp.lib.capnp._AsyncIoStream` ### Members Includes all public and inherited members. ``` -------------------------------- ### Shorthand RPC Method Call with capnp Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst A more concise way to call RPC methods by passing parameters directly as a dictionary. This can become tedious for complex nested structures. ```python eval_promise = calculator.evaluate({"literal": 123}) ``` -------------------------------- ### Clean bundled build artifacts Source: https://github.com/capnproto/pycapnp/blob/master/README.md Clean up the bundled build artifacts for pycapnp. This may be necessary when switching between different versions or build configurations of the Cap'n Proto library. ```bash python setup.py clean ``` -------------------------------- ### Internal Reader Classes Source: https://github.com/capnproto/pycapnp/blob/master/docs/capnp.rst Internal classes for reading Cap'n Proto data structures. ```APIDOC ## Dynamic List Reader ### Description Internal class for reading dynamic lists. ### Class `capnp.lib.capnp._DynamicListReader` ### Members Includes all public and inherited members. ``` ```APIDOC ## Dynamic Struct Reader ### Description Internal class for reading dynamic structs. ### Class `capnp.lib.capnp._DynamicStructReader` ### Members Includes all public and inherited members. ``` ```APIDOC ## Packed Fd Message Reader ### Description Internal class for reading packed file descriptor messages. ### Class `capnp.lib.capnp._PackedFdMessageReader` ### Members Includes all public and inherited members. ``` ```APIDOC ## Stream Fd Message Reader ### Description Internal class for reading messages from a stream file descriptor. ### Class `capnp.lib.capnp._StreamFdMessageReader` ### Members Includes all public and inherited members. ``` -------------------------------- ### Pipelining RPC Calls Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Enables chaining method calls on capabilities returned by other methods without waiting for the initial promise to resolve. This avoids an extra server round-trip. ```python # evaluate returns `value` which is itself an interface. # You can call a new method on `value` without having to call wait first read_promise = eval_promise.value.read() read_result = await read_promise # only 1 await call ``` -------------------------------- ### Iterate and Print Fields Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Access and print fields from a Cap'n Proto message, including nested lists. Fields are accessed using standard dot notation. ```python for person in addresses.people: print(person.name, ':', person.email) for phone in person.phones: print(phone.type, ':', phone.number) ``` -------------------------------- ### Read Message from Async Socket Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Receive and deserialize a Cap'n Proto message asynchronously from a network socket. Requires an active asyncio event loop. ```python stream = await capnp.AsyncIoStream.create_connection(host="localhost", port=6000) message = await addressbook_capnp.AddressBook.read_async(stream) ``` -------------------------------- ### Read Packed Message from File Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Reads a single packed Cap'n Proto message from a binary file. ```python with open('example.bin', 'rb') as f: addresses = addressbook_capnp.AddressBook.read_packed(f) ``` -------------------------------- ### Serialize Message to Segments Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Serializes a Cap'n Proto message into a list of byte segments, minimizing object copies. ```python segments = alice.to_segments() ``` -------------------------------- ### Serialize Message to Bytes Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Serializes a Cap'n Proto message into a byte string. ```python encoded_message = alice.to_bytes() ``` -------------------------------- ### Convert Cap'n Proto Message to Dictionary Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Converts a Cap'n Proto Builder or Reader message into a Python dictionary. ```python alice.to_dict() ``` -------------------------------- ### Response Class Source: https://github.com/capnproto/pycapnp/blob/master/docs/capnp.rst Class representing a response from a Cap'n Proto RPC call. ```APIDOC ## Response ### Description Represents a response message in Cap'n Proto RPC. ### Class `capnp.lib.capnp._Response` ### Members Includes all public and inherited members. ``` -------------------------------- ### Cap'n Proto Struct with Various Data Types Source: https://github.com/capnproto/pycapnp/blob/master/test/all-types.txt This snippet defines a Cap'n Proto struct with fields of various primitive types, including integers, floats, text, and data. It also includes nested structs and lists of these types. This is useful for understanding how to represent complex data structures in Cap'n Proto. ```capnp ( voidField = void, boolField = true, int8Field = -123, int16Field = -12345, int32Field = -12345678, int64Field = -123456789012345, uInt8Field = 234, uInt16Field = 45678, uInt32Field = 3456789012, uInt64Field = 12345678901234567890, float32Field = 1234.5, float64Field = -1.23e47, textField = "foo", dataField = "bar", structField = ( voidField = void, boolField = true, int8Field = -12, int16Field = 3456, int32Field = -78901234, int64Field = 56789012345678, uInt8Field = 90, uInt16Field = 1234, uInt32Field = 56789012, uInt64Field = 345678901234567890, float32Field = -1.25e-10, float64Field = 345, textField = "☃", dataField = "qux", structField = ( voidField = void, boolField = false, int8Field = 0, int16Field = 0, int32Field = 0, int64Field = 0, uInt8Field = 0, uInt16Field = 0, uInt32Field = 0, uInt64Field = 0, float32Field = 0, float64Field = 0, textField = "nested", structField = ( voidField = void, boolField = false, int8Field = 0, int16Field = 0, int32Field = 0, int64Field = 0, uInt8Field = 0, uInt16Field = 0, uInt32Field = 0, uInt64Field = 0, float32Field = 0, float64Field = 0, textField = "really nested", enumField = foo, interfaceField = void ), enumField = foo, interfaceField = void ), enumField = baz, interfaceField = void, voidList = [void, void, void], boolList = [false, true, false, true, true], int8List = [12, -34, -128, 127], int16List = [1234, -5678, -32768, 32767], int32List = [12345678, -90123456, -2147483648, 2147483647], int64List = [123456789012345, -678901234567890, -9223372036854775808, 9223372036854775807], uInt8List = [12, 34, 0, 255], uInt16List = [1234, 5678, 0, 65535], uInt32List = [12345678, 90123456, 0, 4294967295], uInt64List = [123456789012345, 678901234567890, 0, 18446744073709551615], float32List = [0, 1234567, 1e37, -1e37, 1e-37, -1e-37], float64List = [0, 123456789012345, 1e306, -1e306, 1e-306, -1e-306], textList = ["quux", "corge", "grault"], dataList = ["garply", "waldo", "fred"], structList = [ ( voidField = void, boolField = false, int8Field = 0, int16Field = 0, int32Field = 0, int64Field = 0, uInt8Field = 0, uInt16Field = 0, uInt32Field = 0, uInt64Field = 0, float32Field = 0, float64Field = 0, textField = "x structlist 1", enumField = foo, interfaceField = void ), ( voidField = void, boolField = false, int8Field = 0, int16Field = 0, int32Field = 0, int64Field = 0, uInt8Field = 0, uInt16Field = 0, uInt32Field = 0, uInt64Field = 0, float32Field = 0, float64Field = 0, textField = "x structlist 2", enumField = foo, interfaceField = void ), ( voidField = void, boolField = false, int8Field = 0, int16Field = 0, int32Field = 0, int64Field = 0, uInt8Field = 0, uInt16Field = 0, uInt32Field = 0, uInt64Field = 0, float32Field = 0, float64Field = 0, textField = "x structlist 3", enumField = foo, interfaceField = void ) ], enumList = [qux, bar, grault] ), enumField = corge, interfaceField = void, voidList = [void, void, void, void, void, void], boolList = [true, false, false, true], int8List = [111, -111], int16List = [11111, -11111], int32List = [111111111, -111111111], int64List = [1111111111111111111, -1111111111111111111], uInt8List = [111, 222], uInt16List = [33333, 44444], uInt32List = [3333333333], uInt64List = [11111111111111111111], float32List = [5555.5, inf, -inf, nan], float64List = [7777.75, inf, -inf, nan], textList = ["plugh", "xyzzy", "thud"], dataList = ["oops", "exhausted", "rfc3092"], structList = [ ( voidField = void, boolField = false, int8Field = 0, int16Field = 0, int32Field = 0, int64Field = 0, uInt8Field = 0, uInt16Field = 0, uInt32Field = 0, uInt64Field = 0, float32Field = 0, float64Field = 0, textField = "structlist 1", enumField = foo, interfaceField = void ), ( voidField = void, boolField = false, int8Field = 0, int16Field = 0, int32Field = 0, int64Field = 0, uInt8Field = 0, uInt16Field = 0, uInt32Field = 0, uInt64Field = 0, float32Field = 0, float64Field = 0, textField = "structlist 2", enumField = foo, interfaceField = void ), ( voidField = void, boolField = false, int8Field = 0, int16Field = 0, ``` -------------------------------- ### Handle RPC Promise Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Awaits the result of an RPC call, which is returned as an asyncio promise. The result is obtained by awaiting the promise. ```python result = await eval_promise() ``` -------------------------------- ### Deserialize Message from Bytes Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Deserializes a Cap'n Proto message from a byte string. Requires a context manager for proper handling. ```python with addressbook_capnp.Person.from_bytes(encoded_message) as alice: # something with alice ``` -------------------------------- ### Internal Miscellaneous Classes Source: https://github.com/capnproto/pycapnp/blob/master/docs/capnp.rst Internal utility classes. ```APIDOC ## Dynamic Orphan ### Description Internal class representing a dynamically managed orphan. ### Class `capnp.lib.capnp._DynamicOrphan` ### Members Includes all public and inherited members. ``` -------------------------------- ### Serialize Message to Packed Bytes Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Serializes a Cap'n Proto message into a packed byte string. ```python alice2 = addressbook_capnp.Person.from_bytes_packed(alice.to_bytes_packed()) ``` -------------------------------- ### Deserialize Message from Segments Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Deserializes a Cap'n Proto message from a list of byte segments. ```python alice = addressbook_capnp.Person.from_segments(segments) ``` -------------------------------- ### Assign Primitive Types Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Assign values to primitive type fields (Int, UInt, Text, etc.) using standard Python types and dot notation. ```python alice.id = 123 alice.name = 'Alice' alice.email = 'alice@example.com' ``` -------------------------------- ### Access Const Values Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Access constant values defined in the loaded Cap'n Proto schema. ```python print(addressbook_capnp.qux) ``` -------------------------------- ### RPC Classes Source: https://github.com/capnproto/pycapnp/blob/master/docs/capnp.rst Classes related to Remote Procedure Call (RPC) functionality. ```APIDOC ## RemotePromise ### Description Represents a promise for a remote procedure call result. ### Class `capnp.lib.capnp._RemotePromise` ### Members Includes all public and inherited members. ``` ```APIDOC ## Capability Client ### Description Represents a client-side interface to a Cap'n Proto capability. ### Class `capnp.lib.capnp._CapabilityClient` ### Members Includes all public and inherited members. ``` ```APIDOC ## Dynamic Capability Client ### Description Represents a dynamically typed client-side interface to a Cap'n Proto capability. ### Class `capnp.lib.capnp._DynamicCapabilityClient` ### Members Includes all public and inherited members. ``` -------------------------------- ### Initialize Struct in Union Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst When a struct is a member of a union, it must be initialized using `init()` before its fields can be set. This prevents memory leaks. ```python school = alice.employment.init('school') school.name = "MIT" ``` -------------------------------- ### Assign Union Fields Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Assign values to union fields. Unions are generally treated like structs. ```python alice.employment.school = "MIT" ``` -------------------------------- ### Assign Enum Values Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Assign values to enum fields. Enums are treated like Text fields. Assigning an invalid value will raise a ValueError. ```python alicePhone = alice.init('phones', 1)[0] alicePhone.type = 'mobile' ``` -------------------------------- ### Assign Void Type in Union Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst To represent a void type in a union, assign `None` to the corresponding field. ```python bob.employment.unemployed = None ``` -------------------------------- ### Check Union Field Type Source: https://github.com/capnproto/pycapnp/blob/master/docs/quickstart.rst Determine which field of a union is currently active using the `.which()` method. This returns an enum string. ```python which = person.employment.which() print(which) if which == 'unemployed': print('unemployed') elif which == 'employer': print('employer:', person.employment.employer) elif which == 'school': print('student at:', person.employment.school) elif which == 'selfEmployed': print('self employed') print() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.