Skip to content

Instantly share code, notes, and snippets.

@tfrench
tfrench / leader_election.py
Last active April 13, 2023 07:28
etcd v3 leader election using Python
"""etcd3 Leader election."""
import sys
import time
from threading import Event
import etcd3
LEADER_KEY = '/leader'
LEASE_TTL = 5
SLEEP = 1
@tfrench
tfrench / grpc_ssl_server.py
Last active January 20, 2022 09:04
Server code for using SSL and server-side authentication
# read in key and certificate
with open('server.key', 'rb') as f:
private_key = f.read()
with open('server.crt', 'rb') as f:
certificate_chain = f.read()
# create server credentials
server_credentials = grpc.ssl_server_credentials(
((private_key, certificate_chain,),))
@tfrench
tfrench / grpc_ssl_client.py
Last active February 27, 2018 10:04
Client code for using SSL and server-side authentication
# read in certificate
with open('server.crt', 'rb') as f:
trusted_certs = f.read()
# create credentials
credentials = grpc.ssl_channel_credentials(root_certificates=trusted_certs)
# create channel using ssl credentials
channel = grpc.secure_channel('{}:{}'.format(host, port), credentials)
@tfrench
tfrench / grpc_compression.py
Created April 26, 2017 09:52
Add compression to gRPC calls in Python
import grpc
from grpc._cython.cygrpc import CompressionAlgorithm
from grpc._cython.cygrpc import CompressionLevel
chan_ops = [('grpc.default_compression_algorithm', CompressionAlgorithm.gzip),
('grpc.grpc.default_compression_level', CompressionLevel.high)]
chan = grpc.insecure_channel("<srv_addr>:<srv_port>", chan_ops)
@tfrench
tfrench / server_metadata.py
Last active February 27, 2018 10:05
gRPC call metadata - server side
class ServerServicer(service_pb2_grpc.ServerServicer):
def Foo(self, request, context):
metadata = context.invocation_metadata()
print 'metadata: {}'.format(metadata)
return service_pb2.Empty()
@tfrench
tfrench / client_metadata.py
Last active February 27, 2018 10:06
gRPC call metadata - client side
stub = service_pb2_grpc.ServerStub(channel)
stub.Foo(service_pb2.Empty(), metadata=[('foo', 'bar')])