0

我有一个在 Python 中使用 zerorpc 的 RPC 服务器,以这种方式编写

import zerorpc
from service import Service

print('RPC server - loading')
def main():
    print('RPC server - main')
    s = zerorpc.Server(Service())
    s.bind("tcp://*:4242")
    s.run()

if __name__ == "__main__" : main()

当我创建客户端时它工作正常

import zerorpc, sys

client_rpc = zerorpc.Client()
client_rpc.connect("tcp://127.0.0.1:4242")
name = sys.argv[1] if len(sys.argv) > 1 else "dude"
print(client_rpc.videos('138cd9e5-3c4c-488a-9b6f-49907b55a040.webm'))

并运行它。print() 输出此“视频”函数返回的内容。

但是,当我尝试在 Flask 应用程序的路由中使用相同的代码时,我收到以下错误:

文件“src/gevent/__greenlet_primitives.pxd”,第 35 行,gevent.__greenlet_primitives._greenlet_switch gevent.exceptions.LoopExit:此操作将永远阻塞 Hub:

烧瓶方法/摘录

import zerorpc, sys

client_rpc = zerorpc.Client()
client_rpc.connect("tcp://127.0.0.1:4242")

@app.route('/videos', methods=['POST'])
def videos():

    global client_rpc
    client_rpc.videos('138cd9e5-3c4c-488a-9b6f-49907b55a040.webm')

我不知道会发生什么。我对 Python 很陌生,我知道这可能与 Flask 以及它如何处理线程有关,但我不知道如何解决它。

4

1 回答 1

0

zerorpc depends on gevent, which provides async IO with cooperative coroutines. This means your flask application must use gevent for all IO operations.

In your specific case, you are likely starting your application with a standard blocking IO WSGI server.

Here is a snippet using the WSGI server from gevent:

import zerorpc
from gevent.pywsgi import WSGIServer

app = Flask(__name__)

client_rpc = zerorpc.Client()
client_rpc.connect("tcp://127.0.0.1:4242")

@app.route('/videos', methods=['POST'])
def videos():
    global client_rpc
    client_rpc.videos('138cd9e5-3c4c-488a-9b6f-49907b55a040.webm')

# ...

if __name__ == "__main__":
    http = WSGIServer(('', 5000), app)
    http.serve_forever()

Excerpt from https://sdiehl.github.io/gevent-tutorial/#chat-server

于 2019-05-22T16:25:51.390 回答