oSparc 文件通信
项目描述
oSparc 文件通信 Python 库
这个库旨在在oSparc服务中运行的Python代码之间执行基于文件的稳定通信。
安装
pip install osparc-filecomms
握手使用
通过握手,两个服务可以交换对方的ID,并保证另一侧的服务是活跃的。该协议有一个“发起者”和一个“接收者”。
from osparc-filecomms import handshakers
import uuid
# Existing input/output directories
input_dir = Path("input_dir")
output_dir = Path("output_dir")
my_uuid = str(uuid.uuid4())
is_initiator = True # Change this according to if you are the initiator or the receiver
handshaker = handshakers.FileHandshaker(my_uuid, input_dir, output_dir, is_initiator=is_initiator)
other_side_uuid = handshaker.shake()
print(f"I performed a handshake. My uuid is: {my_uuid}. The other side's uuid is: {other_side_uuid}")
在此代码在双方运行后,可以在这两个uuid中交换数据文件。如果访问这些文件的过程确保接收者和发送者uuid匹配,他们可以确信文件来自另一个活跃的服务。例如,要发送一个文件
import json
output_file_path = output_dir \ 'some_data.json'
data = [4, 3]
file_content = {
'sender_uuid': my_uuid,
'receiver_uuid': other_side_uuid,
'data': data
}
output_file_path.write_text(json.dumps(file_content))
然后,另一个进程可以使用以下方法接收它
import json
input_file_path = input_dir \ 'some_data.json'
sender_uuid = None
receiver_uuid = None
while receiver_uuid != my_uuid and sender_uuid != other_side_uuid:
while not input_file_path.exists():
time.sleep(1)
file_content = json.loads(input_file_path.read_text())
receiver_uuid = file_content['receiver_uuid']
sender_uuid = file_content['sender_uuid']
data = file_content['data']