Applying black formatting

- Fixing flake8 configuration to agree with black
- Adding black validation check to github actions
This commit is contained in:
Jacob Alexander
2021-10-01 11:00:22 -07:00
parent 5dade41aeb
commit 6e7fffd7de
51 changed files with 2536 additions and 1837 deletions

View File

@@ -7,26 +7,26 @@ import addressbook_capnp
def writeAddressBook(file):
addresses = addressbook_capnp.AddressBook.new_message()
people = addresses.init('people', 2)
people = addresses.init("people", 2)
alice = people[0]
alice.id = 123
alice.name = 'Alice'
alice.email = 'alice@example.com'
alicePhones = alice.init('phones', 1)
alice.name = "Alice"
alice.email = "alice@example.com"
alicePhones = alice.init("phones", 1)
alicePhones[0].number = "555-1212"
alicePhones[0].type = 'mobile'
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)
bob.name = "Bob"
bob.email = "bob@example.com"
bobPhones = bob.init("phones", 2)
bobPhones[0].number = "555-4567"
bobPhones[0].type = 'home'
bobPhones[0].type = "home"
bobPhones[1].number = "555-7654"
bobPhones[1].type = 'work'
bobPhones[1].type = "work"
bob.employment.unemployed = None
addresses.write(file)
@@ -36,27 +36,27 @@ def printAddressBook(file):
addresses = addressbook_capnp.AddressBook.read(file)
for person in addresses.people:
print(person.name, ':', person.email)
print(person.name, ":", person.email)
for phone in person.phones:
print(phone.type, ':', phone.number)
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')
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')
if __name__ == "__main__":
f = open("example", "w")
writeAddressBook(f)
f = open('example', 'r')
f = open("example", "r")
printAddressBook(f)

View File

@@ -10,16 +10,16 @@ import calculator_capnp
class PowerFunction(calculator_capnp.Calculator.Function.Server):
'''An implementation of the Function interface wrapping pow(). Note that
"""An implementation of the Function interface wrapping pow(). Note that
we're implementing this on the client side and will pass a reference to
the server. The server will then be able to make calls back to the client.'''
the server. The server will then be able to make calls back to the client."""
def call(self, params, **kwargs):
'''Note the **kwargs. This is very necessary to include, since
"""Note the **kwargs. This is very necessary to include, since
protocols can add parameters over time. Also, by default, a _context
variable is passed to all server methods, but you can also return
results directly as python objects, and they'll be added to the
results struct in the correct order'''
results struct in the correct order"""
return pow(params[0], params[1])
@@ -38,29 +38,29 @@ async def mywriter(client, writer):
def parse_args():
parser = argparse.ArgumentParser(usage='Connects to the Calculator server \
at the given address and does some RPCs')
parser = argparse.ArgumentParser(
usage="Connects to the Calculator server \
at the given address and does some RPCs"
)
parser.add_argument("host", help="HOST:PORT")
return parser.parse_args()
async def main(host):
host = host.split(':')
host = host.split(":")
addr = host[0]
port = host[1]
# Handle both IPv4 and IPv6 cases
try:
print("Try IPv4")
reader, writer = await asyncio.open_connection(
addr, port,
family=socket.AF_INET
addr, port, family=socket.AF_INET
)
except Exception:
print("Try IPv6")
reader, writer = await asyncio.open_connection(
addr, port,
family=socket.AF_INET6
addr, port, family=socket.AF_INET6
)
# Start TwoPartyClient using TwoWayPipe (takes no arguments in this mode)
@@ -73,7 +73,7 @@ async def main(host):
# Bootstrap the Calculator interface
calculator = client.bootstrap().cast_as(calculator_capnp.Calculator)
'''Make a request that just evaluates the literal value 123.
"""Make a request that just evaluates the literal value 123.
What's interesting here is that evaluate() returns a "Value", which is
another interface and therefore points back to an object living on the
@@ -81,9 +81,9 @@ async def main(host):
However, even though we are making two RPC's, this block executes in
*one* network round trip because of promise pipelining: we do not wait
for the first call to complete before we send the second call to the
server.'''
server."""
print('Evaluating a literal... ', end="")
print("Evaluating a literal... ", end="")
# Make the request. Note we are using the shorter function form (instead
# of evaluate_request), and we are passing a dictionary that represents a
@@ -91,13 +91,13 @@ async def main(host):
eval_promise = calculator.evaluate({"literal": 123})
# This is equivalent to:
'''
"""
request = calculator.evaluate_request()
request.expression.literal = 123
# Send it, which returns a promise for the result (without blocking).
eval_promise = request.send()
'''
"""
# Using the promise, create a pipelined request to call read() on the
# returned object. Note that here we are using the shortened method call
@@ -111,32 +111,32 @@ async def main(host):
print("PASS")
'''Make a request to evaluate 123 + 45 - 67.
"""Make a request to evaluate 123 + 45 - 67.
The Calculator interface requires that we first call getOperator() to
get the addition and subtraction functions, then call evaluate() to use
them. But, once again, we can get both functions, call evaluate(), and
then read() the result -- four RPCs -- in the time of *one* network
round trip, because of promise pipelining.'''
round trip, because of promise pipelining."""
print("Using add and subtract... ", end='')
print("Using add and subtract... ", end="")
# Get the "add" function from the server.
add = calculator.getOperator(op='add').func
add = calculator.getOperator(op="add").func
# Get the "subtract" function from the server.
subtract = calculator.getOperator(op='subtract').func
subtract = calculator.getOperator(op="subtract").func
# Build the request to evaluate 123 + 45 - 67. Note the form is 'evaluate'
# + '_request', where 'evaluate' is the name of the method we want to call
request = calculator.evaluate_request()
subtract_call = request.expression.init('call')
subtract_call = request.expression.init("call")
subtract_call.function = subtract
subtract_params = subtract_call.init('params', 2)
subtract_params = subtract_call.init("params", 2)
subtract_params[1].literal = 67.0
add_call = subtract_params[0].init('call')
add_call = subtract_params[0].init("call")
add_call.function = add
add_params = add_call.init('params', 2)
add_params = add_call.init("params", 2)
add_params[0].literal = 123
add_params[1].literal = 45
@@ -149,7 +149,7 @@ async def main(host):
print("PASS")
'''
"""
Note: a one liner version of building the previous request (I highly
recommend not doing it this way for such a complicated structure, but I
just wanted to demonstrate it is possible to set all of the fields with a
@@ -161,22 +161,22 @@ async def main(host):
'params': [{'literal': 123},
{'literal': 45}]}},
{'literal': 67.0}]}})
'''
"""
'''Make a request to evaluate 4 * 6, then use the result in two more
"""Make a request to evaluate 4 * 6, then use the result in two more
requests that add 3 and 5.
Since evaluate() returns its result wrapped in a `Value`, we can pass
that `Value` back to the server in subsequent requests before the first
`evaluate()` has actually returned. Thus, this example again does only
one network round trip.'''
one network round trip."""
print("Pipelining eval() calls... ", end="")
# Get the "add" function from the server.
add = calculator.getOperator(op='add').func
add = calculator.getOperator(op="add").func
# Get the "multiply" function from the server.
multiply = calculator.getOperator(op='multiply').func
multiply = calculator.getOperator(op="multiply").func
# Build the request to evaluate 4 * 6
request = calculator.evaluate_request()
@@ -213,7 +213,7 @@ async def main(host):
print("PASS")
'''Our calculator interface supports defining functions. Here we use it
"""Our calculator interface supports defining functions. Here we use it
to define two functions and then make calls to them as follows:
f(x, y) = x * 100 + y
@@ -221,14 +221,14 @@ async def main(host):
f(12, 34)
g(21)
Once again, the whole thing takes only one network round trip.'''
Once again, the whole thing takes only one network round trip."""
print("Defining functions... ", end="")
# Get the "add" function from the server.
add = calculator.getOperator(op='add').func
add = calculator.getOperator(op="add").func
# Get the "multiply" function from the server.
multiply = calculator.getOperator(op='multiply').func
multiply = calculator.getOperator(op="multiply").func
# Define f.
request = calculator.defFunction_request()
@@ -286,7 +286,7 @@ async def main(host):
g_eval_request = calculator.evaluate_request()
g_call = g_eval_request.expression.init("call")
g_call.function = g
g_call.init('params', 1)[0].literal = 21
g_call.init("params", 1)[0].literal = 21
g_eval_promise = g_eval_request.send().value.read()
# Wait for the results.
@@ -295,7 +295,7 @@ async def main(host):
print("PASS")
'''Make a request that will call back to a function defined locally.
"""Make a request that will call back to a function defined locally.
Specifically, we will compute 2^(4 + 5). However, exponent is not
defined by the Calculator server. So, we'll implement the Function
@@ -307,12 +307,12 @@ async def main(host):
particular case, this could potentially be optimized by using a tail
call on the server side -- see CallContext::tailCall(). However, to
keep the example simpler, we haven't implemented this optimization in
the sample server.'''
the sample server."""
print("Using a callback... ", end="")
# Get the "add" function from the server.
add = calculator.getOperator(op='add').func
add = calculator.getOperator(op="add").func
# Build the eval request for 2^(4+5).
request = calculator.evaluate_request()
@@ -334,5 +334,6 @@ async def main(host):
print("PASS")
if __name__ == '__main__':
if __name__ == "__main__":
asyncio.run(main(parse_args().host))

View File

@@ -18,10 +18,7 @@ class Server:
while self.retry:
try:
# Must be a wait_for so we don't block on read()
data = await asyncio.wait_for(
self.reader.read(4096),
timeout=0.1
)
data = await asyncio.wait_for(self.reader.read(4096), timeout=0.1)
except asyncio.TimeoutError:
logger.debug("myreader timeout.")
continue
@@ -36,10 +33,7 @@ class Server:
while self.retry:
try:
# Must be a wait_for so we don't block on read()
data = await asyncio.wait_for(
self.server.read(4096),
timeout=0.1
)
data = await asyncio.wait_for(self.server.read(4096), timeout=0.1)
self.writer.write(data.tobytes())
except asyncio.TimeoutError:
logger.debug("mywriter timeout.")
@@ -74,29 +68,29 @@ class Server:
def read_value(value):
'''Helper function to asynchronously call read() on a Calculator::Value and
"""Helper function to asynchronously call read() on a Calculator::Value and
return a promise for the result. (In the future, the generated code might
include something like this automatically.)'''
include something like this automatically.)"""
return value.read().then(lambda result: result.value)
def evaluate_impl(expression, params=None):
'''Implementation of CalculatorImpl::evaluate(), also shared by
"""Implementation of CalculatorImpl::evaluate(), also shared by
FunctionImpl::call(). In the latter case, `params` are the parameter
values passed to the function; in the former case, `params` is just an
empty list.'''
empty list."""
which = expression.which()
if which == 'literal':
if which == "literal":
return capnp.Promise(expression.literal)
elif which == 'previousResult':
elif which == "previousResult":
return read_value(expression.previousResult)
elif which == 'parameter':
elif which == "parameter":
assert expression.parameter < len(params)
return capnp.Promise(params[expression.parameter])
elif which == 'call':
elif which == "call":
call = expression.call
func = call.function
@@ -105,9 +99,9 @@ def evaluate_impl(expression, params=None):
joinedParams = capnp.join_promises(paramPromises)
# When the parameters are complete, call the function.
ret = (joinedParams
.then(lambda vals: func.call(vals))
.then(lambda result: result.value))
ret = joinedParams.then(lambda vals: func.call(vals)).then(
lambda result: result.value
)
return ret
else:
@@ -127,28 +121,30 @@ class ValueImpl(calculator_capnp.Calculator.Value.Server):
class FunctionImpl(calculator_capnp.Calculator.Function.Server):
'''Implementation of the Calculator.Function Cap'n Proto interface, where the
function is defined by a Calculator.Expression.'''
"""Implementation of the Calculator.Function Cap'n Proto interface, where the
function is defined by a Calculator.Expression."""
def __init__(self, paramCount, body):
self.paramCount = paramCount
self.body = body.as_builder()
def call(self, params, _context, **kwargs):
'''Note that we're returning a Promise object here, and bypassing the
"""Note that we're returning a Promise object here, and bypassing the
helper functionality that normally sets the results struct from the
returned object. Instead, we set _context.results directly inside of
another promise'''
another promise"""
assert len(params) == self.paramCount
# using setattr because '=' is not allowed inside of lambdas
return evaluate_impl(self.body, params).then(lambda value: setattr(_context.results, 'value', value))
return evaluate_impl(self.body, params).then(
lambda value: setattr(_context.results, "value", value)
)
class OperatorImpl(calculator_capnp.Calculator.Function.Server):
'''Implementation of the Calculator.Function Cap'n Proto interface, wrapping
basic binary arithmetic operators.'''
"""Implementation of the Calculator.Function Cap'n Proto interface, wrapping
basic binary arithmetic operators."""
def __init__(self, op):
self.op = op
@@ -158,16 +154,16 @@ class OperatorImpl(calculator_capnp.Calculator.Function.Server):
op = self.op
if op == 'add':
if op == "add":
return params[0] + params[1]
elif op == 'subtract':
elif op == "subtract":
return params[0] - params[1]
elif op == 'multiply':
elif op == "multiply":
return params[0] * params[1]
elif op == 'divide':
elif op == "divide":
return params[0] / params[1]
else:
raise ValueError('Unknown operator')
raise ValueError("Unknown operator")
class CalculatorImpl(calculator_capnp.Calculator.Server):
@@ -175,7 +171,9 @@ 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)))
return evaluate_impl(expression).then(
lambda value: setattr(_context.results, "value", ValueImpl(value))
)
def defFunction(self, paramCount, body, _context, **kwargs):
return FunctionImpl(paramCount, body)
@@ -185,8 +183,10 @@ class CalculatorImpl(calculator_capnp.Calculator.Server):
def parse_args():
parser = argparse.ArgumentParser(usage='''Runs the server bound to the\
given address/port ADDRESS. ''')
parser = argparse.ArgumentParser(
usage="""Runs the server bound to the\
given address/port ADDRESS. """
)
parser.add_argument("address", help="ADDRESS:PORT")
@@ -200,7 +200,7 @@ async def new_connection(reader, writer):
async def main():
address = parse_args().address
host = address.split(':')
host = address.split(":")
addr = host[0]
port = host[1]
@@ -208,20 +208,17 @@ async def main():
try:
print("Try IPv4")
server = await asyncio.start_server(
new_connection,
addr, port,
family=socket.AF_INET
new_connection, addr, port, family=socket.AF_INET
)
except Exception:
print("Try IPv6")
server = await asyncio.start_server(
new_connection,
addr, port,
family=socket.AF_INET6
new_connection, addr, port, family=socket.AF_INET6
)
async with server:
await server.serve_forever()
if __name__ == '__main__':
if __name__ == "__main__":
asyncio.run(main())

View File

@@ -13,18 +13,20 @@ capnp.create_event_loop(threaded=True)
def parse_args():
parser = argparse.ArgumentParser(usage='Connects to the Example thread server \
at the given address and does some RPCs')
parser = argparse.ArgumentParser(
usage="Connects to the Example thread server \
at the given address and does some RPCs"
)
parser.add_argument("host", help="HOST:PORT")
return parser.parse_args()
class StatusSubscriber(thread_capnp.Example.StatusSubscriber.Server):
'''An implementation of the StatusSubscriber interface'''
"""An implementation of the StatusSubscriber interface"""
def status(self, value, **kwargs):
print('status: {}'.format(time.time()))
print("status: {}".format(time.time()))
async def myreader(client, reader):
@@ -46,21 +48,19 @@ async def background(cap):
async def main(host):
host = host.split(':')
host = host.split(":")
addr = host[0]
port = host[1]
# Handle both IPv4 and IPv6 cases
try:
print("Try IPv4")
reader, writer = await asyncio.open_connection(
addr, port,
family=socket.AF_INET
addr, port, family=socket.AF_INET
)
except Exception:
print("Try IPv6")
reader, writer = await asyncio.open_connection(
addr, port,
family=socket.AF_INET6
addr, port, family=socket.AF_INET6
)
# Start TwoPartyClient using TwoWayPipe (takes no arguments in this mode)
@@ -76,13 +76,14 @@ async def main(host):
asyncio.gather(*tasks, return_exceptions=True)
# Run blocking tasks
print('main: {}'.format(time.time()))
print("main: {}".format(time.time()))
await cap.longRunning().a_wait()
print('main: {}'.format(time.time()))
print("main: {}".format(time.time()))
await cap.longRunning().a_wait()
print('main: {}'.format(time.time()))
print("main: {}".format(time.time()))
await cap.longRunning().a_wait()
print('main: {}'.format(time.time()))
print("main: {}".format(time.time()))
if __name__ == '__main__':
if __name__ == "__main__":
asyncio.run(main(parse_args().host))

View File

@@ -17,18 +17,20 @@ capnp.create_event_loop(threaded=True)
def parse_args():
parser = argparse.ArgumentParser(usage='Connects to the Example thread server \
at the given address and does some RPCs')
parser = argparse.ArgumentParser(
usage="Connects to the Example thread server \
at the given address and does some RPCs"
)
parser.add_argument("host", help="HOST:PORT")
return parser.parse_args()
class StatusSubscriber(thread_capnp.Example.StatusSubscriber.Server):
'''An implementation of the StatusSubscriber interface'''
"""An implementation of the StatusSubscriber interface"""
def status(self, value, **kwargs):
print('status: {}'.format(time.time()))
print("status: {}".format(time.time()))
async def myreader(client, reader):
@@ -71,28 +73,26 @@ async def background(cap):
async def main(host):
host = host.split(':')
host = host.split(":")
addr = host[0]
port = host[1]
# Setup SSL context
ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=os.path.join(this_dir, 'selfsigned.cert'))
ctx = ssl.create_default_context(
ssl.Purpose.SERVER_AUTH, cafile=os.path.join(this_dir, "selfsigned.cert")
)
# Handle both IPv4 and IPv6 cases
try:
print("Try IPv4")
reader, writer = await asyncio.open_connection(
addr, port,
ssl=ctx,
family=socket.AF_INET
addr, port, ssl=ctx, family=socket.AF_INET
)
except OSError:
print("Try IPv6")
try:
reader, writer = await asyncio.open_connection(
addr, port,
ssl=ctx,
family=socket.AF_INET6
addr, port, ssl=ctx, family=socket.AF_INET6
)
except OSError:
return False
@@ -115,20 +115,21 @@ async def main(host):
overalltasks.append(asyncio.gather(*tasks, return_exceptions=True))
# Run blocking tasks
print('main: {}'.format(time.time()))
print("main: {}".format(time.time()))
await cap.longRunning().a_wait()
print('main: {}'.format(time.time()))
print("main: {}".format(time.time()))
await cap.longRunning().a_wait()
print('main: {}'.format(time.time()))
print("main: {}".format(time.time()))
await cap.longRunning().a_wait()
print('main: {}'.format(time.time()))
print("main: {}".format(time.time()))
for task in overalltasks:
task.cancel()
return True
if __name__ == '__main__':
if __name__ == "__main__":
# Using asyncio.run hits an asyncio ssl bug
# https://bugs.python.org/issue36709
# asyncio.run(main(parse_args().host), loop=loop, debug=True)

View File

@@ -18,12 +18,15 @@ class ExampleImpl(thread_capnp.Example.Server):
"Implementation of the Example threading Cap'n Proto interface."
def subscribeStatus(self, subscriber, **kwargs):
return capnp.getTimer().after_delay(10**9) \
.then(lambda: subscriber.status(True)) \
return (
capnp.getTimer()
.after_delay(10 ** 9)
.then(lambda: subscriber.status(True))
.then(lambda _: self.subscribeStatus(subscriber))
)
def longRunning(self, **kwargs):
return capnp.getTimer().after_delay(1 * 10**9)
return capnp.getTimer().after_delay(1 * 10 ** 9)
class Server:
@@ -31,10 +34,7 @@ class Server:
while self.retry:
try:
# Must be a wait_for so we don't block on read()
data = await asyncio.wait_for(
self.reader.read(4096),
timeout=0.1
)
data = await asyncio.wait_for(self.reader.read(4096), timeout=0.1)
except asyncio.TimeoutError:
logger.debug("myreader timeout.")
continue
@@ -49,10 +49,7 @@ class Server:
while self.retry:
try:
# Must be a wait_for so we don't block on read()
data = await asyncio.wait_for(
self.server.read(4096),
timeout=0.1
)
data = await asyncio.wait_for(self.server.read(4096), timeout=0.1)
self.writer.write(data.tobytes())
except asyncio.TimeoutError:
logger.debug("mywriter timeout.")
@@ -87,8 +84,10 @@ class Server:
def parse_args():
parser = argparse.ArgumentParser(usage='''Runs the server bound to the\
given address/port ADDRESS. ''')
parser = argparse.ArgumentParser(
usage="""Runs the server bound to the\
given address/port ADDRESS. """
)
parser.add_argument("address", help="ADDRESS:PORT")
@@ -102,7 +101,7 @@ async def new_connection(reader, writer):
async def main():
address = parse_args().address
host = address.split(':')
host = address.split(":")
addr = host[0]
port = host[1]
@@ -110,21 +109,17 @@ async def main():
try:
print("Try IPv4")
server = await asyncio.start_server(
new_connection,
addr, port,
family=socket.AF_INET
new_connection, addr, port, family=socket.AF_INET
)
except Exception:
print("Try IPv6")
server = await asyncio.start_server(
new_connection,
addr, port,
family=socket.AF_INET6
new_connection, addr, port, family=socket.AF_INET6
)
async with server:
await server.serve_forever()
if __name__ == '__main__':
if __name__ == "__main__":
asyncio.run(main())

View File

@@ -15,16 +15,16 @@ this_dir = os.path.dirname(os.path.abspath(__file__))
class PowerFunction(calculator_capnp.Calculator.Function.Server):
'''An implementation of the Function interface wrapping pow(). Note that
"""An implementation of the Function interface wrapping pow(). Note that
we're implementing this on the client side and will pass a reference to
the server. The server will then be able to make calls back to the client.'''
the server. The server will then be able to make calls back to the client."""
def call(self, params, **kwargs):
'''Note the **kwargs. This is very necessary to include, since
"""Note the **kwargs. This is very necessary to include, since
protocols can add parameters over time. Also, by default, a _context
variable is passed to all server methods, but you can also return
results directly as python objects, and they'll be added to the
results struct in the correct order'''
results struct in the correct order"""
return pow(params[0], params[1])
@@ -43,35 +43,35 @@ async def mywriter(client, writer):
def parse_args():
parser = argparse.ArgumentParser(usage='Connects to the Calculator server \
at the given address and does some RPCs')
parser = argparse.ArgumentParser(
usage="Connects to the Calculator server \
at the given address and does some RPCs"
)
parser.add_argument("host", help="HOST:PORT")
return parser.parse_args()
async def main(host):
host = host.split(':')
host = host.split(":")
addr = host[0]
port = host[1]
# Setup SSL context
ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=os.path.join(this_dir, 'selfsigned.cert'))
ctx = ssl.create_default_context(
ssl.Purpose.SERVER_AUTH, cafile=os.path.join(this_dir, "selfsigned.cert")
)
# Handle both IPv4 and IPv6 cases
try:
print("Try IPv4")
reader, writer = await asyncio.open_connection(
addr, port,
ssl=ctx,
family=socket.AF_INET
addr, port, ssl=ctx, family=socket.AF_INET
)
except Exception:
print("Try IPv6")
reader, writer = await asyncio.open_connection(
addr, port,
ssl=ctx,
family=socket.AF_INET6
addr, port, ssl=ctx, family=socket.AF_INET6
)
# Start TwoPartyClient using TwoWayPipe (takes no arguments in this mode)
@@ -84,7 +84,7 @@ async def main(host):
# Bootstrap the Calculator interface
calculator = client.bootstrap().cast_as(calculator_capnp.Calculator)
'''Make a request that just evaluates the literal value 123.
"""Make a request that just evaluates the literal value 123.
What's interesting here is that evaluate() returns a "Value", which is
another interface and therefore points back to an object living on the
@@ -92,9 +92,9 @@ async def main(host):
However, even though we are making two RPC's, this block executes in
*one* network round trip because of promise pipelining: we do not wait
for the first call to complete before we send the second call to the
server.'''
server."""
print('Evaluating a literal... ', end="")
print("Evaluating a literal... ", end="")
# Make the request. Note we are using the shorter function form (instead
# of evaluate_request), and we are passing a dictionary that represents a
@@ -102,13 +102,13 @@ async def main(host):
eval_promise = calculator.evaluate({"literal": 123})
# This is equivalent to:
'''
"""
request = calculator.evaluate_request()
request.expression.literal = 123
# Send it, which returns a promise for the result (without blocking).
eval_promise = request.send()
'''
"""
# Using the promise, create a pipelined request to call read() on the
# returned object. Note that here we are using the shortened method call
@@ -122,32 +122,32 @@ async def main(host):
print("PASS")
'''Make a request to evaluate 123 + 45 - 67.
"""Make a request to evaluate 123 + 45 - 67.
The Calculator interface requires that we first call getOperator() to
get the addition and subtraction functions, then call evaluate() to use
them. But, once again, we can get both functions, call evaluate(), and
then read() the result -- four RPCs -- in the time of *one* network
round trip, because of promise pipelining.'''
round trip, because of promise pipelining."""
print("Using add and subtract... ", end='')
print("Using add and subtract... ", end="")
# Get the "add" function from the server.
add = calculator.getOperator(op='add').func
add = calculator.getOperator(op="add").func
# Get the "subtract" function from the server.
subtract = calculator.getOperator(op='subtract').func
subtract = calculator.getOperator(op="subtract").func
# Build the request to evaluate 123 + 45 - 67. Note the form is 'evaluate'
# + '_request', where 'evaluate' is the name of the method we want to call
request = calculator.evaluate_request()
subtract_call = request.expression.init('call')
subtract_call = request.expression.init("call")
subtract_call.function = subtract
subtract_params = subtract_call.init('params', 2)
subtract_params = subtract_call.init("params", 2)
subtract_params[1].literal = 67.0
add_call = subtract_params[0].init('call')
add_call = subtract_params[0].init("call")
add_call.function = add
add_params = add_call.init('params', 2)
add_params = add_call.init("params", 2)
add_params[0].literal = 123
add_params[1].literal = 45
@@ -160,7 +160,7 @@ async def main(host):
print("PASS")
'''
"""
Note: a one liner version of building the previous request (I highly
recommend not doing it this way for such a complicated structure, but I
just wanted to demonstrate it is possible to set all of the fields with a
@@ -172,22 +172,22 @@ async def main(host):
'params': [{'literal': 123},
{'literal': 45}]}},
{'literal': 67.0}]}})
'''
"""
'''Make a request to evaluate 4 * 6, then use the result in two more
"""Make a request to evaluate 4 * 6, then use the result in two more
requests that add 3 and 5.
Since evaluate() returns its result wrapped in a `Value`, we can pass
that `Value` back to the server in subsequent requests before the first
`evaluate()` has actually returned. Thus, this example again does only
one network round trip.'''
one network round trip."""
print("Pipelining eval() calls... ", end="")
# Get the "add" function from the server.
add = calculator.getOperator(op='add').func
add = calculator.getOperator(op="add").func
# Get the "multiply" function from the server.
multiply = calculator.getOperator(op='multiply').func
multiply = calculator.getOperator(op="multiply").func
# Build the request to evaluate 4 * 6
request = calculator.evaluate_request()
@@ -224,7 +224,7 @@ async def main(host):
print("PASS")
'''Our calculator interface supports defining functions. Here we use it
"""Our calculator interface supports defining functions. Here we use it
to define two functions and then make calls to them as follows:
f(x, y) = x * 100 + y
@@ -232,14 +232,14 @@ async def main(host):
f(12, 34)
g(21)
Once again, the whole thing takes only one network round trip.'''
Once again, the whole thing takes only one network round trip."""
print("Defining functions... ", end="")
# Get the "add" function from the server.
add = calculator.getOperator(op='add').func
add = calculator.getOperator(op="add").func
# Get the "multiply" function from the server.
multiply = calculator.getOperator(op='multiply').func
multiply = calculator.getOperator(op="multiply").func
# Define f.
request = calculator.defFunction_request()
@@ -297,7 +297,7 @@ async def main(host):
g_eval_request = calculator.evaluate_request()
g_call = g_eval_request.expression.init("call")
g_call.function = g
g_call.init('params', 1)[0].literal = 21
g_call.init("params", 1)[0].literal = 21
g_eval_promise = g_eval_request.send().value.read()
# Wait for the results.
@@ -306,7 +306,7 @@ async def main(host):
print("PASS")
'''Make a request that will call back to a function defined locally.
"""Make a request that will call back to a function defined locally.
Specifically, we will compute 2^(4 + 5). However, exponent is not
defined by the Calculator server. So, we'll implement the Function
@@ -318,12 +318,12 @@ async def main(host):
particular case, this could potentially be optimized by using a tail
call on the server side -- see CallContext::tailCall(). However, to
keep the example simpler, we haven't implemented this optimization in
the sample server.'''
the sample server."""
print("Using a callback... ", end="")
# Get the "add" function from the server.
add = calculator.getOperator(op='add').func
add = calculator.getOperator(op="add").func
# Build the eval request for 2^(4+5).
request = calculator.evaluate_request()
@@ -345,7 +345,8 @@ async def main(host):
print("PASS")
if __name__ == '__main__':
if __name__ == "__main__":
# Using asyncio.run hits an asyncio ssl bug
# https://bugs.python.org/issue36709
# asyncio.run(main(parse_args().host), loop=loop, debug=True)

View File

@@ -22,10 +22,7 @@ class Server:
while self.retry:
try:
# Must be a wait_for so we don't block on read()
data = await asyncio.wait_for(
self.reader.read(4096),
timeout=0.1
)
data = await asyncio.wait_for(self.reader.read(4096), timeout=0.1)
except asyncio.TimeoutError:
logger.debug("myreader timeout.")
continue
@@ -40,10 +37,7 @@ class Server:
while self.retry:
try:
# Must be a wait_for so we don't block on read()
data = await asyncio.wait_for(
self.server.read(4096),
timeout=0.1
)
data = await asyncio.wait_for(self.server.read(4096), timeout=0.1)
self.writer.write(data.tobytes())
except asyncio.TimeoutError:
logger.debug("mywriter timeout.")
@@ -78,29 +72,29 @@ class Server:
def read_value(value):
'''Helper function to asynchronously call read() on a Calculator::Value and
"""Helper function to asynchronously call read() on a Calculator::Value and
return a promise for the result. (In the future, the generated code might
include something like this automatically.)'''
include something like this automatically.)"""
return value.read().then(lambda result: result.value)
def evaluate_impl(expression, params=None):
'''Implementation of CalculatorImpl::evaluate(), also shared by
"""Implementation of CalculatorImpl::evaluate(), also shared by
FunctionImpl::call(). In the latter case, `params` are the parameter
values passed to the function; in the former case, `params` is just an
empty list.'''
empty list."""
which = expression.which()
if which == 'literal':
if which == "literal":
return capnp.Promise(expression.literal)
elif which == 'previousResult':
elif which == "previousResult":
return read_value(expression.previousResult)
elif which == 'parameter':
elif which == "parameter":
assert expression.parameter < len(params)
return capnp.Promise(params[expression.parameter])
elif which == 'call':
elif which == "call":
call = expression.call
func = call.function
@@ -109,9 +103,9 @@ def evaluate_impl(expression, params=None):
joinedParams = capnp.join_promises(paramPromises)
# When the parameters are complete, call the function.
ret = (joinedParams
.then(lambda vals: func.call(vals))
.then(lambda result: result.value))
ret = joinedParams.then(lambda vals: func.call(vals)).then(
lambda result: result.value
)
return ret
else:
@@ -131,28 +125,30 @@ class ValueImpl(calculator_capnp.Calculator.Value.Server):
class FunctionImpl(calculator_capnp.Calculator.Function.Server):
'''Implementation of the Calculator.Function Cap'n Proto interface, where the
function is defined by a Calculator.Expression.'''
"""Implementation of the Calculator.Function Cap'n Proto interface, where the
function is defined by a Calculator.Expression."""
def __init__(self, paramCount, body):
self.paramCount = paramCount
self.body = body.as_builder()
def call(self, params, _context, **kwargs):
'''Note that we're returning a Promise object here, and bypassing the
"""Note that we're returning a Promise object here, and bypassing the
helper functionality that normally sets the results struct from the
returned object. Instead, we set _context.results directly inside of
another promise'''
another promise"""
assert len(params) == self.paramCount
# using setattr because '=' is not allowed inside of lambdas
return evaluate_impl(self.body, params).then(lambda value: setattr(_context.results, 'value', value))
return evaluate_impl(self.body, params).then(
lambda value: setattr(_context.results, "value", value)
)
class OperatorImpl(calculator_capnp.Calculator.Function.Server):
'''Implementation of the Calculator.Function Cap'n Proto interface, wrapping
basic binary arithmetic operators.'''
"""Implementation of the Calculator.Function Cap'n Proto interface, wrapping
basic binary arithmetic operators."""
def __init__(self, op):
self.op = op
@@ -162,16 +158,16 @@ class OperatorImpl(calculator_capnp.Calculator.Function.Server):
op = self.op
if op == 'add':
if op == "add":
return params[0] + params[1]
elif op == 'subtract':
elif op == "subtract":
return params[0] - params[1]
elif op == 'multiply':
elif op == "multiply":
return params[0] * params[1]
elif op == 'divide':
elif op == "divide":
return params[0] / params[1]
else:
raise ValueError('Unknown operator')
raise ValueError("Unknown operator")
class CalculatorImpl(calculator_capnp.Calculator.Server):
@@ -179,7 +175,9 @@ 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)))
return evaluate_impl(expression).then(
lambda value: setattr(_context.results, "value", ValueImpl(value))
)
def defFunction(self, paramCount, body, _context, **kwargs):
return FunctionImpl(paramCount, body)
@@ -189,8 +187,10 @@ class CalculatorImpl(calculator_capnp.Calculator.Server):
def parse_args():
parser = argparse.ArgumentParser(usage='''Runs the server bound to the\
given address/port ADDRESS. ''')
parser = argparse.ArgumentParser(
usage="""Runs the server bound to the\
given address/port ADDRESS. """
)
parser.add_argument("address", help="ADDRESS:PORT")
@@ -204,34 +204,32 @@ async def new_connection(reader, writer):
async def main():
address = parse_args().address
host = address.split(':')
host = address.split(":")
addr = host[0]
port = host[1]
# 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'))
ctx.load_cert_chain(
os.path.join(this_dir, "selfsigned.cert"),
os.path.join(this_dir, "selfsigned.key"),
)
# Handle both IPv4 and IPv6 cases
try:
print("Try IPv4")
server = await asyncio.start_server(
new_connection,
addr, port,
ssl=ctx,
family=socket.AF_INET
new_connection, addr, port, ssl=ctx, family=socket.AF_INET
)
except Exception:
print("Try IPv6")
server = await asyncio.start_server(
new_connection,
addr, port,
ssl=ctx,
family=socket.AF_INET6
new_connection, addr, port, ssl=ctx, family=socket.AF_INET6
)
async with server:
await server.serve_forever()
if __name__ == '__main__':
if __name__ == "__main__":
asyncio.run(main())

View File

@@ -14,18 +14,20 @@ this_dir = os.path.dirname(os.path.abspath(__file__))
def parse_args():
parser = argparse.ArgumentParser(usage='Connects to the Example thread server \
at the given address and does some RPCs')
parser = argparse.ArgumentParser(
usage="Connects to the Example thread server \
at the given address and does some RPCs"
)
parser.add_argument("host", help="HOST:PORT")
return parser.parse_args()
class StatusSubscriber(thread_capnp.Example.StatusSubscriber.Server):
'''An implementation of the StatusSubscriber interface'''
"""An implementation of the StatusSubscriber interface"""
def status(self, value, **kwargs):
print('status: {}'.format(time.time()))
print("status: {}".format(time.time()))
async def myreader(client, reader):
@@ -48,27 +50,25 @@ async def background(cap):
async def main(host):
host = host.split(':')
host = host.split(":")
addr = host[0]
port = host[1]
# Setup SSL context
ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=os.path.join(this_dir, 'selfsigned.cert'))
ctx = ssl.create_default_context(
ssl.Purpose.SERVER_AUTH, cafile=os.path.join(this_dir, "selfsigned.cert")
)
# Handle both IPv4 and IPv6 cases
try:
print("Try IPv4")
reader, writer = await asyncio.open_connection(
addr, port,
ssl=ctx,
family=socket.AF_INET
addr, port, ssl=ctx, family=socket.AF_INET
)
except Exception:
print("Try IPv6")
reader, writer = await asyncio.open_connection(
addr, port,
ssl=ctx,
family=socket.AF_INET6
addr, port, ssl=ctx, family=socket.AF_INET6
)
# Start TwoPartyClient using TwoWayPipe (takes no arguments in this mode)
@@ -84,15 +84,16 @@ async def main(host):
asyncio.gather(*tasks, return_exceptions=True)
# Run blocking tasks
print('main: {}'.format(time.time()))
print("main: {}".format(time.time()))
await cap.longRunning().a_wait()
print('main: {}'.format(time.time()))
print("main: {}".format(time.time()))
await cap.longRunning().a_wait()
print('main: {}'.format(time.time()))
print("main: {}".format(time.time()))
await cap.longRunning().a_wait()
print('main: {}'.format(time.time()))
print("main: {}".format(time.time()))
if __name__ == '__main__':
if __name__ == "__main__":
# Using asyncio.run hits an asyncio ssl bug
# https://bugs.python.org/issue36709
# asyncio.run(main(parse_args().host), loop=loop, debug=True)

View File

@@ -22,12 +22,15 @@ class ExampleImpl(thread_capnp.Example.Server):
"Implementation of the Example threading Cap'n Proto interface."
def subscribeStatus(self, subscriber, **kwargs):
return capnp.getTimer().after_delay(10**9) \
.then(lambda: subscriber.status(True)) \
return (
capnp.getTimer()
.after_delay(10 ** 9)
.then(lambda: subscriber.status(True))
.then(lambda _: self.subscribeStatus(subscriber))
)
def longRunning(self, **kwargs):
return capnp.getTimer().after_delay(1 * 10**9)
return capnp.getTimer().after_delay(1 * 10 ** 9)
def alive(self, **kwargs):
return True
@@ -38,10 +41,7 @@ class Server:
while self.retry:
try:
# Must be a wait_for so we don't block on read()
data = await asyncio.wait_for(
self.reader.read(4096),
timeout=0.1
)
data = await asyncio.wait_for(self.reader.read(4096), timeout=0.1)
except asyncio.TimeoutError:
logger.debug("myreader timeout.")
continue
@@ -56,10 +56,7 @@ class Server:
while self.retry:
try:
# Must be a wait_for so we don't block on read()
data = await asyncio.wait_for(
self.server.read(4096),
timeout=0.1
)
data = await asyncio.wait_for(self.server.read(4096), timeout=0.1)
self.writer.write(data.tobytes())
except asyncio.TimeoutError:
logger.debug("mywriter timeout.")
@@ -99,8 +96,10 @@ async def new_connection(reader, writer):
def parse_args():
parser = argparse.ArgumentParser(usage='''Runs the server bound to the\
given address/port ADDRESS. ''')
parser = argparse.ArgumentParser(
usage="""Runs the server bound to the\
given address/port ADDRESS. """
)
parser.add_argument("address", help="ADDRESS:PORT")
@@ -109,20 +108,24 @@ given address/port ADDRESS. ''')
async def main():
address = parse_args().address
host = address.split(':')
host = address.split(":")
addr = host[0]
port = host[1]
# 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'))
ctx.load_cert_chain(
os.path.join(this_dir, "selfsigned.cert"),
os.path.join(this_dir, "selfsigned.key"),
)
# Handle both IPv4 and IPv6 cases
try:
print("Try IPv4")
server = await asyncio.start_server(
new_connection,
addr, port,
addr,
port,
ssl=ctx,
family=socket.AF_INET,
)
@@ -130,7 +133,8 @@ async def main():
print("Try IPv6")
server = await asyncio.start_server(
new_connection,
addr, port,
addr,
port,
ssl=ctx,
family=socket.AF_INET6,
)
@@ -138,5 +142,6 @@ async def main():
async with server:
await server.serve_forever()
if __name__ == '__main__':
if __name__ == "__main__":
asyncio.run(main())

View File

@@ -8,23 +8,25 @@ import calculator_capnp
class PowerFunction(calculator_capnp.Calculator.Function.Server):
'''An implementation of the Function interface wrapping pow(). Note that
"""An implementation of the Function interface wrapping pow(). Note that
we're implementing this on the client side and will pass a reference to
the server. The server will then be able to make calls back to the client.'''
the server. The server will then be able to make calls back to the client."""
def call(self, params, **kwargs):
'''Note the **kwargs. This is very necessary to include, since
"""Note the **kwargs. This is very necessary to include, since
protocols can add parameters over time. Also, by default, a _context
variable is passed to all server methods, but you can also return
results directly as python objects, and they'll be added to the
results struct in the correct order'''
results struct in the correct order"""
return pow(params[0], params[1])
def parse_args():
parser = argparse.ArgumentParser(usage='Connects to the Calculator server \
at the given address and does some RPCs')
parser = argparse.ArgumentParser(
usage="Connects to the Calculator server \
at the given address and does some RPCs"
)
parser.add_argument("host", help="HOST:PORT")
return parser.parse_args()
@@ -36,7 +38,7 @@ def main(host):
# Bootstrap the server capability and cast it to the Calculator interface
calculator = client.bootstrap().cast_as(calculator_capnp.Calculator)
'''Make a request that just evaluates the literal value 123.
"""Make a request that just evaluates the literal value 123.
What's interesting here is that evaluate() returns a "Value", which is
another interface and therefore points back to an object living on the
@@ -44,9 +46,9 @@ def main(host):
However, even though we are making two RPC's, this block executes in
*one* network round trip because of promise pipelining: we do not wait
for the first call to complete before we send the second call to the
server.'''
server."""
print('Evaluating a literal... ', end="")
print("Evaluating a literal... ", end="")
# Make the request. Note we are using the shorter function form (instead
# of evaluate_request), and we are passing a dictionary that represents a
@@ -54,13 +56,13 @@ def main(host):
eval_promise = calculator.evaluate({"literal": 123})
# This is equivalent to:
'''
"""
request = calculator.evaluate_request()
request.expression.literal = 123
# Send it, which returns a promise for the result (without blocking).
eval_promise = request.send()
'''
"""
# Using the promise, create a pipelined request to call read() on the
# returned object. Note that here we are using the shortened method call
@@ -74,32 +76,32 @@ def main(host):
print("PASS")
'''Make a request to evaluate 123 + 45 - 67.
"""Make a request to evaluate 123 + 45 - 67.
The Calculator interface requires that we first call getOperator() to
get the addition and subtraction functions, then call evaluate() to use
them. But, once again, we can get both functions, call evaluate(), and
then read() the result -- four RPCs -- in the time of *one* network
round trip, because of promise pipelining.'''
round trip, because of promise pipelining."""
print("Using add and subtract... ", end='')
print("Using add and subtract... ", end="")
# Get the "add" function from the server.
add = calculator.getOperator(op='add').func
add = calculator.getOperator(op="add").func
# Get the "subtract" function from the server.
subtract = calculator.getOperator(op='subtract').func
subtract = calculator.getOperator(op="subtract").func
# Build the request to evaluate 123 + 45 - 67. Note the form is 'evaluate'
# + '_request', where 'evaluate' is the name of the method we want to call
request = calculator.evaluate_request()
subtract_call = request.expression.init('call')
subtract_call = request.expression.init("call")
subtract_call.function = subtract
subtract_params = subtract_call.init('params', 2)
subtract_params = subtract_call.init("params", 2)
subtract_params[1].literal = 67.0
add_call = subtract_params[0].init('call')
add_call = subtract_params[0].init("call")
add_call.function = add
add_params = add_call.init('params', 2)
add_params = add_call.init("params", 2)
add_params[0].literal = 123
add_params[1].literal = 45
@@ -112,7 +114,7 @@ def main(host):
print("PASS")
'''
"""
Note: a one liner version of building the previous request (I highly
recommend not doing it this way for such a complicated structure, but I
just wanted to demonstrate it is possible to set all of the fields with a
@@ -124,22 +126,22 @@ def main(host):
'params': [{'literal': 123},
{'literal': 45}]}},
{'literal': 67.0}]}})
'''
"""
'''Make a request to evaluate 4 * 6, then use the result in two more
"""Make a request to evaluate 4 * 6, then use the result in two more
requests that add 3 and 5.
Since evaluate() returns its result wrapped in a `Value`, we can pass
that `Value` back to the server in subsequent requests before the first
`evaluate()` has actually returned. Thus, this example again does only
one network round trip.'''
one network round trip."""
print("Pipelining eval() calls... ", end="")
# Get the "add" function from the server.
add = calculator.getOperator(op='add').func
add = calculator.getOperator(op="add").func
# Get the "multiply" function from the server.
multiply = calculator.getOperator(op='multiply').func
multiply = calculator.getOperator(op="multiply").func
# Build the request to evaluate 4 * 6
request = calculator.evaluate_request()
@@ -176,7 +178,7 @@ def main(host):
print("PASS")
'''Our calculator interface supports defining functions. Here we use it
"""Our calculator interface supports defining functions. Here we use it
to define two functions and then make calls to them as follows:
f(x, y) = x * 100 + y
@@ -184,14 +186,14 @@ def main(host):
f(12, 34)
g(21)
Once again, the whole thing takes only one network round trip.'''
Once again, the whole thing takes only one network round trip."""
print("Defining functions... ", end="")
# Get the "add" function from the server.
add = calculator.getOperator(op='add').func
add = calculator.getOperator(op="add").func
# Get the "multiply" function from the server.
multiply = calculator.getOperator(op='multiply').func
multiply = calculator.getOperator(op="multiply").func
# Define f.
request = calculator.defFunction_request()
@@ -249,7 +251,7 @@ def main(host):
g_eval_request = calculator.evaluate_request()
g_call = g_eval_request.expression.init("call")
g_call.function = g
g_call.init('params', 1)[0].literal = 21
g_call.init("params", 1)[0].literal = 21
g_eval_promise = g_eval_request.send().value.read()
# Wait for the results.
@@ -258,7 +260,7 @@ def main(host):
print("PASS")
'''Make a request that will call back to a function defined locally.
"""Make a request that will call back to a function defined locally.
Specifically, we will compute 2^(4 + 5). However, exponent is not
defined by the Calculator server. So, we'll implement the Function
@@ -270,12 +272,12 @@ def main(host):
particular case, this could potentially be optimized by using a tail
call on the server side -- see CallContext::tailCall(). However, to
keep the example simpler, we haven't implemented this optimization in
the sample server.'''
the sample server."""
print("Using a callback... ", end="")
# Get the "add" function from the server.
add = calculator.getOperator(op='add').func
add = calculator.getOperator(op="add").func
# Build the eval request for 2^(4+5).
request = calculator.evaluate_request()
@@ -298,5 +300,5 @@ def main(host):
print("PASS")
if __name__ == '__main__':
if __name__ == "__main__":
main(parse_args().host)

View File

@@ -8,29 +8,29 @@ import calculator_capnp
def read_value(value):
'''Helper function to asynchronously call read() on a Calculator::Value and
"""Helper function to asynchronously call read() on a Calculator::Value and
return a promise for the result. (In the future, the generated code might
include something like this automatically.)'''
include something like this automatically.)"""
return value.read().then(lambda result: result.value)
def evaluate_impl(expression, params=None):
'''Implementation of CalculatorImpl::evaluate(), also shared by
"""Implementation of CalculatorImpl::evaluate(), also shared by
FunctionImpl::call(). In the latter case, `params` are the parameter
values passed to the function; in the former case, `params` is just an
empty list.'''
empty list."""
which = expression.which()
if which == 'literal':
if which == "literal":
return capnp.Promise(expression.literal)
elif which == 'previousResult':
elif which == "previousResult":
return read_value(expression.previousResult)
elif which == 'parameter':
elif which == "parameter":
assert expression.parameter < len(params)
return capnp.Promise(params[expression.parameter])
elif which == 'call':
elif which == "call":
call = expression.call
func = call.function
@@ -39,9 +39,9 @@ def evaluate_impl(expression, params=None):
joinedParams = capnp.join_promises(paramPromises)
# When the parameters are complete, call the function.
ret = (joinedParams
.then(lambda vals: func.call(vals))
.then(lambda result: result.value))
ret = joinedParams.then(lambda vals: func.call(vals)).then(
lambda result: result.value
)
return ret
else:
@@ -61,28 +61,30 @@ class ValueImpl(calculator_capnp.Calculator.Value.Server):
class FunctionImpl(calculator_capnp.Calculator.Function.Server):
'''Implementation of the Calculator.Function Cap'n Proto interface, where the
function is defined by a Calculator.Expression.'''
"""Implementation of the Calculator.Function Cap'n Proto interface, where the
function is defined by a Calculator.Expression."""
def __init__(self, paramCount, body):
self.paramCount = paramCount
self.body = body.as_builder()
def call(self, params, _context, **kwargs):
'''Note that we're returning a Promise object here, and bypassing the
"""Note that we're returning a Promise object here, and bypassing the
helper functionality that normally sets the results struct from the
returned object. Instead, we set _context.results directly inside of
another promise'''
another promise"""
assert len(params) == self.paramCount
# using setattr because '=' is not allowed inside of lambdas
return evaluate_impl(self.body, params).then(lambda value: setattr(_context.results, 'value', value))
return evaluate_impl(self.body, params).then(
lambda value: setattr(_context.results, "value", value)
)
class OperatorImpl(calculator_capnp.Calculator.Function.Server):
'''Implementation of the Calculator.Function Cap'n Proto interface, wrapping
basic binary arithmetic operators.'''
"""Implementation of the Calculator.Function Cap'n Proto interface, wrapping
basic binary arithmetic operators."""
def __init__(self, op):
self.op = op
@@ -92,16 +94,16 @@ class OperatorImpl(calculator_capnp.Calculator.Function.Server):
op = self.op
if op == 'add':
if op == "add":
return params[0] + params[1]
elif op == 'subtract':
elif op == "subtract":
return params[0] - params[1]
elif op == 'multiply':
elif op == "multiply":
return params[0] * params[1]
elif op == 'divide':
elif op == "divide":
return params[0] / params[1]
else:
raise ValueError('Unknown operator')
raise ValueError("Unknown operator")
class CalculatorImpl(calculator_capnp.Calculator.Server):
@@ -109,7 +111,9 @@ 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)))
return evaluate_impl(expression).then(
lambda value: setattr(_context.results, "value", ValueImpl(value))
)
def defFunction(self, paramCount, body, _context, **kwargs):
return FunctionImpl(paramCount, body)
@@ -119,9 +123,11 @@ class CalculatorImpl(calculator_capnp.Calculator.Server):
def parse_args():
parser = argparse.ArgumentParser(usage='''Runs the server bound to the\
parser = argparse.ArgumentParser(
usage="""Runs the server bound to the\
given address/port ADDRESS may be '*' to bind to all local addresses.\
:PORT may be omitted to choose a port automatically. ''')
:PORT may be omitted to choose a port automatically. """
)
parser.add_argument("address", help="ADDRESS[:PORT]")
@@ -137,5 +143,5 @@ def main():
time.sleep(0.001)
if __name__ == '__main__':
if __name__ == "__main__":
main()

View File

@@ -12,8 +12,10 @@ capnp.create_event_loop(threaded=True)
def parse_args():
parser = argparse.ArgumentParser(usage='Connects to the Example thread server \
at the given address and does some RPCs')
parser = argparse.ArgumentParser(
usage="Connects to the Example thread server \
at the given address and does some RPCs"
)
parser.add_argument("host", help="HOST:PORT")
return parser.parse_args()
@@ -21,10 +23,10 @@ at the given address and does some RPCs')
class StatusSubscriber(thread_capnp.Example.StatusSubscriber.Server):
'''An implementation of the StatusSubscriber interface'''
"""An implementation of the StatusSubscriber interface"""
def status(self, value, **kwargs):
print('status: {}'.format(time.time()))
print("status: {}".format(time.time()))
def start_status_thread(host):
@@ -44,14 +46,14 @@ def main(host):
status_thread.daemon = True
status_thread.start()
print('main: {}'.format(time.time()))
print("main: {}".format(time.time()))
cap.longRunning().wait()
print('main: {}'.format(time.time()))
print("main: {}".format(time.time()))
cap.longRunning().wait()
print('main: {}'.format(time.time()))
print("main: {}".format(time.time()))
cap.longRunning().wait()
print('main: {}'.format(time.time()))
print("main: {}".format(time.time()))
if __name__ == '__main__':
if __name__ == "__main__":
main(parse_args().host)

View File

@@ -12,18 +12,23 @@ class ExampleImpl(thread_capnp.Example.Server):
"Implementation of the Example threading Cap'n Proto interface."
def subscribeStatus(self, subscriber, **kwargs):
return capnp.getTimer().after_delay(10**9) \
.then(lambda: subscriber.status(True)) \
return (
capnp.getTimer()
.after_delay(10 ** 9)
.then(lambda: subscriber.status(True))
.then(lambda _: self.subscribeStatus(subscriber))
)
def longRunning(self, **kwargs):
return capnp.getTimer().after_delay(1 * 10**9)
return capnp.getTimer().after_delay(1 * 10 ** 9)
def parse_args():
parser = argparse.ArgumentParser(usage='''Runs the server bound to the\
parser = argparse.ArgumentParser(
usage="""Runs the server bound to the\
given address/port ADDRESS may be '*' to bind to all local addresses.\
:PORT may be omitted to choose a port automatically. ''')
:PORT may be omitted to choose a port automatically. """
)
parser.add_argument("address", help="ADDRESS[:PORT]")
@@ -39,5 +44,5 @@ def main():
time.sleep(0.001)
if __name__ == '__main__':
if __name__ == "__main__":
main()