How to register function in a class rather than one by one use jsonrpclib by python?

460 Views Asked by At

In jsonrpclib docs, example is register function one by one as this:

def foo():
    pass

def bar():
    pass

server = SimpleJSONRPCServer(("localhost", 8000))
server.register_multicall_functions()
server.register_function(foo, 'foo')
server.register_function(bar, 'bar')

It can work but not pythonic. Register functions one by one is intricate after all.

Are there some examples to register functions in a class or other pythonic way at one time. Such as:

class Api(object):
    def foo():
        pass

    def bar():
        pass

def SomeMagic():
    # register all function in Api
    server.register_function(Api)
1

There are 1 best solutions below

0
Wilence On

An idea has come to my mind. Most important is dir() built-in function.

# api.py
def foo():
    pass

def bar():
    pass


# main.py
import api

def register_api(server, api_obj):
    methods = dir(api_obj)
    apis = filter(lambda m: not m.startswith('_'), methods)
    [server.register_function(getattr(api_obj, api)) for api in apis]

def main():
    endpoint = (LISTEN_ADDR, LISTEN_PORT) 
    server = SimpleJSONRPCServer(endpoint)
    register_api(server, api)
    server.serve_forever()