Skip to content

Commit 7c16340

Browse files
committed
Fix code
1 parent 5dca5c3 commit 7c16340

File tree

10 files changed

+284
-87
lines changed

10 files changed

+284
-87
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,4 +159,5 @@ cython_debug/
159159
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
160160
#.idea/
161161
/temp/
162-
/*.json
162+
/*.json
163+
*.db

README.md

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,19 @@ Requires python3
1616
```bash
1717
git clone git@github.com:electerm/electerm-sync-server-python.git
1818
cd electerm-sync-server-python
19-
python -m venv venv
19+
python3 -m venv venv
2020
# On Windows (PowerShell):
2121
venv\Scripts\activate
2222
# On Unix/Mac:
23-
# source venv/bin/activate
23+
source venv/bin/activate
24+
25+
# Install dependencies
2426
pip install -r requirements.txt
2527

2628
# create env file, then edit .env
2729
cp sample.env .env
2830

29-
python src/app.py
31+
python3 src/app.py
3032

3133
# would show something like
3234
# server running at http://127.0.0.1:7837
@@ -47,7 +49,7 @@ bin/test
4749

4850
## Write your own data store
4951

50-
Just take [src/file_store.py](src/file_store.py) as an example, write your own read/write method
52+
Just take [src/data_store.py](src/data_store.py) as an example, write your own read/write method
5153

5254
## Sync server in other languages
5355

README_zh.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
```bash
1616
git clone git@github.com:electerm/electerm-sync-server-python.git
1717
cd electerm-sync-server-python
18-
python -m venv venv
18+
python3 -m venv venv
1919
# 在 Windows (PowerShell) 上:
2020
venv\Scripts\activate
2121
# 在 Unix/Mac 上:
@@ -25,7 +25,8 @@ pip install -r requirements.txt
2525
# 创建环境文件,然后编辑 .env
2626
cp sample.env .env
2727

28-
python src/app.py
28+
# 运行服务
29+
python3 src/app.py
2930

3031
# 会显示类似内容
3132
# server running at http://127.0.0.1:7837
@@ -46,7 +47,7 @@ bin/test
4647

4748
## 编写自己的数据存储
4849

49-
[src/file_store.py](src/file_store.py) 为例,编写自己的读写方法
50+
[src/data_store.py](src/data_store.py) 为例,编写自己的读写方法
5051

5152
## 其他语言的同步服务器
5253

bin/test

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
#!/bin/bash
22
cd `dirname $0`
33
cd ..
4-
python tests/test.py
4+
python -m unittest tests.test -v

sample.env

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,6 @@ PORT=7837
55
HOST=127.0.0.1
66

77
# jwt secret, make sure you change it in production
8-
JWT_SECRET=283hsdfye@!2@9oijnjSwda09
8+
JWT_SECRET=283hsdfyeDDSd6769oijnjSwda09sfsgfsdgsdfgd234e4tgfd5
99
JWT_USERS=username1,username2,xxxx,hhhh
1010
# FILE_STORE_PATH=/home/some/folder

src/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Electerm sync server package

src/app.py

Lines changed: 65 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,19 @@
11
from flask import Flask, jsonify, request
22
from flask_jwt_extended import JWTManager, jwt_required, get_jwt_identity
33
from dotenv import load_dotenv
4-
from file_store import read, write
54
import os
5+
import logging
6+
import sys
7+
8+
# Add src directory to Python path so imports work in both direct execution and module execution
9+
if os.path.dirname(__file__) not in sys.path:
10+
sys.path.insert(0, os.path.dirname(__file__))
11+
12+
from data_store import read, write
13+
14+
# Configure logging
15+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
16+
logger = logging.getLogger(__name__)
617

718
load_dotenv()
819

@@ -13,14 +24,17 @@
1324

1425
@jwt.invalid_token_loader
1526
def invalid_token_callback(error_string):
27+
logger.warning(f"Invalid token provided: {error_string}")
1628
return jsonify({'status': 'error', 'message': 'Invalid token'}), 422
1729

1830
@jwt.expired_token_loader
1931
def expired_token_callback(jwt_header, jwt_payload):
32+
logger.warning("Expired token used")
2033
return jsonify({'status': 'error', 'message': 'Token expired'}), 422
2134

2235
@jwt.unauthorized_loader
2336
def unauthorized_callback(error_string):
37+
logger.warning(f"Unauthorized access: {error_string}")
2438
return jsonify({'status': 'error', 'message': 'Missing or invalid token'}), 422
2539

2640
@app.route('/api/sync', methods=['GET', 'PUT', 'POST'])
@@ -30,28 +44,74 @@ def sync():
3044
users = os.environ['JWT_USERS'].split(',')
3145

3246
if user_id not in users:
47+
logger.warning(f"Unauthorized access attempt by user: {user_id}")
3348
return jsonify({'status': 'error', 'message': 'Unauthorized!'}), 401
3449

3550
if request.method == 'GET':
36-
return read(user_id)
51+
data, status = read(user_id)
52+
if status == 200:
53+
return jsonify(data), 200
54+
else:
55+
return jsonify({'status': 'error', 'message': data}), status
3756

3857
if request.method == 'POST':
58+
logger.info(f"User {user_id} testing sync endpoint")
3959
return 'test ok'
4060

4161
if request.method == 'PUT':
62+
logger.info(f"User {user_id} writing sync data")
4263
data = request.get_json()
43-
return write(data, user_id)
64+
status_msg, status = write(data, user_id)
65+
if status == 200:
66+
return status_msg, 200
67+
else:
68+
return jsonify({'status': 'error', 'message': status_msg}), status
4469

4570
return jsonify({'status': 'error', 'message': 'Unsupported method!'}), 405
4671

4772
@app.route('/test', methods=['GET'])
4873
def test():
74+
logger.info("Test endpoint accessed")
4975
return 'ok'
5076

5177

5278
if __name__ == '__main__':
53-
port = os.environ['PORT']
54-
host = os.environ['HOST']
79+
port = int(os.environ.get('PORT', 5000))
80+
host = os.environ.get('HOST', '127.0.0.1')
81+
82+
logger.info("=== Electerm Sync Server Starting ===")
83+
logger.info(f"Server will run at: http://{host}:{port}")
84+
logger.info(f"API endpoint: http://{host}:{port}/api/sync")
85+
logger.info(f"Test endpoint: http://{host}:{port}/test")
86+
87+
# Show JWT configuration
88+
jwt_secret = os.environ.get('JWT_SECRET', '')
89+
jwt_users = os.environ.get('JWT_USERS', '')
90+
91+
if jwt_secret:
92+
logger.info("JWT_SECRET configured (check your .env file)")
93+
else:
94+
logger.warning("JWT_SECRET not configured in environment variables")
95+
96+
if jwt_users:
97+
users_list = jwt_users.split(',')
98+
logger.info(f"Authorized users: {', '.join(users_list)}")
99+
logger.info(f"Use one of these as JWT_USER_NAME in Electerm: {users_list[0]}")
100+
else:
101+
logger.warning("No JWT_USERS configured in environment variables")
102+
103+
# Show data store location
104+
from data_store import db_path
105+
logger.info(f"Data store location: {db_path}")
106+
107+
logger.info("=== Configuration for Electerm ===")
108+
logger.info(f"Server URL: http://{host}:{port}")
109+
logger.info("Set these values in Electerm sync settings:")
110+
logger.info("- Custom sync server URL: http://{host}:{port}")
111+
logger.info("- JWT_SECRET: check your .env file")
112+
logger.info("- JWT_USER_NAME: (see authorized users above)")
113+
logger.info("=== Server Ready ===")
114+
55115
app.run(
56116
host=host,
57117
port=port,

src/data_store.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import sqlite3
2+
import json
3+
import os
4+
5+
# Database path from environment or default
6+
db_path = os.environ.get('DATA_STORE_PATH') or os.path.join(os.getcwd(), 'data.db')
7+
8+
def get_db_connection():
9+
"""Get a database connection"""
10+
conn = sqlite3.connect(db_path)
11+
conn.execute('''
12+
CREATE TABLE IF NOT EXISTS sync_data (
13+
user_id TEXT PRIMARY KEY,
14+
data TEXT NOT NULL
15+
)
16+
''')
17+
conn.commit()
18+
return conn
19+
20+
def write(data, user_id):
21+
"""Write data for a user"""
22+
try:
23+
json_body = json.dumps(data or {})
24+
conn = get_db_connection()
25+
conn.execute('''
26+
INSERT OR REPLACE INTO sync_data (user_id, data)
27+
VALUES (?, ?)
28+
''', (user_id, json_body))
29+
conn.commit()
30+
conn.close()
31+
return "ok", 200
32+
except Exception as e:
33+
return f"Error writing data: {str(e)}", 500
34+
35+
def read(user_id):
36+
"""Read data for a user"""
37+
try:
38+
conn = get_db_connection()
39+
cursor = conn.cursor()
40+
cursor.execute('SELECT data FROM sync_data WHERE user_id = ?', (user_id,))
41+
row = cursor.fetchone()
42+
conn.close()
43+
if row:
44+
data = json.loads(row[0])
45+
return data, 200
46+
else:
47+
return "User not found", 404
48+
except Exception as e:
49+
return f"Error reading data: {str(e)}", 500

src/file_store.py

Lines changed: 0 additions & 20 deletions
This file was deleted.

0 commit comments

Comments
 (0)