msgpack-rpc / msgpack-rpc-python

MessagePack RPC implementation for Python
205 stars 72 forks source link

AsyncResult is located in msgpack.server #11

Closed dniku closed 8 years ago

dniku commented 9 years ago

Currently a non-blocking server would look like this:

import multiprocessing, time, threading
import msgpackrpc

# Why is this core thing buried deep in a random module?
from msgpackrpc.server import AsyncResult

def run_threaded(result, x, y):
    time.sleep(1)
    result.set_result(x + y)

class SumServer(object):
    def sum(self, x, y):
        result = AsyncResult()
        thread = threading.Thread(target=run_threaded, args=(result, x, y))
        thread.start()
        return result

def server():
    server = msgpackrpc.Server(SumServer())
    server.listen(msgpackrpc.Address("localhost", 4000))
    server.start()

def client():
    client = msgpackrpc.Client(msgpackrpc.Address("localhost", 4000))
    future = client.call_async('sum', 1, 2)
    print(future.get())

def main():
    proc_server = multiprocessing.Process(target=server)
    proc_server.start()

    time.sleep(1)

    try:
        client()
    finally:
        proc_server.terminate()

if __name__ == '__main__':
    main()

In my opinion, this is a design problem: AsyncResult, which is essential to writing asynchronous servers, is contained in a non-top-level module. Is it possible to move it to the top level, for example, by importing from __init__.py?

repeatedly commented 8 years ago

Is it possible to move it to the top level

I don't think top-level is best place because msgpackrpc.server.AyncResult is used with only msgpackrpc.server.Server related code, not general use.

dniku commented 8 years ago

In that case, what would be the proper way to implement a non-blocking server?

repeatedly commented 8 years ago

It depends on your application. Using AsyncResult with thread, non-blocking libraries or etc. msgpack-rpc-python is based on tornado so you can use tornado directly for network access.