[英]How to send a xml-rpc request in python?
I was just wondering, how would I be able to send a xml-rpc
request in python? 我只是想知道,我如何能够在python中发送
xml-rpc
请求? I know you can use xmlrpclib
, but how do I send out a request in xml
to access a function? 我知道您可以使用
xmlrpclib
,但是如何在xml
发出请求以访问函数呢?
I would like to see the xml
response. 我希望看到
xml
响应。
So basically I would like to send the following as my request to the server: 所以基本上我想将以下内容作为请求发送到服务器:
<?xml version="1.0"?>
<methodCall>
<methodName>print</methodName>
<params>
<param>
<value><string>Hello World!</string></value>
</param>
</params>
</methodCall>
and get back the response 并得到回应
Here's a simple XML-RPC client in Python: 这是Python中的一个简单XML-RPC客户端:
import xmlrpclib
s = xmlrpclib.ServerProxy('http://localhost:8000')
print s.myfunction(2, 4)
Works with this server: 适用于此服务器:
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
# Create server
server = SimpleXMLRPCServer(("localhost", 8000),
requestHandler=RequestHandler)
def myfunction(x, y):
status = 1
result = [5, 6, [4, 5]]
return (status, result)
server.register_function(myfunction)
# Run the server's main loop
server.serve_forever()
To access the guts of xmlrpclib
, ie looking at the raw XML requests and so on, look up the xmlrpclib.Transport
class in the documentation. 要访问
xmlrpclib
,即查看原始XML请求等,请在文档中查找xmlrpclib.Transport
类。
I have pared down the source code in xmlrpc.client to a minimum required to send a xml rpc request (as I was interested in trying to port the functionality). 我已将xmlrpc.client中的源代码缩减到发送xml rpc请求所需的最低限度(因为我有兴趣尝试移植功能)。 It returns the response XML.
它返回响应XML。
Server: 服务器:
from xmlrpc.server import SimpleXMLRPCServer
def is_even(n):
return n%2 == 0
server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(is_even, "is_even")
server.serve_forever()
Client: 客户:
import http.client
request_body = b"<?xml version='1.0'?>\n<methodCall>\n<methodName>is_even</methodName>\n<params>\n<param>\n<value><int>2</int></value>\n</param>\n</params>\n</methodCall>\n"
connection = http.client.HTTPConnection('localhost:8000')
connection.putrequest('POST', '/')
connection.putheader('Content-Type', 'text/xml')
connection.putheader('User-Agent', 'Python-xmlrpc/3.5')
connection.putheader("Content-Length", str(len(request_body)))
connection.endheaders(request_body)
print(connection.getresponse().read())
What do you mean by "get around"? 你说“走开”是什么意思? xmlrpclib is the normal way to write an XML-RPC client in python.
xmlrpclib是在python中编写XML-RPC客户端的常规方法。 Just look at the sources (or copy them to your own module and add
print
statements!-) if you want to know the details of how things are done. 如果您想了解事情的详细信息,只需查看源文件 (或将它们复制到自己的模块中并添加
print
语句!-)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.