12.11.7 自省API
与很多网络服务一样,可以查询一个XML-RPC服务器来确定它支持哪些方法,并了解如何使用这些方法。SimpleXMLRPCServer包括一组用于完成这个自省的公共方法。默认地,这些方法是关闭的,不过可以用register_introspection_functions()启用。通过在服务类上定义_listMethods()和_methodHelp(),可以在服务中增加对system.listMethods()和system.methodHelp()的支持。
from xmlrpc.server import SimpleXMLRPCServer,list_public_methods
import os
import inspect
server = SimpleXMLRPCServer(
('localhost',9000),
logRequests=True,
)
server.register_introspection_functions()
class DirectoryService:
def _listMethods(self):
return list_public_methods(self)
def methodHelp(self,method):
f = getattr(self,method)
return inspect.getdoc(f)
def list(self,dir_name):
"""list(dir_name) => [<filenames>]
Returns a list containing the contents of
the named directory.
"""
return os.listdir(dir_name)
server.register_instance(DirectoryService())
try:
print('Use Control-C to exit')
server.serve_forever()
except KeyboardInterrupt:
pritn('Exiting')
在这里,便利函数list_public_methods()扫描一个实例,返回不是以下划线(_)开头的可调用属性的名字。重新定义_listMethods()来应用所需的规则。类似地,对于这个基本例子,_methodHelp()返回了函数的docstring,不过也可以写为从其他来源构建一个帮助文本串。
这个客户会查询服务器,并报告所有可公开调用的方法。
import xmlrpc.client
proxy = xmlrpc.client.ServerProxy('http://localhost:9000')
for method_name in proxy.system.listMethods():
print('=' * 60)
print(method_name)
print('-' * 60)
print(proxy.system.methodHelp(method_name))
print()
结果中还包含了系统方法。
运行结果: