Python XML RPC服務器端和客戶端實例
一、遠程過程調用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.
簡單地,client可以調用server上提供的方法,然后得到執(zhí)行的結果。類似與webservice。
推薦查看xmlprc的源文件:C:\Python31\Lib\xmlrpc
二、實例
1) Server
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
import xmlrpc.client
s = xmlrpc.client.ServerProxy('http://localhost:8000')
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
相關文章
Django admin 實現(xiàn)search_fields精確查詢實例
這篇文章主要介紹了Django admin 實現(xiàn)search_fields精確查詢實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03詳解pandas DataFrame的查詢方法(loc,iloc,at,iat,ix的用法和區(qū)別)
這篇文章主要介紹了詳解pandas DataFrame的查詢方法(loc,iloc,at,iat,ix的用法和區(qū)別),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-08-08在python中計算ssim的方法(與Matlab結果一致)
這篇文章主要介紹了在python中計算ssim的方法(與Matlab結果一致),本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12pytorch教程resnet.py的實現(xiàn)文件源碼分析
torchvision.models這個包中包含alexnet、densenet、inception、resnet、squeezenet、vgg等常用的網(wǎng)絡結構,并且提供了預訓練模型,可以通過簡單調用來讀取網(wǎng)絡結構和預訓練模型2021-09-09Python數(shù)據(jù)結構與算法之使用隊列解決小貓釣魚問題
這篇文章主要介紹了Python數(shù)據(jù)結構與算法之使用隊列解決小貓釣魚問題,結合實例形式分析了Python使用隊列實現(xiàn)小貓釣魚游戲的算法操作技巧,代碼中備有較為詳盡的注釋便于讀者理解,需要的朋友可以參考下2017-12-12