xmlrpc.serverBasic XML-RPC servers基本XML-RPC服务器

Source code: Lib/xmlrpc/server.py


The xmlrpc.server module provides a basic server framework for XML-RPC servers written in Python. xmlrpc.server模块为用Python编写的XML-RPC服务器提供了一个基本的服务器框架。Servers can either be free standing, using SimpleXMLRPCServer, or embedded in a CGI environment, using CGIXMLRPCRequestHandler.服务器可以是独立的,使用SimpleXMLRPCServer,也可以嵌入到CGI环境中,使用CGIXMLRPCRequestHandler

Warning

The xmlrpc.server module is not secure against maliciously constructed data. xmlrpc.server模块对恶意构建的数据不安全。If you need to parse untrusted or unauthenticated data see XML vulnerabilities.如果需要解析不受信任或未经身份验证的数据,请查看XML漏洞

classxmlrpc.server.SimpleXMLRPCServer(addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, use_builtin_types=False)

Create a new server instance. 创建一个新的服务器实例。This class provides methods for registration of functions that can be called by the XML-RPC protocol. 这个类提供了可以由XML-RPC协议调用的函数的注册方法。The requestHandler parameter should be a factory for request handler instances; it defaults to SimpleXMLRPCRequestHandler. The addr and requestHandler parameters are passed to the socketserver.TCPServer constructor. If logRequests is true (the default), requests will be logged; setting this parameter to false will turn off logging. The allow_none and encoding parameters are passed on to xmlrpc.client and control the XML-RPC responses that will be returned from the server. The bind_and_activate parameter controls whether server_bind() and server_activate() are called immediately by the constructor; it defaults to true. Setting it to false allows code to manipulate the allow_reuse_address class variable before the address is bound. The use_builtin_types parameter is passed to the loads() function and controls which types are processed when date/times values or binary data are received; it defaults to false.

Changed in version 3.3:版本3.3中更改: The use_builtin_types flag was added.

classxmlrpc.server.CGIXMLRPCRequestHandler(allow_none=False, encoding=None, use_builtin_types=False)

Create a new instance to handle XML-RPC requests in a CGI environment. 创建一个新实例来处理CGI环境中的XML-RPC请求。The allow_none and encoding parameters are passed on to xmlrpc.client and control the XML-RPC responses that will be returned from the server. allow_noneencoding参数被传递到xmlrpc.client,并控制将从服务器返回的XML-RPC响应。The use_builtin_types parameter is passed to the loads() function and controls which types are processed when date/times values or binary data are received; it defaults to false.use_builtin_types参数被传递给loads()函数,并控制在接收日期/时间值或二进制数据时处理哪些类型;它默认为false

Changed in version 3.3:版本3.3中更改: The use_builtin_types flag was added.已添加use_builtin_types标志。

classxmlrpc.server.SimpleXMLRPCRequestHandler

Create a new request handler instance. 创建一个新的请求处理程序实例。This request handler supports POST requests and modifies logging so that the logRequests parameter to the SimpleXMLRPCServer constructor parameter is honored.此请求处理程序支持POST请求并修改日志记录,以便遵守SimpleXMLRPCServer构造函数参数的logRequests参数。

SimpleXMLRPCServer Objects

The SimpleXMLRPCServer class is based on socketserver.TCPServer and provides a means of creating simple, stand alone XML-RPC servers.SimpleXMLRPCServer类基于socketserver.TCPServer,提供了一种创建简单、独立的XML-RPC服务器的方法。

SimpleXMLRPCServer.register_function(function=None, name=None)

Register a function that can respond to XML-RPC requests. 注册一个可以响应XML-RPC请求的函数。If name is given, it will be the method name associated with function, otherwise function.__name__ will be used. 如果给定name,它将是与function相关联的方法名,否则将使用function.__name__name is a string, and may contain characters not legal in Python identifiers, including the period character.name是一个字符串,可能包含Python标识符中不合法的字符,包括句点字符。

This method can also be used as a decorator. 此方法也可以用作装饰器。When used as a decorator, name can only be given as a keyword argument to register function under name. 当用作装饰器时,name只能作为关键字参数提供,以便在name下注册functionIf no name is given, function.__name__ will be used.如果没有给出name,将使用function.__name__

Changed in version 3.7:版本3.7中更改: register_function() can be used as a decorator.可以用作装饰器。

SimpleXMLRPCServer.register_instance(instance, allow_dotted_names=False)

Register an object which is used to expose method names which have not been registered using register_function(). 注册一个对象,该对象用于公开尚未使用register_function()注册的方法名。If instance contains a _dispatch() method, it is called with the requested method name and the parameters from the request. 如果instance包含_dispatch()方法,则使用请求的方法名和请求中的参数来调用它。Its API is def _dispatch(self, method, params) (note that params does not represent a variable argument list). 它的API是def _dispatch(self, method, params)(注意,params并不表示变量参数列表)。If it calls an underlying function to perform its task, that function is called as func(*params), expanding the parameter list. 如果它调用一个底层函数来执行其任务,则该函数被称为func(*params),从而扩展参数列表。The return value from _dispatch() is returned to the client as the result. _dispatch()的返回值作为结果返回给客户端。If instance does not have a _dispatch() method, it is searched for an attribute matching the name of the requested method.如果instance没有_dispatch()方法,则会搜索与请求方法名称匹配的属性。

If the optional allow_dotted_names argument is true and the instance does not have a _dispatch() method, then if the requested method name contains periods, each component of the method name is searched for individually, with the effect that a simple hierarchical search is performed. 如果可选的allow_dotted_names参数为true,并且实例没有_dispatch()方法,则如果请求的方法名称包含句点,则会单独搜索方法名称的每个组件,从而执行简单的分层搜索。The value found from this search is then called with the parameters from the request, and the return value is passed back to the client.然后使用请求中的参数调用从该搜索中找到的值,并将返回值传递回客户端。

Warning

Enabling the allow_dotted_names option allows intruders to access your module’s global variables and may allow intruders to execute arbitrary code on your machine. Only use this option on a secure, closed network.启用allow_dotted_name选项允许入侵者访问模块的全局变量,并可能允许入侵者在您的计算机上执行任意代码。仅在安全、封闭的网络上使用此选项。

SimpleXMLRPCServer.register_introspection_functions()

Registers the XML-RPC introspection functions system.listMethods, system.methodHelp and system.methodSignature.注册XML-RPC内省函数system.listMethodssystem.methodHelpsystem.methodSignature

SimpleXMLRPCServer.register_multicall_functions()

Registers the XML-RPC multicall function system.multicall.注册XML-RPC多调用函数system.multicall

SimpleXMLRPCRequestHandler.rpc_paths

An attribute value that must be a tuple listing valid path portions of the URL for receiving XML-RPC requests. 一个属性值,它必须是一个元组,列出用于接收XML-RPC请求的URL的有效路径部分。Requests posted to other paths will result in a 404 “no such page” HTTP error. 发布到其他路径的请求将导致404“无此类页面”HTTP错误。If this tuple is empty, all paths will be considered valid. 如果此元组为空,则所有路径都将被视为有效。The default value is ('/', '/RPC2').默认值为('/', '/RPC2')

SimpleXMLRPCServer Example

Server code:

from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)

# Create server
with SimpleXMLRPCServer(('localhost', 8000),
requestHandler=RequestHandler) as server:
server.register_introspection_functions()

# Register pow() function; this will use the value of
# pow.__name__ as the name, which is just 'pow'.
server.register_function(pow)

# Register a function under a different name
def adder_function(x, y):
return x + y
server.register_function(adder_function, 'add')

# Register an instance; all the methods of the instance are
# published as XML-RPC methods (in this case, just 'mul').
class MyFuncs:
def mul(self, x, y):
return x * y

server.register_instance(MyFuncs())

# Run the server's main loop
server.serve_forever()

The following client code will call the methods made available by the preceding server:以下客户端代码将调用前面的服务器提供的方法:

import xmlrpc.client
s = xmlrpc.client.ServerProxy('http://localhost:8000')
print(s.pow(2,3)) # Returns 2**3 = 8
print(s.add(2,3)) # Returns 5
print(s.mul(5,2)) # Returns 5*2 = 10

# Print list of available methods
print(s.system.listMethods())

register_function() can also be used as a decorator. 也可以用作装饰器。The previous server example can register functions in a decorator way:前面的服务器示例可以用decorator方式注册函数:

from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)

with SimpleXMLRPCServer(('localhost', 8000),
requestHandler=RequestHandler) as server:
server.register_introspection_functions()

# Register pow() function; this will use the value of
# pow.__name__ as the name, which is just 'pow'.
server.register_function(pow)

# Register a function under a different name, using
# register_function as a decorator. *name* can only be given
# as a keyword argument.
@server.register_function(name='add')
def adder_function(x, y):
return x + y

# Register a function under function.__name__.
@server.register_function
def mul(x, y):
return x * y

server.serve_forever()

The following example included in the Lib/xmlrpc/server.py module shows a server allowing dotted names and registering a multicall function.Lib/xmlrpc/server.py模块中包含的以下示例显示了一个允许使用点名称并注册多调用函数的服务器。

Warning

Enabling the allow_dotted_names option allows intruders to access your module’s global variables and may allow intruders to execute arbitrary code on your machine. 启用allow_dotted_name选项允许入侵者访问模块的全局变量,并可能允许入侵者在您的计算机上执行任意代码。Only use this example only within a secure, closed network.仅在安全、封闭的网络中使用此示例。

import datetime
class ExampleService:
def getData(self):
return '42'

class currentTime:
@staticmethod
def getCurrentTime():
return datetime.datetime.now()

with SimpleXMLRPCServer(("localhost", 8000)) as server:
server.register_function(pow)
server.register_function(lambda x,y: x+y, 'add')
server.register_instance(ExampleService(), allow_dotted_names=True)
server.register_multicall_functions()
print('Serving XML-RPC on localhost port 8000')
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nKeyboard interrupt received, exiting.")
sys.exit(0)

This ExampleService demo can be invoked from the command line:此ExampleService演示可以从命令行调用:

python -m xmlrpc.server

The client that interacts with the above server is included in Lib/xmlrpc/client.py:与上述服务器交互的客户端包含在Lib/xmlrpc/client.py中:

server = ServerProxy("http://localhost:8000")
try:
print(server.currentTime.getCurrentTime())
except Error as v:
print("ERROR", v)

multi = MultiCall(server)
multi.getData()
multi.pow(2,9)
multi.add(1,2)
try:
for response in multi():
print(response)
except Error as v:
print("ERROR", v)

This client which interacts with the demo XMLRPC server can be invoked as:这个与演示XMLRPC服务器交互的客户端可以被调用为:

python -m xmlrpc.client

CGIXMLRPCRequestHandler

The CGIXMLRPCRequestHandler class can be used to handle XML-RPC requests sent to Python CGI scripts.CGIXMLRPCRequestHandler类可用于处理发送到Python CGI脚本的XML-RPC请求。

CGIXMLRPCRequestHandler.register_function(function=None, name=None)

Register a function that can respond to XML-RPC requests. 注册一个可以响应XML-RPC请求的函数。If name is given, it will be the method name associated with function, otherwise function.__name__ will be used. name is a string, and may contain characters not legal in Python identifiers, including the period character.

This method can also be used as a decorator. 此方法也可以用作装饰器。When used as a decorator, name can only be given as a keyword argument to register function under name. 当用作装饰器时,name只能作为关键字参数提供,以便在name下注册functionIf no name is given, function.__name__ will be used.如果没有给出name,将使用function.__name__

Changed in version 3.7:版本3.7中更改: register_function() can be used as a decorator.

CGIXMLRPCRequestHandler.register_instance(instance)

Register an object which is used to expose method names which have not been registered using register_function(). 注册一个对象,该对象用于公开尚未使用register_function()注册的方法名。If instance contains a _dispatch() method, it is called with the requested method name and the parameters from the request; the return value is returned to the client as the result. 如果实例包含_dispatch()方法,则使用请求的方法名和请求中的参数来调用它;返回值作为结果返回给客户端。If instance does not have a _dispatch() method, it is searched for an attribute matching the name of the requested method; if the requested method name contains periods, each component of the method name is searched for individually, with the effect that a simple hierarchical search is performed. 如果实例没有_dispatch()方法,则会搜索与请求方法名称匹配的属性;如果请求的方法名称包含句点,则会单独搜索方法名称的每个组成部分,从而执行简单的分层搜索。The value found from this search is then called with the parameters from the request, and the return value is passed back to the client.然后使用请求中的参数调用从该搜索中找到的值,并将返回值传递回客户端。

CGIXMLRPCRequestHandler.register_introspection_functions()

Register the XML-RPC introspection functions system.listMethods, system.methodHelp and system.methodSignature.注册XML-RPC内省函数system.listMethodssystem.methodHelpsystem.methodSignature

CGIXMLRPCRequestHandler.register_multicall_functions()

Register the XML-RPC multicall function system.multicall.注册XML-RPC多调用函数system.multicall

CGIXMLRPCRequestHandler.handle_request(request_text=None)

Handle an XML-RPC request. 处理XML-RPC请求。If request_text is given, it should be the POST data provided by the HTTP server, otherwise the contents of stdin will be used.如果给定了request_text,那么它应该是HTTP服务器提供的POST数据,否则将使用stdin的内容。

Example:

class MyFuncs:
def mul(self, x, y):
return x * y
handler = CGIXMLRPCRequestHandler()
handler.register_function(pow)
handler.register_function(lambda x,y: x+y, 'add')
handler.register_introspection_functions()
handler.register_instance(MyFuncs())
handler.handle_request()

Documenting XMLRPC server记录XMLRPC服务器

These classes extend the above classes to serve HTML documentation in response to HTTP GET requests. 这些类扩展了上述类,以响应HTTPGET请求提供HTML文档。Servers can either be free standing, using DocXMLRPCServer, or embedded in a CGI environment, using DocCGIXMLRPCRequestHandler.服务器可以是独立的,使用DocXMLRPCServer,也可以嵌入到CGI环境中,使用DocCGIXMLRPCRequestHandler

classxmlrpc.server.DocXMLRPCServer(addr, requestHandler=DocXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, use_builtin_types=True)

Create a new server instance. 创建一个新的服务器实例。All parameters have the same meaning as for SimpleXMLRPCServer; requestHandler defaults to DocXMLRPCRequestHandler.

Changed in version 3.3:版本3.3中更改: The use_builtin_types flag was added.

classxmlrpc.server.DocCGIXMLRPCRequestHandler

Create a new instance to handle XML-RPC requests in a CGI environment.创建一个新实例来处理CGI环境中的XML-RPC请求。

classxmlrpc.server.DocXMLRPCRequestHandler

Create a new request handler instance. 创建一个新的请求处理程序实例。This request handler supports XML-RPC POST requests, documentation GET requests, and modifies logging so that the logRequests parameter to the DocXMLRPCServer constructor parameter is honored.

DocXMLRPCServer Objects

The DocXMLRPCServer class is derived from SimpleXMLRPCServer and provides a means of creating self-documenting, stand alone XML-RPC servers. HTTP POST requests are handled as XML-RPC method calls. HTTP GET requests are handled by generating pydoc-style HTML documentation. This allows a server to provide its own web-based documentation.HTTP POST请求作为XML-RPC方法调用来处理。HTTPGET请求是通过生成pydoc风格的HTML文档来处理的。这允许服务器提供自己的基于web的文档。

DocXMLRPCServer.set_server_title(server_title)

Set the title used in the generated HTML documentation. This title will be used inside the HTML “title” element.设置生成的HTML文档中使用的标题。此标题将在HTML“title”元素中使用。

DocXMLRPCServer.set_server_name(server_name)

Set the name used in the generated HTML documentation. This name will appear at the top of the generated documentation inside a “h1” element.设置生成的HTML文档中使用的名称。这个名称将出现在“h1”元素中生成的文档的顶部。

DocXMLRPCServer.set_server_documentation(server_documentation)

Set the description used in the generated HTML documentation. This description will appear as a paragraph, below the server name, in the documentation.设置生成的HTML文档中使用的描述。此描述将在文档中显示为服务器名称下方的一段。

DocCGIXMLRPCRequestHandler

The DocCGIXMLRPCRequestHandler class is derived from CGIXMLRPCRequestHandler and provides a means of creating self-documenting, XML-RPC CGI scripts. DocCGIXMLRPCRequestHandler类派生自CGIXMLRPCRequestHandler,并提供了一种创建自文档XML-RPC CGI脚本的方法。HTTP POST requests are handled as XML-RPC method calls. HTTP POST请求作为XML-RPC方法调用来处理。HTTP GET requests are handled by generating pydoc-style HTML documentation. This allows a server to provide its own web-based documentation.HTTPGET请求是通过生成pydoc风格的HTML文档来处理的。这允许服务器提供自己的基于web的文档。

DocCGIXMLRPCRequestHandler.set_server_title(server_title)

Set the title used in the generated HTML documentation. This title will be used inside the HTML “title” element.设置生成的HTML文档中使用的标题。此标题将在HTML“title”元素中使用。

DocCGIXMLRPCRequestHandler.set_server_name(server_name)

Set the name used in the generated HTML documentation. This name will appear at the top of the generated documentation inside a “h1” element.设置生成的HTML文档中使用的名称。这个名称将出现在“h1”元素中生成的文档的顶部。

DocCGIXMLRPCRequestHandler.set_server_documentation(server_documentation)

Set the description used in the generated HTML documentation. This description will appear as a paragraph, below the server name, in the documentation.设置生成的HTML文档中使用的描述。此描述将在文档中显示为服务器名称下方的一段。