Skip to content

Python tutorial

Eric Sage edited this page Mar 24, 2017 · 1 revision

cxmate supports network algorithms in a variety of languages, but we'll be using Python as our example language. The concepts should carry over to other environments. Create a new python file called service.py and paste the following boilerplate code in:


import time
import logging
from concurrent import futures

import grpc

import cx_pb2
import cx_pb2_grpc

_ONE_DAY_IN_SECONDS = 60 * 60 * 24

class CyServiceServicer(cx_pb2_grpc.CyServiceServicer):

    def StreamElements(self, element_iterator, context):
        for element in element_iterator:
            yield element

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    cx_pb2_grpc.add_CyServiceServicer_to_server(
            CyServiceServicer(), server)
    server.add_insecure_port('0.0.0.0:8080')
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == '__main__':
    logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s %(message)s')
    logging.info("Listening for requests on '0.0.0.0:8080'")
    serve()

This boilerplate references a dependancy and two files that are not yet available on your system. To install the grpc dependancy, you can use pip install grpcio grpcio-tools. The cx_pb2 files are generated from a special cxmate schema file. First download the schema file from cxmate via wget or curl:

wget https://raw.githubusercontent.com/ericsage/cxmate/master/cxpb/cx.proto

Then generate the cx_pb2 files with this command:

python -m grpc_tools.protoc -I=. --python_out=. --grpc_python_out=. cx.proto

Now run this service in the background (you can also run it in the forground in a seperate tab):

python service.py &

Now we must configure cxmate by creating environment variables that cxmate can read on startup. We only need to tell cxmate to find our service on the same host with `export SERVICE_ADDRESS="localhost", the rest of the configuration defaults should work for this example.

Start cxmate:

cxmate &

Now try sending a CX document to cxmate running on your local machine:

curl --data "@sample_network.cx" localhost

The Python service should echo back the network, allowing cxmate to respond to your curl with a new network that is identical to the one you passed in.

Clone this wiki locally