[Ifeffit] How to use Larch as function server

ASAKURA, Hiroyuki asakura at moleng.kyoto-u.ac.jp
Sat Mar 2 23:40:03 CST 2019


Dear all,

I would like to use Larch as an external function server.
I'm a Python novice, but if I understand correctly, the present server (larch -r) provides access to a Larch process controllable with xmlrpc from outside.

However, I would like to do something like below to achieve looser coupling with my future code (maybe not in python).
How can I do that?
I appreciate any suggestion for my first step to go, though I guess it is a bit far from the Larch way.

### client.py (not a working code)

from six.moves.xmlrpc_client import ServerProxy
import os, json

def main():
     s = ServerProxy("http://127.0.0.1:4966/", allow_none = True)
     
     response = s.read_ascii(os.path.abspath("/path/to/xas/data"))
     # I expect a JSON or python dict with keys like "energy", "mu", etc.
     
     data = response

     response = s.pre_edge(data)
     # data is a JSON or python dict with keys like "energy", "mu", etc.
     
if __name__ == '__main__':
     main()

### client.py end

I guess one can write some sort of function wrapper, if one wants.

### server.py (not a working code)

from six.moves.socketserver import ThreadingMixIn
from six.moves.xmlrpc_server import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler

import json

import larch

from larch_plugins.xafs import find_e0, pre_edge, autobk
from larch_plugins.io import read_ascii

class LarchServer(ThreadingMixIn, SimpleXMLRPCServer):
     def __init__(self, *args, **kw):
         super().__init__(*args, **kw)
         
         self.larch = larch.Interpreter(with_plugins=True)
         self.larch.run_init_scripts()
         
         self.register_introspection_functions()

class LarchRequestHandler(SimpleXMLRPCRequestHandler):
     def __init__(self, *args, **kw):
         super().__init__(*args, **kw)
         
     def _dispatch(self, method_name, args):
         return getattr(self, method_name)(*args)
     
     ### wrapper function to Larch function
     ### Do something nice to convert the file into processed data as JSON or a python dict
     def read_ascii(self, filepath):
         data = read_ascii(filepath, _larch=larch)
         
         # Return processed data as JSON, for example.
         return json.dumps(data)

def main():
     server = LarchServer( ("127.0.0.1", 4966),
                           requestHandler = LarchRequestHandler,
                           logRequests    = None,
                           allow_none     = True )
     
     server.serve_forever()

if __name__ == '__main__':
     main()

### server.py end


-- 
ASAKURA, Hiroyuki (Ph.D)
Program-Specific Senior Lecturer (ESICB)
T. Tanaka Lab., ESICB, Kyoto University, Japan
asakura at moleng.kyoto-u.ac.jp
http://www.moleng.kyoto-u.ac.jp/~moleng_04/asakura/


More information about the Ifeffit mailing list