将 gevent 与 python xmlrpclib 结合使用
是否可以将 python 的标准库 xmlrpclib 与 gevent 一起使用?目前我尝试使用monkey.patch_all(),但没有成功。
from gevent import monkey
monkey.patch_all()
import gevent
import time
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
import urllib2
def fetch(url):
g = gevent.spawn(urllib2.urlopen, url)
return g.get().read()
def is_even(n):
return n%2 == 0
def req(url):
return fetch(url)
server = SimpleXMLRPCServer(("localhost", 8000))
print "Listening on port 8000..."
server.register_function(is_even, "is_even")
server.register_function(req, "req")
server.serve_forever()
urllib2.urlopen 正在阻止服务器。在我看来,monkey.patch_all 没有修补套接字,这就是它阻塞的原因。
Is it possible to use python's standard libs xmlrpclib with gevent? Currently i'm tried to use monkey.patch_all(), but without success.
from gevent import monkey
monkey.patch_all()
import gevent
import time
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
import urllib2
def fetch(url):
g = gevent.spawn(urllib2.urlopen, url)
return g.get().read()
def is_even(n):
return n%2 == 0
def req(url):
return fetch(url)
server = SimpleXMLRPCServer(("localhost", 8000))
print "Listening on port 8000..."
server.register_function(is_even, "is_even")
server.register_function(req, "req")
server.serve_forever()
urllib2.urlopen is blocking server. It looks to me, that monkey.patch_all did not patched socket, that's why it blocks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
套接字已修补得很好,但您的代码还存在其他问题。
首先,这
一样
与您在这里生成一个新的 greenlet 但然后阻止当前的 greenlet 直到新的 greenlet 完成 。它不会使事情并发。这与运行 urlopen 并等待其完成完全相同。
其次,为了利用 gevent,必须有多个轻量级线程 (greenlet) 同时运行。
然而,SimpleXMLRPCServer 的定义意味着
它一次为一个连接提供服务。
如果您创建自己的
SimpleXMLRPCServer
类,但使用ThreadingTCPServer
而不是TCPServer
,那么您应该能够从此处使用 gevent 中受益。monkey.patch_all()
修补线程
,使其成为基于 greenlet 的,因此此类服务器将为每个新连接生成一个新的 greenlet。The socket is patched fine, but there are other problems with your code.
First, this
is the same as
You're spawning a new greenlet here but then blocking the current one until that new one is done. It does not make things concurrent. It's exactly the same as just running urlopen and waiting for it to finish.
Second, in order to take advantage of gevent there got to be more than one lightweight thread (greenlet) running at the same time.
SimpleXMLRPCServer, however, is defined as
which means it serves one connection at a time.
If you make your own
SimpleXMLRPCServer
class, but useThreadingTCPServer
instead ofTCPServer
, you should be able to benefit from using gevent here.monkey.patch_all()
patchesthreading
to become greenlet-based, so such server will spawn a new greenlet for each new connection.