Compare commits
12 Commits
0926ab2535
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| e650a087ca | |||
| 48bb1b3c12 | |||
| 8a752b2b92 | |||
| a678adf646 | |||
| 08994d732d | |||
| 9c011dfc8c | |||
| aa6b1dec3f | |||
| 81f1eae2d5 | |||
| 263b396142 | |||
| 068e675fd1 | |||
| 5a6f799059 | |||
| 8c530ff599 |
190
ESConnect.py
190
ESConnect.py
@@ -3,6 +3,7 @@ from elasticsearch import Elasticsearch
|
|||||||
# import json
|
# import json
|
||||||
import hashlib
|
import hashlib
|
||||||
import requests
|
import requests
|
||||||
|
import json
|
||||||
|
|
||||||
# Elasticsearch连接配置
|
# Elasticsearch连接配置
|
||||||
ES_URL = "http://localhost:9200"
|
ES_URL = "http://localhost:9200"
|
||||||
@@ -24,6 +25,7 @@ def create_index_with_mapping():
|
|||||||
"mappings": {
|
"mappings": {
|
||||||
"properties": {
|
"properties": {
|
||||||
"writer_id":{"type": "text"},
|
"writer_id":{"type": "text"},
|
||||||
|
|
||||||
"data": {
|
"data": {
|
||||||
"type": "text", # 存储转换后的字符串,支持分词搜索
|
"type": "text", # 存储转换后的字符串,支持分词搜索
|
||||||
"analyzer": "ik_max_word",
|
"analyzer": "ik_max_word",
|
||||||
@@ -60,6 +62,9 @@ def create_index_with_mapping():
|
|||||||
write_user_data(admin)
|
write_user_data(admin)
|
||||||
else:
|
else:
|
||||||
print(f"索引 {users_index_name} 已存在")
|
print(f"索引 {users_index_name} 已存在")
|
||||||
|
def update_document(es, index_name, doc_id=None, updated_doc=None):
|
||||||
|
"""更新指定ID的文档"""
|
||||||
|
es.update(index=index_name, id=doc_id, body={"doc": updated_doc})
|
||||||
|
|
||||||
|
|
||||||
def get_doc_id(data):
|
def get_doc_id(data):
|
||||||
@@ -142,6 +147,49 @@ def delete_by_id(doc_id):
|
|||||||
print("删除失败:", str(e))
|
print("删除失败:", str(e))
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def update_by_id(doc_id, updated_data):
|
||||||
|
"""
|
||||||
|
根据文档ID更新数据
|
||||||
|
|
||||||
|
参数:
|
||||||
|
doc_id (str): 要更新的文档ID
|
||||||
|
updated_data (dict): 更新的数据内容
|
||||||
|
|
||||||
|
返回:
|
||||||
|
bool: 更新成功返回True,失败返回False
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# 执行更新操作
|
||||||
|
es.update(index=data_index_name, id=doc_id, body={"doc": updated_data})
|
||||||
|
print(f"文档 {doc_id} 更新成功")
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
print(f"更新失败: {str(e)}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def get_by_id(doc_id):
|
||||||
|
"""
|
||||||
|
根据文档ID获取单个文档
|
||||||
|
|
||||||
|
参数:
|
||||||
|
doc_id (str): 要获取的文档ID
|
||||||
|
|
||||||
|
返回:
|
||||||
|
dict or None: 成功返回文档数据,失败返回None
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# 执行获取操作
|
||||||
|
result = es.get(index=data_index_name, id=doc_id)
|
||||||
|
if result['found']:
|
||||||
|
return {
|
||||||
|
"_id": result['_id'],
|
||||||
|
**result['_source']
|
||||||
|
}
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
print(f"获取文档失败: {str(e)}")
|
||||||
|
return None
|
||||||
|
|
||||||
def search_by_any_field(keyword):
|
def search_by_any_field(keyword):
|
||||||
"""全字段模糊搜索(支持拼写错误)"""
|
"""全字段模糊搜索(支持拼写错误)"""
|
||||||
try:
|
try:
|
||||||
@@ -216,11 +264,11 @@ def write_user_data(data):
|
|||||||
def verify_user(username, password):
|
def verify_user(username, password):
|
||||||
"""
|
"""
|
||||||
验证用户登录信息
|
验证用户登录信息
|
||||||
|
|
||||||
参数:
|
参数:
|
||||||
username (str): 用户名
|
username (str): 用户名
|
||||||
password (str): 密码
|
password (str): 密码
|
||||||
|
|
||||||
返回:
|
返回:
|
||||||
dict or None: 验证成功返回用户信息,失败返回None
|
dict or None: 验证成功返回用户信息,失败返回None
|
||||||
"""
|
"""
|
||||||
@@ -239,7 +287,7 @@ def verify_user(username, password):
|
|||||||
)
|
)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
results = response.json()["hits"]["hits"]
|
results = response.json()["hits"]["hits"]
|
||||||
|
|
||||||
if results:
|
if results:
|
||||||
user_data = results[0]["_source"]
|
user_data = results[0]["_source"]
|
||||||
# 验证密码
|
# 验证密码
|
||||||
@@ -252,7 +300,7 @@ def verify_user(username, password):
|
|||||||
else:
|
else:
|
||||||
print(f"用户 {username} 不存在")
|
print(f"用户 {username} 不存在")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
except requests.exceptions.HTTPError as e:
|
except requests.exceptions.HTTPError as e:
|
||||||
print(f"用户验证失败: {e.response.text}")
|
print(f"用户验证失败: {e.response.text}")
|
||||||
return None
|
return None
|
||||||
@@ -260,10 +308,10 @@ def verify_user(username, password):
|
|||||||
def get_user_by_username(username):
|
def get_user_by_username(username):
|
||||||
"""
|
"""
|
||||||
根据用户名查询用户信息
|
根据用户名查询用户信息
|
||||||
|
|
||||||
参数:
|
参数:
|
||||||
username (str): 用户名
|
username (str): 用户名
|
||||||
|
|
||||||
返回:
|
返回:
|
||||||
dict or None: 查询成功返回用户信息,失败返回None
|
dict or None: 查询成功返回用户信息,失败返回None
|
||||||
"""
|
"""
|
||||||
@@ -281,12 +329,12 @@ def get_user_by_username(username):
|
|||||||
)
|
)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
results = response.json()["hits"]["hits"]
|
results = response.json()["hits"]["hits"]
|
||||||
|
|
||||||
if results:
|
if results:
|
||||||
return results[0]["_source"]
|
return results[0]["_source"]
|
||||||
else:
|
else:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
except requests.exceptions.HTTPError as e:
|
except requests.exceptions.HTTPError as e:
|
||||||
print(f"用户查询失败: {e.response.text}")
|
print(f"用户查询失败: {e.response.text}")
|
||||||
return None
|
return None
|
||||||
@@ -294,12 +342,12 @@ def get_user_by_username(username):
|
|||||||
def create_user(username, password, permission=1):
|
def create_user(username, password, permission=1):
|
||||||
"""
|
"""
|
||||||
创建新用户
|
创建新用户
|
||||||
|
|
||||||
参数:
|
参数:
|
||||||
username (str): 用户名
|
username (str): 用户名
|
||||||
password (str): 密码
|
password (str): 密码
|
||||||
permission (int): 权限级别,默认为1(普通用户)
|
permission (int): 权限级别,默认为1(普通用户)
|
||||||
|
|
||||||
返回:
|
返回:
|
||||||
bool: 创建成功返回True,失败返回False
|
bool: 创建成功返回True,失败返回False
|
||||||
"""
|
"""
|
||||||
@@ -307,24 +355,24 @@ def create_user(username, password, permission=1):
|
|||||||
if get_user_by_username(username):
|
if get_user_by_username(username):
|
||||||
print(f"用户名 {username} 已存在")
|
print(f"用户名 {username} 已存在")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 生成新的用户ID
|
# 生成新的用户ID
|
||||||
import time
|
import time
|
||||||
user_id = int(time.time() * 1000) # 使用时间戳作为用户ID
|
user_id = int(time.time() * 1000) # 使用时间戳作为用户ID
|
||||||
|
|
||||||
user_data = {
|
user_data = {
|
||||||
"user_id": user_id,
|
"user_id": user_id,
|
||||||
"username": username,
|
"username": username,
|
||||||
"password": password,
|
"password": password,
|
||||||
"premission": permission
|
"premission": permission
|
||||||
}
|
}
|
||||||
|
|
||||||
return write_user_data(user_data)
|
return write_user_data(user_data)
|
||||||
|
|
||||||
def get_all_users():
|
def get_all_users():
|
||||||
"""
|
"""
|
||||||
获取所有用户信息
|
获取所有用户信息
|
||||||
|
|
||||||
返回:
|
返回:
|
||||||
list: 包含所有用户信息的列表
|
list: 包含所有用户信息的列表
|
||||||
"""
|
"""
|
||||||
@@ -341,15 +389,15 @@ def get_all_users():
|
|||||||
)
|
)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
results = response.json()["hits"]["hits"]
|
results = response.json()["hits"]["hits"]
|
||||||
|
|
||||||
users = []
|
users = []
|
||||||
for hit in results:
|
for hit in results:
|
||||||
user_data = hit["_source"]
|
user_data = hit["_source"]
|
||||||
user_data["_id"] = hit["_id"] # 添加文档ID用于后续操作
|
user_data["_id"] = hit["_id"] # 添加文档ID用于后续操作
|
||||||
users.append(user_data)
|
users.append(user_data)
|
||||||
|
|
||||||
return users
|
return users
|
||||||
|
|
||||||
except requests.exceptions.HTTPError as e:
|
except requests.exceptions.HTTPError as e:
|
||||||
print(f"获取用户列表失败: {e.response.text}")
|
print(f"获取用户列表失败: {e.response.text}")
|
||||||
return []
|
return []
|
||||||
@@ -357,11 +405,11 @@ def get_all_users():
|
|||||||
def update_user_password(username, new_password):
|
def update_user_password(username, new_password):
|
||||||
"""
|
"""
|
||||||
更新用户密码
|
更新用户密码
|
||||||
|
|
||||||
参数:
|
参数:
|
||||||
username (str): 用户名
|
username (str): 用户名
|
||||||
new_password (str): 新密码
|
new_password (str): 新密码
|
||||||
|
|
||||||
返回:
|
返回:
|
||||||
bool: 更新成功返回True,失败返回False
|
bool: 更新成功返回True,失败返回False
|
||||||
"""
|
"""
|
||||||
@@ -380,18 +428,18 @@ def update_user_password(username, new_password):
|
|||||||
)
|
)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
results = response.json()["hits"]["hits"]
|
results = response.json()["hits"]["hits"]
|
||||||
|
|
||||||
if not results:
|
if not results:
|
||||||
print(f"用户 {username} 不存在")
|
print(f"用户 {username} 不存在")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 获取用户文档ID
|
# 获取用户文档ID
|
||||||
doc_id = results[0]["_id"]
|
doc_id = results[0]["_id"]
|
||||||
user_data = results[0]["_source"]
|
user_data = results[0]["_source"]
|
||||||
|
|
||||||
# 更新密码
|
# 更新密码
|
||||||
user_data["password"] = new_password
|
user_data["password"] = new_password
|
||||||
|
|
||||||
# 更新文档
|
# 更新文档
|
||||||
update_response = requests.post(
|
update_response = requests.post(
|
||||||
f"{ES_URL}/{users_index_name}/_doc/{doc_id}",
|
f"{ES_URL}/{users_index_name}/_doc/{doc_id}",
|
||||||
@@ -400,10 +448,10 @@ def update_user_password(username, new_password):
|
|||||||
headers={"Content-Type": "application/json"}
|
headers={"Content-Type": "application/json"}
|
||||||
)
|
)
|
||||||
update_response.raise_for_status()
|
update_response.raise_for_status()
|
||||||
|
|
||||||
print(f"用户 {username} 密码更新成功")
|
print(f"用户 {username} 密码更新成功")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except requests.exceptions.HTTPError as e:
|
except requests.exceptions.HTTPError as e:
|
||||||
print(f"更新用户密码失败: {e.response.text}")
|
print(f"更新用户密码失败: {e.response.text}")
|
||||||
return False
|
return False
|
||||||
@@ -411,10 +459,10 @@ def update_user_password(username, new_password):
|
|||||||
def delete_user(username):
|
def delete_user(username):
|
||||||
"""
|
"""
|
||||||
删除用户
|
删除用户
|
||||||
|
|
||||||
参数:
|
参数:
|
||||||
username (str): 要删除的用户名
|
username (str): 要删除的用户名
|
||||||
|
|
||||||
返回:
|
返回:
|
||||||
bool: 删除成功返回True,失败返回False
|
bool: 删除成功返回True,失败返回False
|
||||||
"""
|
"""
|
||||||
@@ -423,7 +471,7 @@ def delete_user(username):
|
|||||||
if username == "admin":
|
if username == "admin":
|
||||||
print("不能删除管理员账户")
|
print("不能删除管理员账户")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 先查找用户
|
# 先查找用户
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
f"{ES_URL}/{users_index_name}/_search",
|
f"{ES_URL}/{users_index_name}/_search",
|
||||||
@@ -438,24 +486,24 @@ def delete_user(username):
|
|||||||
)
|
)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
results = response.json()["hits"]["hits"]
|
results = response.json()["hits"]["hits"]
|
||||||
|
|
||||||
if not results:
|
if not results:
|
||||||
print(f"用户 {username} 不存在")
|
print(f"用户 {username} 不存在")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 获取用户文档ID
|
# 获取用户文档ID
|
||||||
doc_id = results[0]["_id"]
|
doc_id = results[0]["_id"]
|
||||||
|
|
||||||
# 删除用户
|
# 删除用户
|
||||||
delete_response = requests.delete(
|
delete_response = requests.delete(
|
||||||
f"{ES_URL}/{users_index_name}/_doc/{doc_id}",
|
f"{ES_URL}/{users_index_name}/_doc/{doc_id}",
|
||||||
auth=AUTH
|
auth=AUTH
|
||||||
)
|
)
|
||||||
delete_response.raise_for_status()
|
delete_response.raise_for_status()
|
||||||
|
|
||||||
print(f"用户 {username} 删除成功")
|
print(f"用户 {username} 删除成功")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except requests.exceptions.HTTPError as e:
|
except requests.exceptions.HTTPError as e:
|
||||||
print(f"删除用户失败: {e.response.text}")
|
print(f"删除用户失败: {e.response.text}")
|
||||||
return False
|
return False
|
||||||
@@ -463,11 +511,11 @@ def delete_user(username):
|
|||||||
def update_user_permission(username, new_permission):
|
def update_user_permission(username, new_permission):
|
||||||
"""
|
"""
|
||||||
更新用户权限
|
更新用户权限
|
||||||
|
|
||||||
参数:
|
参数:
|
||||||
username (str): 用户名
|
username (str): 用户名
|
||||||
new_permission (int): 新权限级别
|
new_permission (int): 新权限级别
|
||||||
|
|
||||||
返回:
|
返回:
|
||||||
bool: 更新成功返回True,失败返回False
|
bool: 更新成功返回True,失败返回False
|
||||||
"""
|
"""
|
||||||
@@ -476,7 +524,7 @@ def update_user_permission(username, new_permission):
|
|||||||
if username == "admin":
|
if username == "admin":
|
||||||
print("不能修改管理员权限")
|
print("不能修改管理员权限")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 先查找用户
|
# 先查找用户
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
f"{ES_URL}/{users_index_name}/_search",
|
f"{ES_URL}/{users_index_name}/_search",
|
||||||
@@ -491,18 +539,18 @@ def update_user_permission(username, new_permission):
|
|||||||
)
|
)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
results = response.json()["hits"]["hits"]
|
results = response.json()["hits"]["hits"]
|
||||||
|
|
||||||
if not results:
|
if not results:
|
||||||
print(f"用户 {username} 不存在")
|
print(f"用户 {username} 不存在")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 获取用户文档ID
|
# 获取用户文档ID
|
||||||
doc_id = results[0]["_id"]
|
doc_id = results[0]["_id"]
|
||||||
user_data = results[0]["_source"]
|
user_data = results[0]["_source"]
|
||||||
|
|
||||||
# 更新权限
|
# 更新权限
|
||||||
user_data["premission"] = new_permission
|
user_data["premission"] = new_permission
|
||||||
|
|
||||||
# 更新文档
|
# 更新文档
|
||||||
update_response = requests.post(
|
update_response = requests.post(
|
||||||
f"{ES_URL}/{users_index_name}/_doc/{doc_id}",
|
f"{ES_URL}/{users_index_name}/_doc/{doc_id}",
|
||||||
@@ -511,10 +559,10 @@ def update_user_permission(username, new_permission):
|
|||||||
headers={"Content-Type": "application/json"}
|
headers={"Content-Type": "application/json"}
|
||||||
)
|
)
|
||||||
update_response.raise_for_status()
|
update_response.raise_for_status()
|
||||||
|
|
||||||
print(f"用户 {username} 权限更新成功")
|
print(f"用户 {username} 权限更新成功")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except requests.exceptions.HTTPError as e:
|
except requests.exceptions.HTTPError as e:
|
||||||
print(f"更新用户权限失败: {e.response.text}")
|
print(f"更新用户权限失败: {e.response.text}")
|
||||||
return False
|
return False
|
||||||
@@ -522,11 +570,11 @@ def update_user_permission(username, new_permission):
|
|||||||
def search_data_by_user(user_id, keyword=None):
|
def search_data_by_user(user_id, keyword=None):
|
||||||
"""
|
"""
|
||||||
根据用户ID查询该用户的数据,支持关键词搜索
|
根据用户ID查询该用户的数据,支持关键词搜索
|
||||||
|
|
||||||
参数:
|
参数:
|
||||||
user_id (str): 用户ID
|
user_id (str): 用户ID
|
||||||
keyword (str, optional): 搜索关键词
|
keyword (str, optional): 搜索关键词
|
||||||
|
|
||||||
返回:
|
返回:
|
||||||
list: 包含文档ID和源数据的列表
|
list: 包含文档ID和源数据的列表
|
||||||
"""
|
"""
|
||||||
@@ -552,7 +600,7 @@ def search_data_by_user(user_id, keyword=None):
|
|||||||
query = {
|
query = {
|
||||||
"term": {"user_id": user_id}
|
"term": {"user_id": user_id}
|
||||||
}
|
}
|
||||||
|
|
||||||
response = requests.post(
|
response = requests.post(
|
||||||
f"{ES_URL}/{data_index_name}/_search",
|
f"{ES_URL}/{data_index_name}/_search",
|
||||||
auth=AUTH,
|
auth=AUTH,
|
||||||
@@ -563,13 +611,13 @@ def search_data_by_user(user_id, keyword=None):
|
|||||||
)
|
)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
results = response.json()["hits"]["hits"]
|
results = response.json()["hits"]["hits"]
|
||||||
|
|
||||||
# 返回包含文档ID和源数据的列表
|
# 返回包含文档ID和源数据的列表
|
||||||
return [{
|
return [{
|
||||||
"_id": hit["_id"],
|
"_id": hit["_id"],
|
||||||
**hit["_source"]
|
**hit["_source"]
|
||||||
} for hit in results]
|
} for hit in results]
|
||||||
|
|
||||||
except requests.exceptions.HTTPError as e:
|
except requests.exceptions.HTTPError as e:
|
||||||
print(f"查询用户数据失败: {e.response.text}")
|
print(f"查询用户数据失败: {e.response.text}")
|
||||||
return []
|
return []
|
||||||
@@ -577,12 +625,12 @@ def search_data_by_user(user_id, keyword=None):
|
|||||||
def update_data_by_id(doc_id, updated_data, user_id):
|
def update_data_by_id(doc_id, updated_data, user_id):
|
||||||
"""
|
"""
|
||||||
根据文档ID更新数据(仅允许数据所有者修改)
|
根据文档ID更新数据(仅允许数据所有者修改)
|
||||||
|
|
||||||
参数:
|
参数:
|
||||||
doc_id (str): 文档ID
|
doc_id (str): 文档ID
|
||||||
updated_data (dict): 更新的数据
|
updated_data (dict): 更新的数据
|
||||||
user_id (str): 当前用户ID
|
user_id (str): 当前用户ID
|
||||||
|
|
||||||
返回:
|
返回:
|
||||||
bool: 更新成功返回True,失败返回False
|
bool: 更新成功返回True,失败返回False
|
||||||
"""
|
"""
|
||||||
@@ -594,20 +642,20 @@ def update_data_by_id(doc_id, updated_data, user_id):
|
|||||||
)
|
)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
doc = response.json()
|
doc = response.json()
|
||||||
|
|
||||||
# 检查文档是否存在
|
# 检查文档是否存在
|
||||||
if not doc.get("found"):
|
if not doc.get("found"):
|
||||||
print(f"文档 {doc_id} 不存在")
|
print(f"文档 {doc_id} 不存在")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 检查用户权限(只能修改自己的数据)
|
# 检查用户权限(只能修改自己的数据)
|
||||||
if doc["_source"].get("user_id") != user_id:
|
if doc["_source"].get("user_id") != user_id:
|
||||||
print(f"用户 {user_id} 无权修改文档 {doc_id}")
|
print(f"用户 {user_id} 无权修改文档 {doc_id}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 保持用户ID不变
|
# 保持用户ID不变
|
||||||
updated_data["user_id"] = user_id
|
updated_data["user_id"] = user_id
|
||||||
|
|
||||||
# 更新文档
|
# 更新文档
|
||||||
update_response = requests.post(
|
update_response = requests.post(
|
||||||
f"{ES_URL}/{data_index_name}/_doc/{doc_id}",
|
f"{ES_URL}/{data_index_name}/_doc/{doc_id}",
|
||||||
@@ -616,10 +664,10 @@ def update_data_by_id(doc_id, updated_data, user_id):
|
|||||||
headers={"Content-Type": "application/json"}
|
headers={"Content-Type": "application/json"}
|
||||||
)
|
)
|
||||||
update_response.raise_for_status()
|
update_response.raise_for_status()
|
||||||
|
|
||||||
print(f"文档 {doc_id} 更新成功")
|
print(f"文档 {doc_id} 更新成功")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except requests.exceptions.HTTPError as e:
|
except requests.exceptions.HTTPError as e:
|
||||||
print(f"更新文档失败: {e.response.text}")
|
print(f"更新文档失败: {e.response.text}")
|
||||||
return False
|
return False
|
||||||
@@ -627,11 +675,11 @@ def update_data_by_id(doc_id, updated_data, user_id):
|
|||||||
def delete_data_by_id(doc_id, user_id):
|
def delete_data_by_id(doc_id, user_id):
|
||||||
"""
|
"""
|
||||||
根据文档ID删除数据(仅允许数据所有者或管理员删除)
|
根据文档ID删除数据(仅允许数据所有者或管理员删除)
|
||||||
|
|
||||||
参数:
|
参数:
|
||||||
doc_id (str): 文档ID
|
doc_id (str): 文档ID
|
||||||
user_id (str): 当前用户ID
|
user_id (str): 当前用户ID
|
||||||
|
|
||||||
返回:
|
返回:
|
||||||
bool: 删除成功返回True,失败返回False
|
bool: 删除成功返回True,失败返回False
|
||||||
"""
|
"""
|
||||||
@@ -643,12 +691,12 @@ def delete_data_by_id(doc_id, user_id):
|
|||||||
)
|
)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
doc = response.json()
|
doc = response.json()
|
||||||
|
|
||||||
# 检查文档是否存在
|
# 检查文档是否存在
|
||||||
if not doc.get("found"):
|
if not doc.get("found"):
|
||||||
print(f"文档 {doc_id} 不存在")
|
print(f"文档 {doc_id} 不存在")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 检查用户权限(只能删除自己的数据,管理员可以删除所有数据)
|
# 检查用户权限(只能删除自己的数据,管理员可以删除所有数据)
|
||||||
doc_user_id = doc["_source"].get("user_id")
|
doc_user_id = doc["_source"].get("user_id")
|
||||||
if doc_user_id != user_id:
|
if doc_user_id != user_id:
|
||||||
@@ -657,17 +705,17 @@ def delete_data_by_id(doc_id, user_id):
|
|||||||
if not user_info or user_info.get("premission") != 0:
|
if not user_info or user_info.get("premission") != 0:
|
||||||
print(f"用户 {user_id} 无权删除文档 {doc_id}")
|
print(f"用户 {user_id} 无权删除文档 {doc_id}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 删除文档
|
# 删除文档
|
||||||
delete_response = requests.delete(
|
delete_response = requests.delete(
|
||||||
f"{ES_URL}/{data_index_name}/_doc/{doc_id}",
|
f"{ES_URL}/{data_index_name}/_doc/{doc_id}",
|
||||||
auth=AUTH
|
auth=AUTH
|
||||||
)
|
)
|
||||||
delete_response.raise_for_status()
|
delete_response.raise_for_status()
|
||||||
|
|
||||||
print(f"文档 {doc_id} 删除成功")
|
print(f"文档 {doc_id} 删除成功")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except requests.exceptions.HTTPError as e:
|
except requests.exceptions.HTTPError as e:
|
||||||
print(f"删除文档失败: {e.response.text}")
|
print(f"删除文档失败: {e.response.text}")
|
||||||
return False
|
return False
|
||||||
@@ -675,12 +723,12 @@ def delete_data_by_id(doc_id, user_id):
|
|||||||
def update_user_own_password(user_id, old_password, new_password):
|
def update_user_own_password(user_id, old_password, new_password):
|
||||||
"""
|
"""
|
||||||
用户修改自己的密码
|
用户修改自己的密码
|
||||||
|
|
||||||
参数:
|
参数:
|
||||||
user_id (str): 用户ID
|
user_id (str): 用户ID
|
||||||
old_password (str): 旧密码
|
old_password (str): 旧密码
|
||||||
new_password (str): 新密码
|
new_password (str): 新密码
|
||||||
|
|
||||||
返回:
|
返回:
|
||||||
bool: 修改成功返回True,失败返回False
|
bool: 修改成功返回True,失败返回False
|
||||||
"""
|
"""
|
||||||
@@ -699,22 +747,22 @@ def update_user_own_password(user_id, old_password, new_password):
|
|||||||
)
|
)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
results = response.json()["hits"]["hits"]
|
results = response.json()["hits"]["hits"]
|
||||||
|
|
||||||
if not results:
|
if not results:
|
||||||
print(f"用户 {user_id} 不存在")
|
print(f"用户 {user_id} 不存在")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
user_data = results[0]["_source"]
|
user_data = results[0]["_source"]
|
||||||
doc_id = results[0]["_id"]
|
doc_id = results[0]["_id"]
|
||||||
|
|
||||||
# 验证旧密码
|
# 验证旧密码
|
||||||
if user_data.get("password") != old_password:
|
if user_data.get("password") != old_password:
|
||||||
print("旧密码错误")
|
print("旧密码错误")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 更新密码
|
# 更新密码
|
||||||
user_data["password"] = new_password
|
user_data["password"] = new_password
|
||||||
|
|
||||||
# 更新文档
|
# 更新文档
|
||||||
update_response = requests.post(
|
update_response = requests.post(
|
||||||
f"{ES_URL}/{users_index_name}/_doc/{doc_id}",
|
f"{ES_URL}/{users_index_name}/_doc/{doc_id}",
|
||||||
@@ -723,10 +771,10 @@ def update_user_own_password(user_id, old_password, new_password):
|
|||||||
headers={"Content-Type": "application/json"}
|
headers={"Content-Type": "application/json"}
|
||||||
)
|
)
|
||||||
update_response.raise_for_status()
|
update_response.raise_for_status()
|
||||||
|
|
||||||
print(f"用户 {user_id} 密码修改成功")
|
print(f"用户 {user_id} 密码修改成功")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except requests.exceptions.HTTPError as e:
|
except requests.exceptions.HTTPError as e:
|
||||||
print(f"修改密码失败: {e.response.text}")
|
print(f"修改密码失败: {e.response.text}")
|
||||||
return False
|
return False
|
||||||
|
|||||||
164
app.py
164
app.py
@@ -7,18 +7,19 @@ from PIL import Image
|
|||||||
import re
|
import re
|
||||||
import json
|
import json
|
||||||
import requests
|
import requests
|
||||||
|
from functools import wraps
|
||||||
from ESConnect import *
|
from ESConnect import *
|
||||||
from json_converter import json_to_string, string_to_json
|
from json_converter import json_to_string, string_to_json
|
||||||
from openai import OpenAI
|
from openai import OpenAI
|
||||||
from functools import wraps
|
|
||||||
# import config
|
# import config
|
||||||
|
|
||||||
# 创建Flask应用实例
|
# 创建Flask应用实例
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
# 设置会话密钥,用于加密会话数据
|
|
||||||
app.secret_key = 'your-secret-key-change-this-in-production'
|
|
||||||
# app.config.from_object(config.Config)
|
# app.config.from_object(config.Config)
|
||||||
|
|
||||||
|
# 设置会话密钥,用于加密会话数据
|
||||||
|
app.secret_key = 'your-secret-key-change-this-in-production'
|
||||||
|
# OCR和信息提取函数,使用大模型API处理图片并提取结构化信息
|
||||||
# 权限装饰器
|
# 权限装饰器
|
||||||
def login_required(f):
|
def login_required(f):
|
||||||
"""要求用户登录的装饰器"""
|
"""要求用户登录的装饰器"""
|
||||||
@@ -29,7 +30,6 @@ def login_required(f):
|
|||||||
return redirect(url_for('login'))
|
return redirect(url_for('login'))
|
||||||
return f(*args, **kwargs)
|
return f(*args, **kwargs)
|
||||||
return decorated_function
|
return decorated_function
|
||||||
|
|
||||||
def admin_required(f):
|
def admin_required(f):
|
||||||
"""要求管理员权限的装饰器"""
|
"""要求管理员权限的装饰器"""
|
||||||
@wraps(f)
|
@wraps(f)
|
||||||
@@ -42,7 +42,6 @@ def admin_required(f):
|
|||||||
return redirect(url_for('index'))
|
return redirect(url_for('index'))
|
||||||
return f(*args, **kwargs)
|
return f(*args, **kwargs)
|
||||||
return decorated_function
|
return decorated_function
|
||||||
|
|
||||||
def user_or_admin_required(f):
|
def user_or_admin_required(f):
|
||||||
"""要求普通用户或管理员权限的装饰器"""
|
"""要求普通用户或管理员权限的装饰器"""
|
||||||
@wraps(f)
|
@wraps(f)
|
||||||
@@ -57,7 +56,6 @@ def user_or_admin_required(f):
|
|||||||
return f(*args, **kwargs)
|
return f(*args, **kwargs)
|
||||||
return decorated_function
|
return decorated_function
|
||||||
|
|
||||||
# OCR和信息提取函数,使用大模型API处理图片并提取结构化信息
|
|
||||||
def ocr_and_extract_info(image_path):
|
def ocr_and_extract_info(image_path):
|
||||||
"""
|
"""
|
||||||
使用大模型API进行OCR识别并提取图片中的结构化信息
|
使用大模型API进行OCR识别并提取图片中的结构化信息
|
||||||
@@ -186,18 +184,18 @@ def ocr_and_extract_info(image_path):
|
|||||||
def login():
|
def login():
|
||||||
"""
|
"""
|
||||||
处理用户登录
|
处理用户登录
|
||||||
|
|
||||||
GET: 显示登录页面
|
GET: 显示登录页面
|
||||||
POST: 处理登录表单提交
|
POST: 处理登录表单提交
|
||||||
"""
|
"""
|
||||||
if request.method == 'POST':
|
if request.method == 'POST':
|
||||||
username = request.form.get('username')
|
username = request.form.get('username')
|
||||||
password = request.form.get('password')
|
password = request.form.get('password')
|
||||||
|
|
||||||
if not username or not password:
|
if not username or not password:
|
||||||
flash('请输入用户名和密码', 'error')
|
flash('请输入用户名和密码', 'error')
|
||||||
return render_template('login.html')
|
return render_template('login.html')
|
||||||
|
|
||||||
# 验证用户
|
# 验证用户
|
||||||
user_data = verify_user(username, password)
|
user_data = verify_user(username, password)
|
||||||
if user_data:
|
if user_data:
|
||||||
@@ -210,9 +208,10 @@ def login():
|
|||||||
else:
|
else:
|
||||||
flash('用户名或密码错误', 'error')
|
flash('用户名或密码错误', 'error')
|
||||||
return render_template('login.html')
|
return render_template('login.html')
|
||||||
|
|
||||||
return render_template('login.html')
|
return render_template('login.html')
|
||||||
|
|
||||||
|
|
||||||
# 登出路由
|
# 登出路由
|
||||||
@app.route('/logout')
|
@app.route('/logout')
|
||||||
def logout():
|
def logout():
|
||||||
@@ -223,6 +222,7 @@ def logout():
|
|||||||
flash('已成功登出', 'info')
|
flash('已成功登出', 'info')
|
||||||
return redirect(url_for('login'))
|
return redirect(url_for('login'))
|
||||||
|
|
||||||
|
|
||||||
# 用户管理页面路由
|
# 用户管理页面路由
|
||||||
@app.route('/user_management')
|
@app.route('/user_management')
|
||||||
@admin_required
|
@admin_required
|
||||||
@@ -233,13 +233,14 @@ def user_management():
|
|||||||
users = get_all_users()
|
users = get_all_users()
|
||||||
return render_template('user_management.html', users=users)
|
return render_template('user_management.html', users=users)
|
||||||
|
|
||||||
|
|
||||||
# 注册新用户路由
|
# 注册新用户路由
|
||||||
@app.route('/register', methods=['GET', 'POST'])
|
@app.route('/register', methods=['GET', 'POST'])
|
||||||
@admin_required
|
@admin_required
|
||||||
def register():
|
def register():
|
||||||
"""
|
"""
|
||||||
注册新用户(仅管理员可访问)
|
注册新用户(仅管理员可访问)
|
||||||
|
|
||||||
GET: 显示注册页面
|
GET: 显示注册页面
|
||||||
POST: 处理注册表单提交
|
POST: 处理注册表单提交
|
||||||
"""
|
"""
|
||||||
@@ -248,26 +249,26 @@ def register():
|
|||||||
password = request.form.get('password')
|
password = request.form.get('password')
|
||||||
confirm_password = request.form.get('confirm_password')
|
confirm_password = request.form.get('confirm_password')
|
||||||
permission = int(request.form.get('permission', 1))
|
permission = int(request.form.get('permission', 1))
|
||||||
|
|
||||||
# 验证输入
|
# 验证输入
|
||||||
if not username or not password:
|
if not username or not password:
|
||||||
flash('请输入用户名和密码', 'error')
|
flash('请输入用户名和密码', 'error')
|
||||||
return render_template('register.html')
|
return render_template('register.html')
|
||||||
|
|
||||||
if password != confirm_password:
|
if password != confirm_password:
|
||||||
flash('两次输入的密码不一致', 'error')
|
flash('两次输入的密码不一致', 'error')
|
||||||
return render_template('register.html')
|
return render_template('register.html')
|
||||||
|
|
||||||
if len(password) < 6:
|
if len(password) < 6:
|
||||||
flash('密码长度至少6位', 'error')
|
flash('密码长度至少6位', 'error')
|
||||||
return render_template('register.html')
|
return render_template('register.html')
|
||||||
|
|
||||||
# 检查用户名是否已存在
|
# 检查用户名是否已存在
|
||||||
existing_user = get_user_by_username(username)
|
existing_user = get_user_by_username(username)
|
||||||
if existing_user:
|
if existing_user:
|
||||||
flash('用户名已存在', 'error')
|
flash('用户名已存在', 'error')
|
||||||
return render_template('register.html')
|
return render_template('register.html')
|
||||||
|
|
||||||
# 创建新用户
|
# 创建新用户
|
||||||
success = create_user(username, password, permission)
|
success = create_user(username, password, permission)
|
||||||
if success:
|
if success:
|
||||||
@@ -276,9 +277,10 @@ def register():
|
|||||||
else:
|
else:
|
||||||
flash('创建用户失败', 'error')
|
flash('创建用户失败', 'error')
|
||||||
return render_template('register.html')
|
return render_template('register.html')
|
||||||
|
|
||||||
return render_template('register.html')
|
return render_template('register.html')
|
||||||
|
|
||||||
|
|
||||||
# 修改用户密码路由
|
# 修改用户密码路由
|
||||||
@app.route('/change_password/<username>', methods=['POST'])
|
@app.route('/change_password/<username>', methods=['POST'])
|
||||||
@admin_required
|
@admin_required
|
||||||
@@ -288,27 +290,28 @@ def change_password(username):
|
|||||||
"""
|
"""
|
||||||
new_password = request.form.get('new_password')
|
new_password = request.form.get('new_password')
|
||||||
confirm_password = request.form.get('confirm_password')
|
confirm_password = request.form.get('confirm_password')
|
||||||
|
|
||||||
if not new_password or not confirm_password:
|
if not new_password or not confirm_password:
|
||||||
flash('请输入新密码', 'error')
|
flash('请输入新密码', 'error')
|
||||||
return redirect(url_for('user_management'))
|
return redirect(url_for('user_management'))
|
||||||
|
|
||||||
if new_password != confirm_password:
|
if new_password != confirm_password:
|
||||||
flash('两次输入的密码不一致', 'error')
|
flash('两次输入的密码不一致', 'error')
|
||||||
return redirect(url_for('user_management'))
|
return redirect(url_for('user_management'))
|
||||||
|
|
||||||
if len(new_password) < 6:
|
if len(new_password) < 6:
|
||||||
flash('密码长度至少6位', 'error')
|
flash('密码长度至少6位', 'error')
|
||||||
return redirect(url_for('user_management'))
|
return redirect(url_for('user_management'))
|
||||||
|
|
||||||
success = update_user_password(username, new_password)
|
success = update_user_password(username, new_password)
|
||||||
if success:
|
if success:
|
||||||
flash(f'用户 {username} 密码修改成功', 'success')
|
flash(f'用户 {username} 密码修改成功', 'success')
|
||||||
else:
|
else:
|
||||||
flash(f'修改用户 {username} 密码失败', 'error')
|
flash(f'修改用户 {username} 密码失败', 'error')
|
||||||
|
|
||||||
return redirect(url_for('user_management'))
|
return redirect(url_for('user_management'))
|
||||||
|
|
||||||
|
|
||||||
# 修改用户权限路由
|
# 修改用户权限路由
|
||||||
@app.route('/change_permission/<username>', methods=['POST'])
|
@app.route('/change_permission/<username>', methods=['POST'])
|
||||||
@admin_required
|
@admin_required
|
||||||
@@ -317,15 +320,16 @@ def change_permission(username):
|
|||||||
修改用户权限(仅管理员可访问)
|
修改用户权限(仅管理员可访问)
|
||||||
"""
|
"""
|
||||||
new_permission = int(request.form.get('permission', 1))
|
new_permission = int(request.form.get('permission', 1))
|
||||||
|
|
||||||
success = update_user_permission(username, new_permission)
|
success = update_user_permission(username, new_permission)
|
||||||
if success:
|
if success:
|
||||||
flash(f'用户 {username} 权限修改成功', 'success')
|
flash(f'用户 {username} 权限修改成功', 'success')
|
||||||
else:
|
else:
|
||||||
flash(f'修改用户 {username} 权限失败', 'error')
|
flash(f'修改用户 {username} 权限失败', 'error')
|
||||||
|
|
||||||
return redirect(url_for('user_management'))
|
return redirect(url_for('user_management'))
|
||||||
|
|
||||||
|
|
||||||
# 删除用户路由
|
# 删除用户路由
|
||||||
@app.route('/delete_user/<username>', methods=['POST'])
|
@app.route('/delete_user/<username>', methods=['POST'])
|
||||||
@admin_required
|
@admin_required
|
||||||
@@ -338,9 +342,10 @@ def delete_user_route(username):
|
|||||||
flash(f'用户 {username} 删除成功', 'success')
|
flash(f'用户 {username} 删除成功', 'success')
|
||||||
else:
|
else:
|
||||||
flash(f'删除用户 {username} 失败', 'error')
|
flash(f'删除用户 {username} 失败', 'error')
|
||||||
|
|
||||||
return redirect(url_for('user_management'))
|
return redirect(url_for('user_management'))
|
||||||
|
|
||||||
|
|
||||||
# 个人设置页面路由
|
# 个人设置页面路由
|
||||||
@app.route('/profile')
|
@app.route('/profile')
|
||||||
@login_required
|
@login_required
|
||||||
@@ -350,6 +355,7 @@ def profile():
|
|||||||
"""
|
"""
|
||||||
return render_template('profile.html')
|
return render_template('profile.html')
|
||||||
|
|
||||||
|
|
||||||
# 修改个人密码路由
|
# 修改个人密码路由
|
||||||
@app.route('/change_own_password', methods=['POST'])
|
@app.route('/change_own_password', methods=['POST'])
|
||||||
@login_required
|
@login_required
|
||||||
@@ -360,29 +366,30 @@ def change_own_password():
|
|||||||
old_password = request.form.get('old_password')
|
old_password = request.form.get('old_password')
|
||||||
new_password = request.form.get('new_password')
|
new_password = request.form.get('new_password')
|
||||||
confirm_password = request.form.get('confirm_password')
|
confirm_password = request.form.get('confirm_password')
|
||||||
|
|
||||||
# 验证输入
|
# 验证输入
|
||||||
if not old_password or not new_password or not confirm_password:
|
if not old_password or not new_password or not confirm_password:
|
||||||
flash('请填写所有密码字段', 'error')
|
flash('请填写所有密码字段', 'error')
|
||||||
return redirect(url_for('profile'))
|
return redirect(url_for('profile'))
|
||||||
|
|
||||||
if new_password != confirm_password:
|
if new_password != confirm_password:
|
||||||
flash('两次输入的新密码不一致', 'error')
|
flash('两次输入的新密码不一致', 'error')
|
||||||
return redirect(url_for('profile'))
|
return redirect(url_for('profile'))
|
||||||
|
|
||||||
if len(new_password) < 6:
|
if len(new_password) < 6:
|
||||||
flash('新密码长度至少6位', 'error')
|
flash('新密码长度至少6位', 'error')
|
||||||
return redirect(url_for('profile'))
|
return redirect(url_for('profile'))
|
||||||
|
|
||||||
# 调用修改密码函数
|
# 调用修改密码函数
|
||||||
success = update_user_own_password(session['user_id'], old_password, new_password)
|
success = update_user_own_password(session['user_id'], old_password, new_password)
|
||||||
if success:
|
if success:
|
||||||
flash('密码修改成功', 'success')
|
flash('密码修改成功', 'success')
|
||||||
else:
|
else:
|
||||||
flash('密码修改失败,请检查旧密码是否正确', 'error')
|
flash('密码修改失败,请检查旧密码是否正确', 'error')
|
||||||
|
|
||||||
return redirect(url_for('profile'))
|
return redirect(url_for('profile'))
|
||||||
|
|
||||||
|
|
||||||
# 个人数据页面路由
|
# 个人数据页面路由
|
||||||
@app.route('/my_data')
|
@app.route('/my_data')
|
||||||
@login_required
|
@login_required
|
||||||
@@ -392,13 +399,13 @@ def my_data():
|
|||||||
"""
|
"""
|
||||||
user_id = session['user_id']
|
user_id = session['user_id']
|
||||||
keyword = request.args.get('keyword', '')
|
keyword = request.args.get('keyword', '')
|
||||||
|
|
||||||
# 查询用户自己的数据
|
# 查询用户自己的数据
|
||||||
if keyword:
|
if keyword:
|
||||||
data = search_data_by_user(user_id, keyword)
|
data = search_data_by_user(user_id, keyword)
|
||||||
else:
|
else:
|
||||||
data = search_data_by_user(user_id)
|
data = search_data_by_user(user_id)
|
||||||
|
|
||||||
# 将data字段从字符串转换回JSON格式以便显示
|
# 将data字段从字符串转换回JSON格式以便显示
|
||||||
processed_data = []
|
processed_data = []
|
||||||
for item in data:
|
for item in data:
|
||||||
@@ -418,7 +425,7 @@ def my_data():
|
|||||||
processed_data.append(item)
|
processed_data.append(item)
|
||||||
else:
|
else:
|
||||||
processed_data.append(item)
|
processed_data.append(item)
|
||||||
|
|
||||||
return render_template('my_data.html', data=processed_data, keyword=keyword)
|
return render_template('my_data.html', data=processed_data, keyword=keyword)
|
||||||
|
|
||||||
# 首页路由
|
# 首页路由
|
||||||
@@ -478,7 +485,7 @@ def upload_image():
|
|||||||
def confirm_data():
|
def confirm_data():
|
||||||
"""
|
"""
|
||||||
确认并录入用户编辑后的数据
|
确认并录入用户编辑后的数据
|
||||||
|
|
||||||
返回:
|
返回:
|
||||||
JSON: 录入成功或失败的响应
|
JSON: 录入成功或失败的响应
|
||||||
"""
|
"""
|
||||||
@@ -487,18 +494,18 @@ def confirm_data():
|
|||||||
request_data = request.get_json()
|
request_data = request.get_json()
|
||||||
if not request_data:
|
if not request_data:
|
||||||
return jsonify({"error": "没有接收到数据"}), 400
|
return jsonify({"error": "没有接收到数据"}), 400
|
||||||
|
|
||||||
# 获取编辑后的数据和图片文件名
|
# 获取编辑后的数据和图片文件名
|
||||||
edited_data = request_data.get('data', {})
|
edited_data = request_data.get('data', {})
|
||||||
image_filename = request_data.get('image', '')
|
image_filename = request_data.get('image', '')
|
||||||
|
|
||||||
if not edited_data:
|
if not edited_data:
|
||||||
return jsonify({"error": "数据不能为空"}), 400
|
return jsonify({"error": "数据不能为空"}), 400
|
||||||
|
|
||||||
# 使用json_converter将JSON数据转换为字符串
|
# 使用json_converter将JSON数据转换为字符串
|
||||||
data_string = json_to_string(edited_data)
|
data_string = json_to_string(edited_data)
|
||||||
print(f"转换后的数据字符串: {data_string}")
|
print(f"转换后的数据字符串: {data_string}")
|
||||||
|
|
||||||
# 构造新的数据结构,只包含data和image字段,并添加用户ID
|
# 构造新的数据结构,只包含data和image字段,并添加用户ID
|
||||||
processed_data = {
|
processed_data = {
|
||||||
"data": data_string,
|
"data": data_string,
|
||||||
@@ -622,17 +629,17 @@ def serve_image(filename):
|
|||||||
@login_required
|
@login_required
|
||||||
def delete_entry(doc_id):
|
def delete_entry(doc_id):
|
||||||
"""
|
"""
|
||||||
根据文档ID删除数据(用户只能删除自己的数据,管理员可以删除所有数据)
|
根据文档ID删除数据
|
||||||
|
|
||||||
参数:
|
参数:
|
||||||
doc_id (str): 要删除的文档ID
|
doc_id (str): 要删除的文档ID
|
||||||
|
|
||||||
返回:
|
返回:
|
||||||
重定向到相应页面或错误信息
|
重定向到所有数据页面或错误信息
|
||||||
"""
|
"""
|
||||||
user_id = session['user_id']
|
user_id = session['user_id']
|
||||||
user_permission = session.get('permission', 1)
|
user_permission = session.get('permission', 1)
|
||||||
|
|
||||||
# 管理员可以删除所有数据,普通用户只能删除自己的数据
|
# 管理员可以删除所有数据,普通用户只能删除自己的数据
|
||||||
if user_permission == 0: # 管理员
|
if user_permission == 0: # 管理员
|
||||||
success = delete_by_id(doc_id)
|
success = delete_by_id(doc_id)
|
||||||
@@ -640,13 +647,50 @@ def delete_entry(doc_id):
|
|||||||
else: # 普通用户
|
else: # 普通用户
|
||||||
success = delete_data_by_id(doc_id, user_id)
|
success = delete_data_by_id(doc_id, user_id)
|
||||||
redirect_url = 'my_data'
|
redirect_url = 'my_data'
|
||||||
|
|
||||||
if success:
|
if success:
|
||||||
return redirect(url_for(redirect_url))
|
return redirect(url_for(redirect_url))
|
||||||
else:
|
else:
|
||||||
return "删除失败", 500
|
return "删除失败", 500
|
||||||
|
|
||||||
# 编辑数据路由
|
|
||||||
|
# 批量删除数据路由
|
||||||
|
@app.route('/batch_delete', methods=['POST'])
|
||||||
|
@admin_required
|
||||||
|
def batch_delete():
|
||||||
|
"""
|
||||||
|
批量删除选中的数据(仅管理员可访问)
|
||||||
|
|
||||||
|
返回:
|
||||||
|
重定向到所有数据页面或错误信息
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# 获取选中的文档ID列表
|
||||||
|
doc_ids = request.form.getlist('doc_ids')
|
||||||
|
|
||||||
|
if not doc_ids:
|
||||||
|
flash('请选择要删除的记录', 'error')
|
||||||
|
return redirect(url_for('show_all'))
|
||||||
|
|
||||||
|
# 批量删除选中的文档
|
||||||
|
success_count = 0
|
||||||
|
for doc_id in doc_ids:
|
||||||
|
if delete_by_id(doc_id):
|
||||||
|
success_count += 1
|
||||||
|
|
||||||
|
if success_count > 0:
|
||||||
|
flash(f'成功删除 {success_count} 条记录', 'success')
|
||||||
|
else:
|
||||||
|
flash('删除失败,请重试', 'error')
|
||||||
|
|
||||||
|
return redirect(url_for('show_all'))
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"批量删除失败: {str(e)}")
|
||||||
|
flash('批量删除失败,请重试', 'error')
|
||||||
|
return redirect(url_for('show_all'))
|
||||||
|
|
||||||
|
|
||||||
@app.route('/edit/<doc_id>', methods=['GET', 'POST'])
|
@app.route('/edit/<doc_id>', methods=['GET', 'POST'])
|
||||||
@login_required
|
@login_required
|
||||||
def edit_entry(doc_id):
|
def edit_entry(doc_id):
|
||||||
@@ -663,37 +707,37 @@ def edit_entry(doc_id):
|
|||||||
)
|
)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
doc = response.json()
|
doc = response.json()
|
||||||
|
|
||||||
if not doc.get("found"):
|
if not doc.get("found"):
|
||||||
flash('数据不存在', 'error')
|
flash('数据不存在', 'error')
|
||||||
return redirect(url_for('my_data'))
|
return redirect(url_for('my_data'))
|
||||||
|
|
||||||
# 检查权限
|
# 检查权限
|
||||||
user_id = session['user_id']
|
user_id = session['user_id']
|
||||||
user_permission = session.get('permission', 1)
|
user_permission = session.get('permission', 1)
|
||||||
doc_user_id = doc["_source"].get("user_id")
|
doc_user_id = doc["_source"].get("user_id")
|
||||||
|
|
||||||
# 管理员可以编辑所有数据,普通用户只能编辑自己的数据
|
# 管理员可以编辑所有数据,普通用户只能编辑自己的数据
|
||||||
if user_permission != 0 and doc_user_id != user_id:
|
if user_permission != 0 and doc_user_id != user_id:
|
||||||
flash('您无权编辑此数据', 'error')
|
flash('您无权编辑此数据', 'error')
|
||||||
return redirect(url_for('my_data'))
|
return redirect(url_for('my_data'))
|
||||||
|
|
||||||
# 解析数据
|
# 解析数据
|
||||||
data_str = doc["_source"].get("data", "{}")
|
data_str = doc["_source"].get("data", "{}")
|
||||||
original_data = string_to_json(data_str)
|
original_data = string_to_json(data_str)
|
||||||
|
|
||||||
edit_data = {
|
edit_data = {
|
||||||
'_id': doc_id,
|
'_id': doc_id,
|
||||||
'image': doc["_source"].get('image', ''),
|
'image': doc["_source"].get('image', ''),
|
||||||
**original_data
|
**original_data
|
||||||
}
|
}
|
||||||
|
|
||||||
return render_template('edit.html', data=edit_data)
|
return render_template('edit.html', data=edit_data)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
flash('获取数据失败', 'error')
|
flash('获取数据失败', 'error')
|
||||||
return redirect(url_for('my_data'))
|
return redirect(url_for('my_data'))
|
||||||
|
|
||||||
else: # POST 请求 - 保存编辑
|
else: # POST 请求 - 保存编辑
|
||||||
try:
|
try:
|
||||||
# 获取编辑后的数据
|
# 获取编辑后的数据
|
||||||
@@ -701,37 +745,35 @@ def edit_entry(doc_id):
|
|||||||
for key, value in request.form.items():
|
for key, value in request.form.items():
|
||||||
if key != '_id' and key != 'image':
|
if key != '_id' and key != 'image':
|
||||||
edited_data[key] = value
|
edited_data[key] = value
|
||||||
|
|
||||||
# 转换为字符串格式
|
# 转换为字符串格式
|
||||||
data_string = json_to_string(edited_data)
|
data_string = json_to_string(edited_data)
|
||||||
|
|
||||||
# 构造更新数据
|
# 构造更新数据
|
||||||
updated_data = {
|
updated_data = {
|
||||||
"data": data_string,
|
"data": data_string,
|
||||||
"image": request.form.get('image', ''),
|
"image": request.form.get('image', ''),
|
||||||
"user_id": session['user_id']
|
"user_id": session['user_id']
|
||||||
}
|
}
|
||||||
|
|
||||||
# 更新数据
|
# 更新数据
|
||||||
success = update_data_by_id(doc_id, updated_data, session['user_id'])
|
success = update_data_by_id(doc_id, updated_data, session['user_id'])
|
||||||
|
|
||||||
if success:
|
if success:
|
||||||
flash('数据更新成功', 'success')
|
flash('数据更新成功', 'success')
|
||||||
else:
|
else:
|
||||||
flash('数据更新失败', 'error')
|
flash('数据更新失败', 'error')
|
||||||
|
|
||||||
# 根据用户权限重定向
|
# 根据用户权限重定向
|
||||||
if session.get('permission', 1) == 0:
|
if session.get('permission', 1) == 0:
|
||||||
return redirect(url_for('show_all'))
|
return redirect(url_for('show_all'))
|
||||||
else:
|
else:
|
||||||
return redirect(url_for('my_data'))
|
return redirect(url_for('my_data'))
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
flash('保存数据失败', 'error')
|
flash('保存数据失败', 'error')
|
||||||
return redirect(url_for('my_data'))
|
return redirect(url_for('my_data'))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# 主程序入口
|
# 主程序入口
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
# 创建Elasticsearch索引
|
# 创建Elasticsearch索引
|
||||||
|
|||||||
@@ -27,50 +27,87 @@
|
|||||||
margin-bottom: 15px;
|
margin-bottom: 15px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 表格容器 - 顶部边距调整 */
|
/* 卡片容器样式 */
|
||||||
.table-container {
|
.data-cards {
|
||||||
overflow-x: auto;
|
display: grid;
|
||||||
margin-top: 15px; /* 减少顶部间距 */
|
grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
|
||||||
|
gap: 20px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 卡片样式 */
|
||||||
|
.data-card {
|
||||||
|
background-color: white;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
|
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
|
||||||
|
padding: 20px;
|
||||||
|
border: 1px solid #e0e0e0;
|
||||||
|
transition: transform 0.3s, box-shadow 0.3s;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 表格样式 */
|
.data-card:hover {
|
||||||
table {
|
transform: translateY(-2px);
|
||||||
width: 100%;
|
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
|
||||||
border-collapse: collapse;
|
|
||||||
font-family: 'Segoe UI', Arial, sans-serif;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 表头样式 */
|
/* 卡片头部样式 */
|
||||||
thead {
|
.card-header {
|
||||||
background: linear-gradient(135deg, #3498db, #1a5276);
|
display: flex;
|
||||||
color: white;
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 15px;
|
||||||
|
padding-bottom: 15px;
|
||||||
|
border-bottom: 1px solid #f0f0f0;
|
||||||
}
|
}
|
||||||
|
|
||||||
th {
|
.card-header h3 {
|
||||||
padding: 16px 12px;
|
margin: 0;
|
||||||
text-align: left;
|
color: #333;
|
||||||
|
font-size: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 卡片内容样式 */
|
||||||
|
.card-content {
|
||||||
|
margin-bottom: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field-item {
|
||||||
|
display: flex;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field-key {
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
|
color: #333;
|
||||||
|
min-width: 120px;
|
||||||
|
margin-right: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 表格行样式 */
|
.field-value {
|
||||||
tbody tr {
|
color: #666;
|
||||||
border-bottom: 1px solid #eef1f5;
|
flex: 1;
|
||||||
transition: background-color 0.3s;
|
word-break: break-word;
|
||||||
}
|
}
|
||||||
|
|
||||||
tbody tr:nth-child(even) {
|
/* 卡片图片样式 */
|
||||||
background-color: #f8fafc;
|
.card-image {
|
||||||
|
text-align: center;
|
||||||
|
margin-top: 15px;
|
||||||
|
padding-top: 15px;
|
||||||
|
border-top: 1px solid #f0f0f0;
|
||||||
}
|
}
|
||||||
|
|
||||||
tbody tr:hover {
|
.card-image img {
|
||||||
background-color: #e3f2fd;
|
max-width: 100%;
|
||||||
}
|
max-height: 200px;
|
||||||
|
border-radius: 4px;
|
||||||
td {
|
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||||
padding: 14px 12px;
|
|
||||||
color: #4a5568;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 操作按钮样式 */
|
/* 操作按钮样式 */
|
||||||
@@ -81,6 +118,17 @@
|
|||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
transition: all 0.3s;
|
transition: all 0.3s;
|
||||||
|
margin: 0 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.edit-btn {
|
||||||
|
background: linear-gradient(to right, #4CAF50, #45a049);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.edit-btn:hover {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow: 0 4px 8px rgba(76, 175, 80, 0.3);
|
||||||
}
|
}
|
||||||
|
|
||||||
.delete-btn {
|
.delete-btn {
|
||||||
@@ -117,48 +165,250 @@
|
|||||||
padding: 40px 0;
|
padding: 40px 0;
|
||||||
color: #a0aec0;
|
color: #a0aec0;
|
||||||
font-style: italic;
|
font-style: italic;
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 响应式设计 */
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.data-cards {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-header {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-actions {
|
||||||
|
align-self: flex-end;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field-item {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field-key {
|
||||||
|
min-width: auto;
|
||||||
|
margin-bottom: 5px;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<div class="container">
|
<div class="container">
|
||||||
<h2>所有已录入的奖项信息</h2>
|
<h2>所有已录入的奖项信息</h2>
|
||||||
<p>在此页面可以查看所有已录入的成果信息,并进行删除操作</p>
|
<p>在此页面可以查看所有已录入的成果信息,并进行编辑和删除操作</p>
|
||||||
|
|
||||||
<div class="table-container">
|
<!-- 批量操作区域 -->
|
||||||
<table>
|
<div class="batch-operations" style="margin-bottom: 20px; padding: 15px; background-color: #f8f9fa; border-radius: 8px; border: 1px solid #e0e0e0;">
|
||||||
<thead>
|
<div style="display: flex; align-items: center; gap: 15px;">
|
||||||
<tr>
|
<div style="display: flex; align-items: center; gap: 8px;">
|
||||||
<th>比赛/论文名称</th>
|
<input type="checkbox" id="select-all" onchange="toggleSelectAll(this.checked)">
|
||||||
<th>项目名称</th>
|
<label for="select-all" style="font-weight: 600; color: #333;">全选</label>
|
||||||
<th>学生</th>
|
</div>
|
||||||
<th>指导老师</th>
|
<button type="button" class="batch-delete-btn" onclick="batchDelete()" style="padding: 8px 16px; background-color: #dc3545; color: white; border: none; border-radius: 4px; cursor: pointer; font-weight: 500; transition: background-color 0.3s;">
|
||||||
<th style="text-align: center;">操作</th>
|
批量删除选中项
|
||||||
</tr>
|
</button>
|
||||||
</thead>
|
<span id="selected-count" style="color: #666; font-size: 14px;">已选择 0 项</span>
|
||||||
<tbody>
|
</div>
|
||||||
{% if data %}
|
</div>
|
||||||
{% for item in data %}
|
|
||||||
<tr>
|
<div class="data-cards">
|
||||||
<td>{{ item.id or '无' }}</td>
|
{% if data %}
|
||||||
<td>{{ item.name or '无' }}</td>
|
{% for item in data %}
|
||||||
<td>{% if item.students is string %}{{ item.students or '无' }}{% else %}{{ item.students|join(', ') if item.students else '无' }}{% endif %}</td>
|
<div class="data-card">
|
||||||
<td>{% if item.teacher is string %}{{ item.teacher or '无' }}{% else %}{{ item.teacher|join(', ') if item.teacher else '无' }}{% endif %}</td>
|
<div class="card-header">
|
||||||
<td style="text-align: center;">
|
<div style="display: flex; align-items: center; gap: 15px;">
|
||||||
<form action="{{ url_for('delete_entry', doc_id=item._id) }}" method="POST" onsubmit="return confirm('确定要删除这条记录吗?')">
|
<input type="checkbox" class="doc-checkbox" value="{{ item._id }}" onchange="updateSelectedCount()">
|
||||||
<button type="submit" class="action-button delete-btn">删除</button>
|
<h3>记录 {{ loop.index }}</h3>
|
||||||
</form>
|
</div>
|
||||||
</td>
|
<div class="card-actions">
|
||||||
</tr>
|
<a href="{{ url_for('edit_entry', doc_id=item._id) }}" class="action-button edit-btn">编辑</a>
|
||||||
{% endfor %}
|
<button type="button" class="action-button delete-btn" onclick="deleteRecord('{{ item._id }}')">删除</button>
|
||||||
{% else %}
|
</div>
|
||||||
<tr>
|
</div>
|
||||||
<td colspan="5" class="no-data">暂无数据</td>
|
|
||||||
</tr>
|
<div class="card-content">
|
||||||
{% endif %}
|
{% if item.data %}
|
||||||
</tbody>
|
{# 从原始数据中解析字段 #}
|
||||||
</table>
|
{% set data_string = item.data %}
|
||||||
|
{% set pairs = data_string.split('|###|') %}
|
||||||
|
|
||||||
|
{% for pair in pairs %}
|
||||||
|
{% if ':' in pair %}
|
||||||
|
{% set key_value = pair.split(':', 1) %}
|
||||||
|
{% set field_key = key_value[0].strip() %}
|
||||||
|
{% set field_value = key_value[1].strip() %}
|
||||||
|
|
||||||
|
{# 处理列表格式 [item1|##|item2] #}
|
||||||
|
{% if field_value.startswith('[') and field_value.endswith(']') %}
|
||||||
|
{% set list_content = field_value[1:-1] %}
|
||||||
|
{% set field_value = list_content.split('|##|')|join(', ') %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="field-item">
|
||||||
|
<span class="field-key">{{ field_key }}:</span>
|
||||||
|
<span class="field-value">{{ field_value or '无' }}</span>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
{% else %}
|
||||||
|
{# 如果没有data字段,显示解析后的字段 #}
|
||||||
|
{% for key, value in item.items() %}
|
||||||
|
{% if key not in ['_id', 'image'] %}
|
||||||
|
<div class="field-item">
|
||||||
|
<span class="field-key">{{ key }}:</span>
|
||||||
|
<span class="field-value">
|
||||||
|
{% if value is sequence and value is not string %}
|
||||||
|
{{ value|join(', ') if value else '无' }}
|
||||||
|
{% else %}
|
||||||
|
{{ value or '无' }}
|
||||||
|
{% endif %}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
{% else %}
|
||||||
|
<div class="no-data">暂无数据</div>
|
||||||
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<a href="{{ url_for('index') }}" class="back-btn">返回首页</a>
|
<a href="{{ url_for('index') }}" class="back-btn">返回首页</a>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// 全选/取消全选功能
|
||||||
|
function toggleSelectAll(checked) {
|
||||||
|
const checkboxes = document.querySelectorAll('.doc-checkbox');
|
||||||
|
checkboxes.forEach(checkbox => {
|
||||||
|
checkbox.checked = checked;
|
||||||
|
});
|
||||||
|
updateSelectedCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新选择计数
|
||||||
|
function updateSelectedCount() {
|
||||||
|
const checkboxes = document.querySelectorAll('.doc-checkbox');
|
||||||
|
const selectedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
|
||||||
|
document.getElementById('selected-count').textContent = `已选择 ${selectedCount} 项`;
|
||||||
|
|
||||||
|
// 更新全选复选框状态
|
||||||
|
const selectAllCheckbox = document.getElementById('select-all');
|
||||||
|
if (selectedCount === 0) {
|
||||||
|
selectAllCheckbox.checked = false;
|
||||||
|
selectAllCheckbox.indeterminate = false;
|
||||||
|
} else if (selectedCount === checkboxes.length) {
|
||||||
|
selectAllCheckbox.checked = true;
|
||||||
|
selectAllCheckbox.indeterminate = false;
|
||||||
|
} else {
|
||||||
|
selectAllCheckbox.checked = false;
|
||||||
|
selectAllCheckbox.indeterminate = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 批量删除功能
|
||||||
|
function batchDelete() {
|
||||||
|
const checkboxes = document.querySelectorAll('.doc-checkbox:checked');
|
||||||
|
if (checkboxes.length === 0) {
|
||||||
|
alert('请至少选择一条记录进行删除');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const confirmMessage = `确定要删除选中的 ${checkboxes.length} 条记录吗?此操作不可撤销。`;
|
||||||
|
if (!confirm(confirmMessage)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 收集选中的文档ID
|
||||||
|
const docIds = Array.from(checkboxes).map(cb => cb.value);
|
||||||
|
|
||||||
|
// 创建表单并提交
|
||||||
|
const form = document.createElement('form');
|
||||||
|
form.method = 'POST';
|
||||||
|
form.action = '/batch_delete';
|
||||||
|
|
||||||
|
docIds.forEach(docId => {
|
||||||
|
const input = document.createElement('input');
|
||||||
|
input.type = 'hidden';
|
||||||
|
input.name = 'doc_ids';
|
||||||
|
input.value = docId;
|
||||||
|
form.appendChild(input);
|
||||||
|
});
|
||||||
|
|
||||||
|
document.body.appendChild(form);
|
||||||
|
form.submit();
|
||||||
|
|
||||||
|
// 提交后自动刷新页面
|
||||||
|
form.addEventListener('submit', function() {
|
||||||
|
setTimeout(function() {
|
||||||
|
window.location.reload();
|
||||||
|
}, 1000); // 1秒后刷新页面,给服务器处理时间
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 页面加载时初始化
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
updateSelectedCount();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 单个删除功能
|
||||||
|
function deleteRecord(docId) {
|
||||||
|
// 显示删除确认模态框
|
||||||
|
showDeleteModal(docId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 显示删除确认模态框
|
||||||
|
function showDeleteModal(docId) {
|
||||||
|
// 创建模态框HTML
|
||||||
|
const modalHtml = `
|
||||||
|
<div id="deleteModal" class="modal" style="display: block;">
|
||||||
|
<div class="modal-content modal-small">
|
||||||
|
<h3>确认删除</h3>
|
||||||
|
<p>您确定要删除这条数据吗?此操作不可撤销。</p>
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button onclick="closeDeleteModal()" class="btn btn-secondary">取消</button>
|
||||||
|
<button onclick="confirmDeleteRecord('${docId}')" class="btn btn-danger">确认删除</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
// 添加模态框到页面
|
||||||
|
document.body.insertAdjacentHTML('beforeend', modalHtml);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 关闭删除确认模态框
|
||||||
|
function closeDeleteModal() {
|
||||||
|
const modal = document.getElementById('deleteModal');
|
||||||
|
if (modal) {
|
||||||
|
modal.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 确认删除记录
|
||||||
|
function confirmDeleteRecord(docId) {
|
||||||
|
// 关闭模态框
|
||||||
|
closeDeleteModal();
|
||||||
|
|
||||||
|
// 创建表单并提交
|
||||||
|
const form = document.createElement('form');
|
||||||
|
form.method = 'POST';
|
||||||
|
form.action = '/delete/' + docId;
|
||||||
|
|
||||||
|
document.body.appendChild(form);
|
||||||
|
form.submit();
|
||||||
|
|
||||||
|
// 提交后自动刷新页面
|
||||||
|
setTimeout(function() {
|
||||||
|
window.location.reload();
|
||||||
|
}, 1000); // 1秒后刷新页面,给服务器处理时间
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
256
templates/edited.html
Normal file
256
templates/edited.html
Normal file
@@ -0,0 +1,256 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
|
||||||
|
{% block title %}编辑成果信息 - 紫金·稷下薪火·云枢智海师生成果共创系统{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<style>
|
||||||
|
/* 基础样式重置 */
|
||||||
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||||
|
|
||||||
|
/* 容器样式 */
|
||||||
|
.container {
|
||||||
|
max-width: 800px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 标题样式 */
|
||||||
|
h2 {
|
||||||
|
color: #2c3e50;
|
||||||
|
border-bottom: 2px solid #3498db;
|
||||||
|
padding-bottom: 8px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 表单样式 */
|
||||||
|
.form-container {
|
||||||
|
background: white;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
|
||||||
|
padding: 30px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #2c3e50;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input,
|
||||||
|
.form-group textarea {
|
||||||
|
width: 100%;
|
||||||
|
padding: 12px;
|
||||||
|
border: 2px solid #e1e8ed;
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 14px;
|
||||||
|
transition: border-color 0.3s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input:focus,
|
||||||
|
.form-group textarea:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: #3498db;
|
||||||
|
box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group textarea {
|
||||||
|
resize: vertical;
|
||||||
|
min-height: 80px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-hint {
|
||||||
|
font-size: 12px;
|
||||||
|
color: #7f8c8d;
|
||||||
|
margin-top: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 按钮样式 */
|
||||||
|
.button-group {
|
||||||
|
display: flex;
|
||||||
|
gap: 15px;
|
||||||
|
margin-top: 30px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn {
|
||||||
|
padding: 12px 24px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.3s;
|
||||||
|
text-decoration: none;
|
||||||
|
display: inline-block;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
background: linear-gradient(to right, #3498db, #2980b9);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow: 0 4px 8px rgba(52, 152, 219, 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background: linear-gradient(to right, #95a5a6, #7f8c8d);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow: 0 4px 8px rgba(149, 165, 166, 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger {
|
||||||
|
background: linear-gradient(to right, #e74c3c, #c0392b);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger:hover {
|
||||||
|
transform: translateY(-2px);
|
||||||
|
box-shadow: 0 4px 8px rgba(231, 76, 60, 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 图片预览样式 */
|
||||||
|
.image-preview {
|
||||||
|
margin-top: 10px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-preview img {
|
||||||
|
max-width: 200px;
|
||||||
|
max-height: 200px;
|
||||||
|
border-radius: 6px;
|
||||||
|
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 错误提示样式 */
|
||||||
|
.error-message {
|
||||||
|
color: #e74c3c;
|
||||||
|
font-size: 12px;
|
||||||
|
margin-top: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 必填字段标记 */
|
||||||
|
.required {
|
||||||
|
color: #e74c3c;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<div class="container">
|
||||||
|
<h2>编辑成果信息</h2>
|
||||||
|
|
||||||
|
<div class="form-container">
|
||||||
|
<form action="{{ url_for('update_entry', doc_id=document._id) }}" method="POST" id="editForm">
|
||||||
|
{% if document.data %}
|
||||||
|
{# 从原始数据中解析字段 #}
|
||||||
|
{% set data_string = document.data %}
|
||||||
|
{% set pairs = data_string.split('|###|') %}
|
||||||
|
|
||||||
|
{% for pair in pairs %}
|
||||||
|
{% if ':' in pair %}
|
||||||
|
{% set key_value = pair.split(':', 1) %}
|
||||||
|
{% set field_key = key_value[0].strip() %}
|
||||||
|
{% set field_value = key_value[1].strip() %}
|
||||||
|
|
||||||
|
{# 处理列表格式 [item1|##|item2] #}
|
||||||
|
{% if field_value.startswith('[') and field_value.endswith(']') %}
|
||||||
|
{% set list_content = field_value[1:-1] %}
|
||||||
|
{% set field_value = list_content.split('|##|')|join(', ') %}
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="field_{{ loop.index }}">{{ field_key }} <span class="required">*</span></label>
|
||||||
|
<input type="text" id="field_{{ loop.index }}" name="field_{{ loop.index }}" value="{{ field_value }}" required>
|
||||||
|
<input type="hidden" name="key_{{ loop.index }}" value="{{ field_key }}">
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
{% else %}
|
||||||
|
{# 如果没有data字段,显示提示信息 #}
|
||||||
|
<div class="form-group">
|
||||||
|
<p style="color: #e74c3c; text-align: center;">该记录没有可编辑的数据</p>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if document.image %}
|
||||||
|
<div class="form-group">
|
||||||
|
<label>原图片预览</label>
|
||||||
|
<div class="image-preview">
|
||||||
|
<img src="{{ url_for('serve_image', filename=document.image) }}" alt="原图片" onerror="this.style.display='none'">
|
||||||
|
</div>
|
||||||
|
<div class="form-hint">当前关联的图片,编辑时无法修改图片</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="button-group">
|
||||||
|
<button type="submit" class="btn btn-primary">保存修改</button>
|
||||||
|
<a href="{{ url_for('show_all') }}" class="btn btn-secondary">取消返回</a>
|
||||||
|
<button type="button" class="btn btn-danger" onclick="confirmDelete()">删除记录</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// 表单验证
|
||||||
|
document.getElementById('editForm').addEventListener('submit', function(e) {
|
||||||
|
// 检查所有字段是否都有值
|
||||||
|
const inputs = document.querySelectorAll('input[type="text"]');
|
||||||
|
let hasEmptyField = false;
|
||||||
|
|
||||||
|
inputs.forEach(input => {
|
||||||
|
if (!input.value.trim()) {
|
||||||
|
hasEmptyField = true;
|
||||||
|
input.style.borderColor = '#e74c3c';
|
||||||
|
} else {
|
||||||
|
input.style.borderColor = '#e1e8ed';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (hasEmptyField) {
|
||||||
|
e.preventDefault();
|
||||||
|
alert('所有字段都必须填写!');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
// 删除确认
|
||||||
|
function confirmDelete() {
|
||||||
|
if (confirm('确定要删除这条记录吗?此操作不可撤销!')) {
|
||||||
|
// 创建删除表单并提交
|
||||||
|
const form = document.createElement('form');
|
||||||
|
form.method = 'POST';
|
||||||
|
form.action = '{{ url_for("delete_entry", doc_id=document._id) }}';
|
||||||
|
document.body.appendChild(form);
|
||||||
|
form.submit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 自动格式化逗号分隔的值
|
||||||
|
document.querySelectorAll('input[type="text"]').forEach(input => {
|
||||||
|
input.addEventListener('blur', function(e) {
|
||||||
|
const value = e.target.value.trim();
|
||||||
|
if (value && value.includes(',')) {
|
||||||
|
// 格式化逗号分隔的值
|
||||||
|
const formatted = value
|
||||||
|
.split(',')
|
||||||
|
.map(item => item.trim())
|
||||||
|
.filter(item => item)
|
||||||
|
.join(', ');
|
||||||
|
e.target.value = formatted;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
{% endblock %}
|
||||||
@@ -99,7 +99,7 @@
|
|||||||
<p>您确定要删除这条数据吗?此操作不可撤销。</p>
|
<p>您确定要删除这条数据吗?此操作不可撤销。</p>
|
||||||
<div class="modal-actions">
|
<div class="modal-actions">
|
||||||
<button onclick="closeDeleteModal()" class="btn btn-secondary">取消</button>
|
<button onclick="closeDeleteModal()" class="btn btn-secondary">取消</button>
|
||||||
<form id="deleteForm" method="POST" style="display: inline;">
|
<form id="deleteForm" method="POST" style="display: inline;" onsubmit="handleDeleteSubmit(event)">
|
||||||
<button type="submit" class="btn btn-danger">确认删除</button>
|
<button type="submit" class="btn btn-danger">确认删除</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
@@ -470,6 +470,23 @@ function closeDeleteModal() {
|
|||||||
document.getElementById('deleteModal').style.display = 'none';
|
document.getElementById('deleteModal').style.display = 'none';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 处理删除表单提交
|
||||||
|
function handleDeleteSubmit(event) {
|
||||||
|
// 关闭模态框
|
||||||
|
closeDeleteModal();
|
||||||
|
|
||||||
|
// 显示删除中的提示
|
||||||
|
const submitButton = event.target.querySelector('button[type="submit"]');
|
||||||
|
const originalText = submitButton.textContent;
|
||||||
|
submitButton.textContent = '删除中...';
|
||||||
|
submitButton.disabled = true;
|
||||||
|
|
||||||
|
// 提交表单后自动刷新页面
|
||||||
|
setTimeout(function() {
|
||||||
|
window.location.reload();
|
||||||
|
}, 1000); // 1秒后刷新页面,给服务器处理时间
|
||||||
|
}
|
||||||
|
|
||||||
// 点击模态框外部关闭
|
// 点击模态框外部关闭
|
||||||
window.onclick = function(event) {
|
window.onclick = function(event) {
|
||||||
const imageModal = document.getElementById('imageModal');
|
const imageModal = document.getElementById('imageModal');
|
||||||
|
|||||||
Reference in New Issue
Block a user