摘要:主要是两个Pyro4入门的例子,作为Pyro4的初步入门认识。记得要把NS开启,不然会出错。
Pyro4官网:https://pythonhosted.org/Pyro4/index.html
安装:pip install Pyro4
Demo01:
来自官网的一个例子:
服务器端:
# saved as greeting-server.py
import Pyro4
# greeting-server 服务器
@Pyro4.expose
class GreetingMaker(object):
def get_fortune(self, name):
return "Hello, {0}. Here is your fortune message:\n" \
"Behold the warranty -- the bold print giveth and the fine print taketh away.".format(name)
# 运行一个进程
daemon = Pyro4.Daemon() # make a Pyro daemon
# 把GreetingMaker注册成Pyro object对像
uri = daemon.register(GreetingMaker) # register the greeting maker as a Pyro object
print("Ready. Object uri =", uri) # print the uri so we can use it in the client later
# 等待被调用
daemon.requestLoop() # start the event loop of the server to wait for calls
运行服务器:
Ready. Object uri = PYRO:obj_85156a856ff94ef29fbb9be41aea36b5@localhost:52500
客户端:
# saved as greeting-client.py
import Pyro4
# 输入Pyro对象的URI
uri = input("What is the Pyro uri of the greeting object? ").strip()
name = input("What is your name? ").strip()
# 获取一个远程的代理对象
greeting_maker = Pyro4.Proxy(uri) # get a Pyro proxy to the greeting object
# 远程调用
print(greeting_maker.get_fortune(name)) # call method normally
运行行客户端:
What is the Pyro uri of the greeting object? PYRO:obj_85156a856ff94ef29fbb9be41aea36b5@localhost:52500
What is your name? dd
Hello, dd. Here is your fortune message:
Behold the warranty -- the bold print giveth and the fine print taketh away.
Demo02 增加名字服务器:
名字服务器的启动有多个方式的,可以在控制台或自已的代码控制的,可参见:http://pythonhosted.org/Pyro4/nameserver.html,下面从控制台启动
1). 启动Pyro4的名字服务器:
python -m Pyro4.naming
查看:python -m Pyro4.nsc list
2) 代码
服务器端:
# saved as greeting-server.py
import Pyro4
# greeting-server 服务器
@Pyro4.expose
class GreetingMaker(object):
def get_fortune(self, name):
return "Hello, {0}. Here is your fortune message:\n" \
"Behold the warranty -- the bold print giveth and the fine print taketh away.".format(name)
# 获取本地名字服务器
ns = Pyro4.locateNS() # find the name server
# 运行一个后台进程
daemon = Pyro4.Daemon() # make a Pyro daemon
# 把GreetingMaker注册成Pyro object对像
uri = daemon.register(GreetingMaker) # register the greeting maker as a Pyro object
# 把uri注册到名字服务器
ns.register("example.greeting", uri) # register the object with a name in the name server
# 等待被调用
daemon.requestLoop() # start the event loop of the server to wait for calls
客户端:
# saved as greeting-client.py
import Pyro4
# 输入Pyro对象的URI
name = 'zhang'
# 获取一个远程的代理对象
greeting_maker = Pyro4.Proxy('PYRONAME:example.greeting')
# 远程调用
print(greeting_maker.get_fortune(name))
查看一下名称服务器,发现多了一行记录,对象已经被注册上去了。
【作者:happyprince, http://blog.csdn.net/ld326/article/details/78467885】