siyuan-实时同步
项目介绍
项目作者:muhanstudio
预览效果
实现过程
这个 Express.js 应用通过 push 和 pull 两种操作实现了简单的数据存储和读取功能,所有数据都存储在一个 JSON 文件中,并根据客户端的请求动态更新和返回数据。它适合用作简单的 API 服务,能够接受并处理来自客户端的请求,同时维护一定的用户状态。
封装Docker
git clone https://github.com/muhanstudio/siyuan-sync-aware-serve.git
cd siyuan-sync-aware-serve
cat >> Dockerfile << "EOF"
# 使用官方 Node.js 镜像作为基础镜像
FROM node:14
# 指定工作目录
WORKDIR /app
# 复制文件
COPY package*.json ./
# 安装依赖
RUN npm install
# 复制项目文件到容器中
COPY aware.js ./
COPY data.json ./
# 暴露应用运行的端口
EXPOSE 80
# 命令行启动应用
CMD ["node", "aware.js"]
EOF
docker build -t siyuan-sync .
docker run -itd --name=siyuan-sync -p 28888:80 siyuan-sync
docker ps -a
# 各位友友可以直接使用已经封装好的镜像
docker pull ccr.ccs.tencentyun.com/kentstationcloud/siyuan-sync:latest
Python版本
import json
import os
from flask import Flask, request, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
PORT = 33333
DATA_FILE = 'data.json'
@app.route('/', methods=['GET'])
def health_check():
return '感知节点正常运行中', 200
@app.route('/', methods=['POST'])
def handle_request():
user_key = request.headers.get('userkey', None)
action = request.headers.get('action', None)
body = request.get_json()
client_ip = request.headers.get('X-Forwarded-For', '').split(',').pop().strip()
user_agent = request.headers.get('User-Agent', None)
# print('Received userkey:', user_key)
# print('Received action:', action)
# print('Received body:', body)
# print('Client IP:', client_ip)
# print('User-Agent:', user_agent)
if action == 'push':
return handle_push(user_key, body, client_ip, user_agent)
elif action == 'pull':
return handle_pull(user_key, client_ip, user_agent)
else:
return jsonify({'message': 'Invalid action'}), 400
def handle_push(user_key, body, client_ip, user_agent):
data_to_write = {
user_key: {
'syncst': body.get('syncst'),
'ip': client_ip,
'userAgent': user_agent
}
}
try:
with open(DATA_FILE, 'r') as f:
data = json.load(f)
except FileNotFoundError:
data = {}
data.update(data_to_write)
try:
with open(DATA_FILE, 'w') as f:
json.dump(data, f, indent=2)
return jsonify({'message': 'Data received and written successfully'}), 200
except Exception as e:
print(f'Error writing JSON file: {e}')
return jsonify({'message': 'Failed to write data'}), 500
def handle_pull(user_key, client_ip, user_agent):
try:
with open(DATA_FILE, 'r') as f:
data = json.load(f)
except FileNotFoundError:
return jsonify({'userKey': user_key, 'syncst': 0}), 200
except Exception as e:
print(f'Error reading JSON file: {e}')
return jsonify({'message': 'Failed to read data'}), 500
user_data = data.get(user_key)
if user_data:
if user_data.get('ip') == client_ip and user_data.get('userAgent') == user_agent:
del data[user_key]
try:
with open(DATA_FILE, 'w') as f:
json.dump(data, f, indent=2)
return jsonify({'userKey': user_key, 'syncst': 0}), 200
except Exception as e:
print(f'Error writing JSON file: {e}')
return jsonify({'message': 'Failed to write data'}), 500
else:
return jsonify({'userKey': user_key, 'syncst': user_data.get('syncst')}), 200
else:
return jsonify({'userKey': user_key, 'syncst': 0}), 200
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=PORT)