Python xml rpc server and client instance, pythonrpc

Source: Internet
Author: User

Python xml rpc server and client instance, pythonrpc

I. Remote Procedure Call RPC

XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP 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.

In short, the client can call the methods provided on the server and obtain the execution result. Similar to webservice.

We recommend that you check the xmlprc source file: C: \ Python31 \ Lib \ xmlrpc.

Ii. Instances

1) Server

Copy codeThe Code is as follows:

From xmlrpc. server import SimpleXMLRPCServer
From xmlrpc. server import SimpleXMLRPCRequestHandler

Def div (x, y ):
Return x-y

Class Math:
Def _ listMethods (self ):
# This method must be present for system. listMethods
# To work
Return ['add', 'pow']
Def _ methodHelp (self, method ):
# This method must be present for system. methodHelp
# To work
If method = 'add ':
Return "add (2, 3) => 5"
Elif method = 'pow ':
Return "pow (x, y [, z]) => number"
Else:
# By convention, return empty
# String if no help is available
Return ""
Def _ dispatch (self, method, params ):
If method = 'pow ':
Return pow (* params)
Elif method = 'add ':
Return params [0] + params [1]
Else:
Raise 'bad Method'

Server = SimpleXMLRPCServer ("localhost", 8000 ))
Server. register_introspection_functions ()
Server. register_function (div, "div ")
Server. register_function (lambda x, y: x * y, 'multiply ')
Server. register_instance (Math ())
Server. serve_forever ()

2) client

Copy codeThe Code is as follows:

Import xmlrpc. client

S = xmlrpc. client. ServerProxy ('HTTP: // localhost: 8080 ')

Print (s. system. listMethods ())

Print (s. pow (2, 3) # Returns 28
Print (s. add (2, 3) # Returns 5
Print (s. div (3, 2) # Returns 1
Print (s. multiply (4, 5) # Returns 20

3) result

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.