使用db服务
This commit is contained in:
1 parent
787502b88d
commit
a6ff35260b
3 files changed
+172
-45
No files matched your search
@@ -10,7 +10,7 @@ CREATE TABLE IF NOT EXISTS Users (
|
|||||||
is_active BOOLEAN DEFAULT 1
|
is_active BOOLEAN DEFAULT 1
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS notes (
|
CREATE TABLE IF NOT EXISTS Notes (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
pid INTEGER NOT NULL,
|
pid INTEGER NOT NULL,
|
||||||
title VARCHAR(128) NOT NULL,
|
title VARCHAR(128) NOT NULL,
|
||||||
|
|||||||
+168
-41
@@ -21,6 +21,53 @@ from flask_cors import CORS
|
|||||||
from flask_sqlalchemy import SQLAlchemy
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
from waitress import serve
|
from waitress import serve
|
||||||
import os
|
import os
|
||||||
|
import json
|
||||||
|
import urllib.request
|
||||||
|
import urllib.error
|
||||||
|
|
||||||
|
_SERVER_URL = 'http://127.0.0.1:8005/execute'
|
||||||
|
def call_db_service(url: str, payload: dict, timeout: int = 10) -> dict:
|
||||||
|
'''
|
||||||
|
使用标准库向数据库服务发送 JSON 请求并返回解析后的响应。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
url: 服务端点 URL (例如 'http://127.0.0.1:8005/execute')
|
||||||
|
payload: 要发送的 JSON 数据字典
|
||||||
|
timeout: 请求超时秒数
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict: 服务返回的 JSON 响应
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
urllib.error.URLError: 网络连接错误
|
||||||
|
urllib.error.HTTPError: HTTP 状态错误 (4xx, 5xx)
|
||||||
|
json.JSONDecodeError: 响应不是有效的 JSON
|
||||||
|
'''
|
||||||
|
|
||||||
|
data = json.dumps(payload).encode('utf-8')
|
||||||
|
|
||||||
|
req = urllib.request.Request(
|
||||||
|
url,
|
||||||
|
data=data,
|
||||||
|
headers={'Content-Type': 'application/json'},
|
||||||
|
method='POST'
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=timeout) as response:
|
||||||
|
raw = response.read().decode('utf-8')
|
||||||
|
return json.loads(raw)
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
# HTTP错误,尝试读取错误响应体
|
||||||
|
error_body = e.read().decode('utf-8', errors='replace')
|
||||||
|
raise urllib.error.HTTPError(
|
||||||
|
e.url, e.code, f'HTTP Error {e.code}: {error_body}', e.hdrs, e.fp
|
||||||
|
) from None
|
||||||
|
except urllib.error.URLError as e:
|
||||||
|
raise urllib.error.URLError(f'连接失败: {e.reason}') from None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
basedir = os.path.abspath(os.path.dirname(__file__))
|
basedir = os.path.abspath(os.path.dirname(__file__))
|
||||||
|
|
||||||
@@ -66,25 +113,42 @@ def add_note():
|
|||||||
|
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
|
|
||||||
pid = data.get('pid')
|
pid: int = data.get('pid')
|
||||||
|
|
||||||
title = data.get('title')
|
title: str = data.get('title')
|
||||||
|
|
||||||
content = data.get('content')
|
content: str = data.get('content')
|
||||||
|
|
||||||
if pid is None or not title or not content:
|
if pid is None or not title or not content:
|
||||||
|
|
||||||
return jsonify({"error": "Pid, title and content are required"}), 400
|
return jsonify({"error": "Pid, title and content are required"}), 400
|
||||||
|
|
||||||
new_note = Note(pid=int(pid), title=title, content=content)
|
#new_note = Note(pid=int(pid), title=title, content=content)
|
||||||
|
|
||||||
|
#with app.app_context():
|
||||||
|
|
||||||
with app.app_context():
|
# db.session.add(new_note)
|
||||||
|
|
||||||
db.session.add(new_note)
|
# db.session.commit()
|
||||||
|
|
||||||
db.session.commit()
|
insert_payload = {
|
||||||
|
'action': 'insert',
|
||||||
|
'table': 'Notes',
|
||||||
|
'values': {
|
||||||
|
"pid": pid,
|
||||||
|
"title": title,
|
||||||
|
'content': content
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return jsonify({"message": "Note added successfully"}), 200
|
result = call_db_service(_SERVER_URL, insert_payload)
|
||||||
|
|
||||||
|
success = result['success']
|
||||||
|
|
||||||
|
if success is True:
|
||||||
|
return jsonify({'success': success}), 200
|
||||||
|
else:
|
||||||
|
return jsonify({'success': success}), 400
|
||||||
|
|
||||||
|
|
||||||
# {“pid”: "0"}
|
# {“pid”: "0"}
|
||||||
@@ -96,15 +160,30 @@ def get_notes():
|
|||||||
|
|
||||||
pid = data.get('pid')
|
pid = data.get('pid')
|
||||||
|
|
||||||
if not pid:
|
if not pid: pid = 0
|
||||||
|
|
||||||
pid = 0
|
select_payload = {
|
||||||
|
'action': 'select',
|
||||||
|
'table': 'Notes',
|
||||||
|
'where': {
|
||||||
|
'pid': pid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
with app.app_context():
|
notes = call_db_service(_SERVER_URL, select_payload)
|
||||||
|
|
||||||
notes = Note.query.filter(Note.pid == int(pid))
|
#with app.app_context():
|
||||||
|
|
||||||
result = [{'id': note.id, 'pid': note.pid, 'title': note.title, 'content':note.content} for note in notes]
|
# notes = Note.query.filter(Note.pid == int(pid))
|
||||||
|
|
||||||
|
#result = [{
|
||||||
|
# 'id': note['id'],
|
||||||
|
# 'pid': note['pid'],
|
||||||
|
# 'title': note['title'],
|
||||||
|
# 'content':note['content']
|
||||||
|
#} for note in notes]
|
||||||
|
|
||||||
|
result = notes['data']
|
||||||
|
|
||||||
return jsonify(result), 200
|
return jsonify(result), 200
|
||||||
|
|
||||||
@@ -116,35 +195,65 @@ def delete_note():
|
|||||||
|
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
|
|
||||||
note_id = data.get('id')
|
note_id: int = data.get('id')
|
||||||
|
|
||||||
if note_id:
|
if not note_id:
|
||||||
|
|
||||||
return jsonify({"error": "Note ID is required"}), 400
|
return jsonify({"error": "Note ID is required"}), 400
|
||||||
|
|
||||||
with app.app_context():
|
#with app.app_context():
|
||||||
|
|
||||||
notes = Note.query.filter(Note.pid == int(note_id))
|
# notes = Note.query.filter(Note.pid == int(note_id))
|
||||||
|
|
||||||
# 有子节点的情况不可删除
|
# note = Note.query.get(note_id)
|
||||||
if not notes:
|
|
||||||
|
|
||||||
return jsonify({'error': 'this node has a child'}), 400
|
# if note:
|
||||||
|
|
||||||
|
# db.session.delete(note)
|
||||||
|
|
||||||
|
# db.session.commit()
|
||||||
|
|
||||||
|
# return jsonify({'message': "Note deleted successfully"}), 200
|
||||||
|
|
||||||
|
# else:
|
||||||
|
|
||||||
|
# return jsonify({"error": "Note not found"}), 404
|
||||||
|
|
||||||
|
|
||||||
note = Note.query.get(note_id)
|
select_payload = {
|
||||||
|
'action': 'select',
|
||||||
|
'table': 'Notes',
|
||||||
|
'where': {
|
||||||
|
'id': note_id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if note:
|
notes = call_db_service(_SERVER_URL, select_payload)
|
||||||
|
|
||||||
db.session.delete(note)
|
# 有子节点的情况不可删除
|
||||||
|
if not notes['data']:
|
||||||
|
|
||||||
db.session.commit()
|
return jsonify({'error': 'this node has a child'}), 400
|
||||||
|
|
||||||
return jsonify({'message': "Note deleted successfully"}), 200
|
|
||||||
|
|
||||||
else:
|
|
||||||
|
|
||||||
return jsonify({"error": "Note not found"}), 404
|
delete_payload = {
|
||||||
|
'action': 'delete',
|
||||||
|
'table': 'Notes',
|
||||||
|
'where': {'id': note_id}
|
||||||
|
}
|
||||||
|
|
||||||
|
result = call_db_service(_SERVER_URL, delete_payload)
|
||||||
|
|
||||||
|
result = result['success']
|
||||||
|
|
||||||
|
if result is True:
|
||||||
|
|
||||||
|
return jsonify({'success': True}), 200
|
||||||
|
|
||||||
|
else:
|
||||||
|
|
||||||
|
return jsonify({'success': False}), 400
|
||||||
|
|
||||||
|
|
||||||
# eg: {
|
# eg: {
|
||||||
@@ -159,37 +268,55 @@ def update_note():
|
|||||||
|
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
|
|
||||||
id = data.get('id')
|
id: int = data.get('id')
|
||||||
|
|
||||||
pid = data.get('pid')
|
pid: int = data.get('pid')
|
||||||
|
|
||||||
title = data.get('title')
|
title: str = data.get('title')
|
||||||
|
|
||||||
content = data.get('content')
|
content: str = data.get('content')
|
||||||
|
|
||||||
if id is None or pid is None or not title or not content:
|
if id is None or pid is None or not title or not content:
|
||||||
|
|
||||||
return jsonify({"error": "Invalid param"}), 400
|
return jsonify({"error": "Invalid param"}), 400
|
||||||
|
|
||||||
with app.app_context():
|
|
||||||
|
|
||||||
note = Note.query.get(id)
|
#with app.app_context():
|
||||||
|
|
||||||
if note:
|
# note = Note.query.get(id)
|
||||||
|
|
||||||
note.pid = pid
|
# if note:
|
||||||
|
|
||||||
note.title = title
|
# note.pid = pid
|
||||||
|
|
||||||
note.content = content
|
# note.title = title
|
||||||
|
|
||||||
db.session.commit()
|
# note.content = content
|
||||||
|
|
||||||
return jsonify({'message': "Your change is up-to-date."}), 200
|
# db.session.commit()
|
||||||
|
|
||||||
else:
|
update_payload = {
|
||||||
|
"action": "update",
|
||||||
|
'table': 'Notes',
|
||||||
|
"values": {
|
||||||
|
'pid': pid,
|
||||||
|
'title': title,
|
||||||
|
'content': content
|
||||||
|
},
|
||||||
|
'where': {'id': id}
|
||||||
|
}
|
||||||
|
|
||||||
return jsonify({'error': 'Note not found'}), 400
|
result = call_db_service(_SERVER_URL, update_payload)
|
||||||
|
|
||||||
|
result = result['success']
|
||||||
|
|
||||||
|
if result is True:
|
||||||
|
|
||||||
|
return jsonify({'success': True}), 200
|
||||||
|
|
||||||
|
else:
|
||||||
|
|
||||||
|
return jsonify({'success': False}), 400
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -90,7 +90,7 @@ async function addNode(token, pid, title, content) {
|
|||||||
getNode(token, stack[stack.length - 1]).then(load_notes);
|
getNode(token, stack[stack.length - 1]).then(load_notes);
|
||||||
|
|
||||||
//if (result.success) {
|
//if (result.success) {
|
||||||
console.log(`添加节点成功`, result);
|
alert(`添加节点成功`, result);
|
||||||
return result
|
return result
|
||||||
//...
|
//...
|
||||||
|
|
||||||
@@ -132,7 +132,7 @@ async function deleteNode(token, id) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
throw new Error(result.message || `删除节点失败(HTTP ${res.status})`);
|
throw new Error(`删除节点失败(HTTP ${res.status})`);
|
||||||
}
|
}
|
||||||
|
|
||||||
stack.pop();
|
stack.pop();
|
||||||
@@ -174,7 +174,7 @@ input_note_submit.addEventListener('click', function(event) {
|
|||||||
//alert(stack.length)
|
//alert(stack.length)
|
||||||
//alert(pid)
|
//alert(pid)
|
||||||
addNode(token, pid, title, content).then(result => {
|
addNode(token, pid, title, content).then(result => {
|
||||||
alert(result.message);
|
//alert(result.message);
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user