关于Python中的XML-RPC的远程调用的一些笔记

python 官方文档:
https://docs.python.org/2/library/xmlrpclib.html

https://python-documentation-cn.readthedocs.org/en/latest/library/xmlrpc.server.html#module-xmlrpc.server


1. 基本使用

Client端

  import xmlrpclib
  client_obj=xmlrpclib.ServerProxy("http://localhost:8888",allow_none=True)
    try:
        func=getattr(client_obj,"Multiply")
        answer=func(21,10)
        print answer
    except xmlrpclib.Fault, e:
        print e

Server端

    import server_action
    from SimpleXMLRPCServer import SimpleXMLRPCServer
    server=SimpleXMLRPCServer(("localhost",8888))
    server.register_function(server_action.Multiply)
    server.serve_forever()

对于服务器端:

  1. import SimpleXMLRPCServer
  2. 确定url 和 port 口
  3. register_function or register_instance
  4. serve_forever()

对于客户端:

  1. import xmrpclib
  2. 使用 xmlrpclib.Serverproxy((url,port))
  3. 得到的对象来调用服务器端的方法

2. 传输文件

http://blog.csdn.net/ustbhacker/article/details/6098808

传输中要用xmlrpclib.Binary包装数据,接收端需要用Binary.data返回原始数据并保存。

  1. 先将要传输的文件,读取出来。open
  2. 利用xmlroclib.binary()将1中得到的放入其中
  3. 传到另外一端后,要将得到的文件进行存储。 write(binary.date)

client端

import xmlrpclib

proxy = xmlrpclib.ServerProxy("http://localhost:8888",allow_none=True)
#recieve
func=getattr(proxy,'sendFile')
filename="python-logo.png"
getDate=func(filename)
with open("recieved_from_server.png", "wb") as handle: 
    handle.write(getDate.data)

Server端

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: anchen
# @Date:   2016-03-17 14:01:54
# @Last Modified by:   anchen
# @Last Modified time: 2016-03-17 15:20:21
from SimpleXMLRPCServer import SimpleXMLRPCServer
import xmlrpclib
import os 

class FileOp(object):
    def __init__(self,path):
        self.path=path
    def sendFile(self,filename):
        self.the_file=self.path+filename
        if os.path.isfile(self.the_file):
            with open (self.the_file,'rb') as handle:
                return xmlrpclib.Binary(handle.read())
            print "the file have been sent!!"
        else:
            print "no such file in the directory!"
            

server=SimpleXMLRPCServer(("localhost",8888))
file_operate=FileOp(r'C:\Users\chch\Downloads\\')
server.register_instance(file_operate)
server.serve_forever()

有些语言描述可能不怎么准确,妄指正!谢谢!

你可能感兴趣的:(关于Python中的XML-RPC的远程调用的一些笔记)