What is it?
XML-RPC is a Remote Procedure Call method that uses XML
passed via HTTP(S) as a transport. With it, a client can call methods with
parameters on a remote server (the server is named by a URI) and get back
structured data. This module supports writing XML-RPC client code; it handles
all the details of translating between conformable Python objects and XML on
the wire.
XML-RPC is a package that collects server and client
modules implementing XML-RPC. The modules are:
In this article, we will see the basics of the library and
implement a python program with a client-server architecture in which the client
will send a string and the server will calculate the number of vowels in the string
and send back the same response.
Now lets look at the SimpleXMLRPCServer in xmlrpclib.
The SimpleXMLRPCServer module contains classes for creating your own cross-platform, language-independent server using the XML-RPC protocol. Client libraries exist for many other languages, making XML-RPC an easy choice for building RPC-style services.
Lets create a SimpleXMLRPCServer:
from xmlrpc.server import SimpleXMLRPCServer
import logging
import os
# Set up logging
logging.basicConfig(level=logging.DEBUG)
server = SimpleXMLRPCServer(('localhost', 9000), logRequests=True)
try:
print('Server is running...')
server.serve_forever()
except KeyboardInterrupt:
print('Exiting')
So we have successfully made a server program, now we need to make a client that can make a request to the server, and then the server can make a response and send it back to the client.
For that, we import the xmlrpc.client and define a proxy server to make the requests.
Client:
import xmlrpc.client as xmlrpclib
with xmlrpclib.ServerProxy("http://localhost:8000/") as proxy:
print("Vowels in Hello World:",str(proxy.get_num_vowels("Hello World")))
print("Vowels in Python Programming:", str(proxy.get_num_vowels("Python Programming")))
Server:
from xmlrpc.server import SimpleXMLRPCServer
def get_num_vowels(s):
vowels=0
for char in s:
if char.lower() in ['a', 'e', 'i', 'o', 'u']:
vowels+=1
return vowels
try:
server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(get_num_vowels, "get_num_vowels")
server.serve_forever()
except Exception as e:
print(e)
Outputs:
Name | Views | Likes |
---|---|---|
Server Client program with xmlrpclib Python | 345 | 0 |
Alive Progress Bar | 3019 | 1 |
Annotate Bars in Barplot with Matplotlib in Python? | 2978 | 0 |
Comments