Hello:
I created a simple RPC server to perform certain tasks common to our teams, but which are called from different networks. The server looks like this (I don't include error handling for brevity):
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
import json
class MyProtocol(Protocol):
def dataReceived(self, data):
req = json.loads(data) # create a dictionary from JSON string
method = getattr(self, req['method']) # get the method
method(req['params']) # call the method
def add(self, params):
result = {} # initialize a dictionary to convert later to JSON
result['result'] = sum(params)
result['error'] = None
result['id'] = 1
self.transport.write(json.dumps(result)) # return a JSON string
self.transport.loseConnection() # close connection
factory = Factory()
factory.protocol = MyProtocol
reactor.listenTCP(8080, factory)
reactor.run()
This is very simple: the server receives a JSON RPC request from the client, looks for the method, and calls the method passing the parameters. The method itself is the one returning the JSON RPC response. For the less familiar, a JSON RPC looks approximately like this:
request:
{"method":"my_method", "params":[1,2,3], "id":"my_id"}
response:
{"result":"my_result", "error":null, "id":"my_id"}
The RPC server as I have it serves my current purposes very well (as you can imagine, my task is very simple). But I will need to continue adding methods as the complexity of the task increases.
I don't want to open the main file and add yet another def method3(...)
and, two weeks later, add def method4(...)
and so forth; the code would grow too quickly and the maintenance would be harder and harder.
So, my question is: how can I create an architecture that allows me to register methods into the Server. A bonus would be to have a separate folder holding one file per method, so that they can easily be shared and maintained. This "architecture" would also allow me to defer maintenance of some methods to someone else, regardless of their understanding of Twisted.
I don't care if I need to restart the server every time a new method is registered, but an obvious plus would be if I don't have too :).
Thanks.