安装Jina
pip install -U jina
服务端python
server.py
:
from jina import Flow, Document, Executor, requests,DocumentArray
class MyExecutor(Executor):
@requests(on='/bar')
def foo(self, docs:DocumentArray, **kwargs):
#ret = DocumentArray()
print("修改前:",docs.texts)
#docs = DocumentArray([Document(text='The cake is a lie'), Document(text='Do a barrel roll!')])
docs.append(Document(text='aha, the cake is a lie'))
print("修改后:",docs.texts)
return docs
f = Flow(port_expose=12345).add(name='myexec1', uses=MyExecutor)
if __name__ == '__main__':
with f:
# backend server forever
f.block()
注意:必须加上if __name__ == '__main__':
,否则会报RuntimeError错误:
RuntimeError:
An attempt has been made to start a new process before thecurrent process has finished its bootstrapping phase.
This probably means that you are not using fork to start yourchild processes and you have forgotten to use the proper idiomin the main module :
ifname_"Imainfreeze_support()
The "freeze_support()" line can be omitted if the programis not going to be frozen to produce an executable.
客户端
client.py
:
from jina import Client, Document,DocumentArray
c = Client(port=12345)
docs = DocumentArray([Document(text='Here is a delicious cake.')])
resp = c.post(on='/bar', inputs=docs)
print("resp:",resp)
print("resp.texts:",resp.texts)
运行效果:
server端:
D:\textCompare>python serverComp.py
─────────────────────────────── 🎉 Flow is ready to serve! ────────────────────────────────
╭────────────── 🔗 Endpoint ───────────────╮
│ ⛓ Protocol GRPC │
│ 🏠 Local 127.0.0.1:12345 │
│ 🔒 Private 172.17.29.48:12345 │
╰──────────────────────────────────────────╯
修改前: ['Here is a delicious cake.']
修改后: ['Here is a delicious cake.', 'aha, the cake is a lie']
client端:
D:\textCompare>python clientComp.py
resp: <DocumentArray (length=2) at 2071732501376>
resp.texts: ['Here is a delicious cake.', 'aha, the cake is a lie']
从yaml
文件加载服务配置
my.yaml
:
jtype: Flow
executors:
- name: myexec1
uses: MyExecutor
客户端
client.py
:
from jina import Flow, Document
f = Flow.load_config('my.yml')
with f:
f.post(on='/bar', inputs=Document(text='this is a test'))
注意:客户端和服务端交换的数据,必须包装成DocumentArray
类型