Compare commits
13 Commits
main
...
3f673f2f69
| Author | SHA1 | Date | |
|---|---|---|---|
| 3f673f2f69 | |||
| 83a9dd04ba | |||
| 0e1d3e54d1 | |||
| 2c31e1571f | |||
| 127f5c5926 | |||
| cf57f981c0 | |||
| 30999e1de4 | |||
| be054e70ea | |||
| d37d60b896 | |||
| 1bbd777565 | |||
| f3aec9a18d | |||
| 61b1d93718 | |||
| aba94c074a |
0
Achievement_Inputing/__init__.py
Normal file
0
Achievement_Inputing/__init__.py
Normal file
16
Achievement_Inputing/asgi.py
Normal file
16
Achievement_Inputing/asgi.py
Normal file
@@ -0,0 +1,16 @@
|
||||
"""
|
||||
ASGI config for Achievement_Inputing project.
|
||||
|
||||
It exposes the ASGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/5.2/howto/deployment/asgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.asgi import get_asgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Achievement_Inputing.settings')
|
||||
|
||||
application = get_asgi_application()
|
||||
159
Achievement_Inputing/settings.py
Normal file
159
Achievement_Inputing/settings.py
Normal file
@@ -0,0 +1,159 @@
|
||||
"""
|
||||
Django settings for Achievement_Inputing project.
|
||||
|
||||
Generated by 'django-admin startproject' using Django 5.2.8.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/5.2/topics/settings/
|
||||
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/5.2/ref/settings/
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
import os
|
||||
from elastic.indexes import INDEX_NAME
|
||||
|
||||
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = 'django-insecure-p^*6tak7wy1z#bw__#o^s5hsydearm=(-s(km!-61j2(#)*+-t'
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS = ["127.0.0.1", "localhost"]
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
'accounts',
|
||||
'main',
|
||||
'elastic',
|
||||
'django_elasticsearch_dsl',
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
'django.middleware.security.SecurityMiddleware',
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
]
|
||||
|
||||
ROOT_URLCONF = 'Achievement_Inputing.urls'
|
||||
|
||||
TEMPLATES = [
|
||||
{
|
||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
||||
'DIRS': [],
|
||||
'APP_DIRS': True,
|
||||
'OPTIONS': {
|
||||
'context_processors': [
|
||||
'django.template.context_processors.request',
|
||||
'django.contrib.auth.context_processors.auth',
|
||||
'django.contrib.messages.context_processors.messages',
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
WSGI_APPLICATION = 'Achievement_Inputing.wsgi.application'
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': BASE_DIR / 'db.sqlite3',
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# Password validation
|
||||
# https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators
|
||||
|
||||
AUTH_PASSWORD_VALIDATORS = [
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# Internationalization
|
||||
# https://docs.djangoproject.com/en/5.2/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = 'en-us'
|
||||
|
||||
TIME_ZONE = 'UTC'
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
USE_TZ = True
|
||||
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/5.2/howto/static-files/
|
||||
|
||||
STATIC_URL = 'static/'
|
||||
|
||||
# Media files (uploaded images)
|
||||
MEDIA_URL = '/media/'
|
||||
MEDIA_ROOT = BASE_DIR / 'media'
|
||||
|
||||
# Security settings for cookies and headers (dev-friendly defaults)
|
||||
SESSION_COOKIE_HTTPONLY = True
|
||||
SESSION_COOKIE_SAMESITE = 'Lax'
|
||||
SESSION_COOKIE_SECURE = False if DEBUG else True
|
||||
|
||||
CSRF_COOKIE_SECURE = False if DEBUG else True
|
||||
CSRF_COOKIE_SAMESITE = 'Lax'
|
||||
|
||||
X_FRAME_OPTIONS = 'DENY'
|
||||
|
||||
# Default primary key field type
|
||||
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field
|
||||
|
||||
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
||||
|
||||
# Elasticsearch configuration
|
||||
ELASTICSEARCH_DSL = {
|
||||
'default': {
|
||||
'hosts': 'localhost:9200'
|
||||
},
|
||||
}
|
||||
|
||||
# Elasticsearch index settings
|
||||
ELASTICSEARCH_INDEX_NAMES = {
|
||||
'elastic.documents.AchievementDocument': INDEX_NAME,
|
||||
'elastic.documents.UserDocument': INDEX_NAME,
|
||||
}
|
||||
|
||||
# AI Studio/OpenAI client settings
|
||||
AISTUDIO_API_KEY = os.environ.get('AISTUDIO_API_KEY', '')
|
||||
OPENAI_BASE_URL = os.environ.get('OPENAI_BASE_URL', 'https://aistudio.baidu.com/llm/lmapi/v3')
|
||||
32
Achievement_Inputing/urls.py
Normal file
32
Achievement_Inputing/urls.py
Normal file
@@ -0,0 +1,32 @@
|
||||
"""
|
||||
URL configuration for Achievement_Inputing project.
|
||||
|
||||
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||
https://docs.djangoproject.com/en/5.2/topics/http/urls/
|
||||
Examples:
|
||||
Function views
|
||||
1. Add an import: from my_app import views
|
||||
2. Add a URL to urlpatterns: path('', views.home, name='home')
|
||||
Class-based views
|
||||
1. Add an import: from other_app.views import Home
|
||||
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
|
||||
Including another URLconf
|
||||
1. Import the include() function: from django.urls import include, path
|
||||
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
||||
"""
|
||||
from django.contrib import admin
|
||||
from django.urls import path, include
|
||||
from django.conf import settings
|
||||
from django.conf.urls.static import static
|
||||
from main.views import home as main_home
|
||||
|
||||
urlpatterns = [
|
||||
path('admin/', admin.site.urls),
|
||||
path('accounts/', include('accounts.urls', namespace='accounts')),
|
||||
path('main/', include('main.urls', namespace='main')),
|
||||
path('elastic/', include('elastic.urls', namespace='elastic')),
|
||||
path('', main_home, name='root_home'),
|
||||
]
|
||||
|
||||
if settings.DEBUG:
|
||||
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
||||
16
Achievement_Inputing/wsgi.py
Normal file
16
Achievement_Inputing/wsgi.py
Normal file
@@ -0,0 +1,16 @@
|
||||
"""
|
||||
WSGI config for Achievement_Inputing project.
|
||||
|
||||
It exposes the WSGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/5.2/howto/deployment/wsgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Achievement_Inputing.settings')
|
||||
|
||||
application = get_wsgi_application()
|
||||
780
ESConnect.py
780
ESConnect.py
@@ -1,780 +0,0 @@
|
||||
from elasticsearch import Elasticsearch
|
||||
# import os
|
||||
# import json
|
||||
import hashlib
|
||||
import requests
|
||||
import json
|
||||
|
||||
# Elasticsearch连接配置
|
||||
ES_URL = "http://localhost:9200"
|
||||
AUTH = None # 如需认证则改为("用户名","密码")
|
||||
|
||||
# document=os.open('results/output.json', os.O_RDONLY)
|
||||
|
||||
# 创建Elasticsearch客户端实例,连接到本地Elasticsearch服务
|
||||
es = Elasticsearch(["http://localhost:9200"])
|
||||
|
||||
# 定义索引名称和类型名称
|
||||
data_index_name = "wordsearch266666"
|
||||
users_index_name = "users"
|
||||
|
||||
def create_index_with_mapping():
|
||||
"""修正后的索引映射配置"""
|
||||
# 新增一个用户mapping
|
||||
data_mapping = {
|
||||
"mappings": {
|
||||
"properties": {
|
||||
"writer_id":{"type": "text"},
|
||||
|
||||
"data": {
|
||||
"type": "text", # 存储转换后的字符串,支持分词搜索
|
||||
"analyzer": "ik_max_word",
|
||||
"search_analyzer": "ik_smart"
|
||||
},
|
||||
"image": {"type": "keyword"}, # 存储图片路径或标识
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
users_mapping = {
|
||||
"mappings": {
|
||||
"properties": {
|
||||
"user_id":{"type":"long"}, #由系统分配的用户唯一id
|
||||
"username":{"type":"keyword"}, #可修改的用户名
|
||||
"password":{"type":"keyword"}, #密码
|
||||
"premission":{"type":"integer"},#权限组分配(比方说0就是管理员,1是普通用户,以此类推)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# 检查数据索引是否存在,不存在则创建
|
||||
if not es.indices.exists(index=data_index_name):
|
||||
es.indices.create(index=data_index_name, body=data_mapping)
|
||||
print(f"创建索引 {data_index_name} 并设置映射")
|
||||
else:
|
||||
print(f"索引 {data_index_name} 已存在")
|
||||
|
||||
# 检查用户索引是否存在,不存在则创建
|
||||
if not es.indices.exists(index=users_index_name):
|
||||
es.indices.create(index=users_index_name, body=users_mapping)
|
||||
print(f"创建索引 {users_index_name} 并设置映射")
|
||||
admin={"user_id":0000000000,"username": "admin", "password": "admin", "premission": 0}
|
||||
write_user_data(admin)
|
||||
else:
|
||||
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):
|
||||
"""
|
||||
根据数据内容生成唯一ID(用于去重)
|
||||
|
||||
参数:
|
||||
data (dict): 包含文档数据的字典
|
||||
|
||||
返回:
|
||||
str: 基于数据内容生成的MD5哈希值作为唯一ID
|
||||
"""
|
||||
# 使用data字段的内容生成唯一字符串
|
||||
data_str = data.get('data', '')
|
||||
image_str = data.get('image', '')
|
||||
unique_str = f"{data_str}{image_str}"
|
||||
# 使用MD5哈希生成唯一ID
|
||||
return hashlib.md5(unique_str.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def insert_data(data):
|
||||
"""
|
||||
向Elasticsearch插入数据
|
||||
|
||||
参数:
|
||||
data (dict): 要插入的数据
|
||||
|
||||
返回:
|
||||
bool: 插入成功返回True,失败返回False
|
||||
"""
|
||||
# 生成文档唯一ID
|
||||
return batch_write_data(data)
|
||||
|
||||
|
||||
def search_data(query):
|
||||
"""
|
||||
在Elasticsearch中搜索数据
|
||||
|
||||
参数:
|
||||
query (str): 搜索关键词
|
||||
|
||||
返回:
|
||||
list: 包含搜索结果的列表,每个元素是一个文档的源数据
|
||||
"""
|
||||
# 执行多字段匹配搜索
|
||||
result = es.search(index=data_index_name, body={"query": {"multi_match": {"query": query, "fields": ["*"]}}})
|
||||
# 返回搜索结果的源数据部分
|
||||
return [hit["_source"] for hit in result['hits']['hits']]
|
||||
|
||||
def search_all():
|
||||
"""
|
||||
获取所有文档
|
||||
|
||||
返回:
|
||||
list: 包含所有文档的列表,每个元素包含文档ID和源数据
|
||||
"""
|
||||
# 执行匹配所有文档的查询
|
||||
result = es.search(index=data_index_name, body={"query": {"match_all": {}}})
|
||||
# 返回包含文档ID和源数据的列表
|
||||
return [{
|
||||
"_id": hit["_id"],
|
||||
**hit["_source"]
|
||||
} for hit in result['hits']['hits']]
|
||||
|
||||
def delete_by_id(doc_id):
|
||||
"""
|
||||
根据 doc_id 删除文档
|
||||
|
||||
参数:
|
||||
doc_id (str): 要删除的文档ID
|
||||
|
||||
返回:
|
||||
bool: 删除成功返回True,失败返回False
|
||||
"""
|
||||
try:
|
||||
# 执行删除操作
|
||||
es.delete(index=data_index_name, id=doc_id)
|
||||
return True
|
||||
except Exception as e:
|
||||
print("删除失败:", str(e))
|
||||
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):
|
||||
"""全字段模糊搜索(支持拼写错误)"""
|
||||
try:
|
||||
# update_data_mapping()
|
||||
response = requests.post(
|
||||
f"{ES_URL}/{data_index_name}/_search",
|
||||
auth=AUTH,
|
||||
json={
|
||||
"query": {
|
||||
"multi_match": {
|
||||
"query": keyword,
|
||||
"fields": ["*"], # 匹配所有字段
|
||||
"fuzziness": "AUTO", # 启用模糊匹配
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
response.raise_for_status()
|
||||
results = response.json()["hits"]["hits"]
|
||||
print(f"\n模糊搜索 '{keyword}' 找到 {len(results)} 条结果:")
|
||||
|
||||
for doc in results:
|
||||
print(f"\n文档ID: {doc['_id']}")
|
||||
if '_source' in doc:
|
||||
max_key_len = max(len(k) for k in doc['_source'].keys())
|
||||
for key, value in doc['_source'].items():
|
||||
# 提取高亮部分
|
||||
highlight = doc.get('highlight', {}).get(key, [value])[0]
|
||||
print(f"{key:>{max_key_len + 2}} : {highlight}")
|
||||
else:
|
||||
print("无_source数据")
|
||||
|
||||
return results
|
||||
except requests.exceptions.HTTPError as e:
|
||||
print(f"搜索失败: {e.response.text}")
|
||||
return []
|
||||
|
||||
def batch_write_data(data):
|
||||
"""批量写入获奖数据"""
|
||||
try:
|
||||
response = requests.post(
|
||||
f"{ES_URL}/{data_index_name}/_doc",
|
||||
json=data,
|
||||
auth=AUTH,
|
||||
headers={"Content-Type": "application/json"}
|
||||
)
|
||||
response.raise_for_status()
|
||||
doc_id = response.json()["_id"]
|
||||
print(f"文档写入成功,ID: {doc_id}, 内容: {data}")
|
||||
return True
|
||||
except requests.exceptions.HTTPError as e:
|
||||
print(f"文档写入失败: {e.response.text}, 数据: {data}")
|
||||
return False
|
||||
|
||||
def write_user_data(data):
|
||||
"""写入用户数据"""
|
||||
try:
|
||||
response = requests.post(
|
||||
f"{ES_URL}/{users_index_name}/_doc",
|
||||
json=data,
|
||||
auth=AUTH,
|
||||
headers={"Content-Type": "application/json"}
|
||||
)
|
||||
response.raise_for_status()
|
||||
doc_id = response.json()["_id"]
|
||||
print(f"文档写入成功,ID: {doc_id}, 内容: {data}")
|
||||
return True
|
||||
except requests.exceptions.HTTPError as e:
|
||||
print(f"文档写入失败: {e.response.text}, 数据: {data}")
|
||||
return False
|
||||
|
||||
def verify_user(username, password):
|
||||
"""
|
||||
验证用户登录信息
|
||||
|
||||
参数:
|
||||
username (str): 用户名
|
||||
password (str): 密码
|
||||
|
||||
返回:
|
||||
dict or None: 验证成功返回用户信息,失败返回None
|
||||
"""
|
||||
try:
|
||||
# 搜索用户名匹配的用户
|
||||
response = requests.post(
|
||||
f"{ES_URL}/{users_index_name}/_search",
|
||||
auth=AUTH,
|
||||
json={
|
||||
"query": {
|
||||
"term": {
|
||||
"username": username
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
response.raise_for_status()
|
||||
results = response.json()["hits"]["hits"]
|
||||
|
||||
if results:
|
||||
user_data = results[0]["_source"]
|
||||
# 验证密码
|
||||
if user_data.get("password") == password:
|
||||
print(f"用户 {username} 登录成功")
|
||||
return user_data
|
||||
else:
|
||||
print(f"用户 {username} 密码错误")
|
||||
return None
|
||||
else:
|
||||
print(f"用户 {username} 不存在")
|
||||
return None
|
||||
|
||||
except requests.exceptions.HTTPError as e:
|
||||
print(f"用户验证失败: {e.response.text}")
|
||||
return None
|
||||
|
||||
def get_user_by_username(username):
|
||||
"""
|
||||
根据用户名查询用户信息
|
||||
|
||||
参数:
|
||||
username (str): 用户名
|
||||
|
||||
返回:
|
||||
dict or None: 查询成功返回用户信息,失败返回None
|
||||
"""
|
||||
try:
|
||||
response = requests.post(
|
||||
f"{ES_URL}/{users_index_name}/_search",
|
||||
auth=AUTH,
|
||||
json={
|
||||
"query": {
|
||||
"term": {
|
||||
"username": username
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
response.raise_for_status()
|
||||
results = response.json()["hits"]["hits"]
|
||||
|
||||
if results:
|
||||
return results[0]["_source"]
|
||||
else:
|
||||
return None
|
||||
|
||||
except requests.exceptions.HTTPError as e:
|
||||
print(f"用户查询失败: {e.response.text}")
|
||||
return None
|
||||
|
||||
def create_user(username, password, permission=1):
|
||||
"""
|
||||
创建新用户
|
||||
|
||||
参数:
|
||||
username (str): 用户名
|
||||
password (str): 密码
|
||||
permission (int): 权限级别,默认为1(普通用户)
|
||||
|
||||
返回:
|
||||
bool: 创建成功返回True,失败返回False
|
||||
"""
|
||||
# 检查用户名是否已存在
|
||||
if get_user_by_username(username):
|
||||
print(f"用户名 {username} 已存在")
|
||||
return False
|
||||
|
||||
# 生成新的用户ID
|
||||
import time
|
||||
user_id = int(time.time() * 1000) # 使用时间戳作为用户ID
|
||||
|
||||
user_data = {
|
||||
"user_id": user_id,
|
||||
"username": username,
|
||||
"password": password,
|
||||
"premission": permission
|
||||
}
|
||||
|
||||
return write_user_data(user_data)
|
||||
|
||||
def get_all_users():
|
||||
"""
|
||||
获取所有用户信息
|
||||
|
||||
返回:
|
||||
list: 包含所有用户信息的列表
|
||||
"""
|
||||
try:
|
||||
response = requests.post(
|
||||
f"{ES_URL}/{users_index_name}/_search",
|
||||
auth=AUTH,
|
||||
json={
|
||||
"query": {
|
||||
"match_all": {}
|
||||
},
|
||||
"size": 1000 # 限制返回数量,可根据需要调整
|
||||
}
|
||||
)
|
||||
response.raise_for_status()
|
||||
results = response.json()["hits"]["hits"]
|
||||
|
||||
users = []
|
||||
for hit in results:
|
||||
user_data = hit["_source"]
|
||||
user_data["_id"] = hit["_id"] # 添加文档ID用于后续操作
|
||||
users.append(user_data)
|
||||
|
||||
return users
|
||||
|
||||
except requests.exceptions.HTTPError as e:
|
||||
print(f"获取用户列表失败: {e.response.text}")
|
||||
return []
|
||||
|
||||
def update_user_password(username, new_password):
|
||||
"""
|
||||
更新用户密码
|
||||
|
||||
参数:
|
||||
username (str): 用户名
|
||||
new_password (str): 新密码
|
||||
|
||||
返回:
|
||||
bool: 更新成功返回True,失败返回False
|
||||
"""
|
||||
try:
|
||||
# 先查找用户
|
||||
response = requests.post(
|
||||
f"{ES_URL}/{users_index_name}/_search",
|
||||
auth=AUTH,
|
||||
json={
|
||||
"query": {
|
||||
"term": {
|
||||
"username": username
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
response.raise_for_status()
|
||||
results = response.json()["hits"]["hits"]
|
||||
|
||||
if not results:
|
||||
print(f"用户 {username} 不存在")
|
||||
return False
|
||||
|
||||
# 获取用户文档ID
|
||||
doc_id = results[0]["_id"]
|
||||
user_data = results[0]["_source"]
|
||||
|
||||
# 更新密码
|
||||
user_data["password"] = new_password
|
||||
|
||||
# 更新文档
|
||||
update_response = requests.post(
|
||||
f"{ES_URL}/{users_index_name}/_doc/{doc_id}",
|
||||
auth=AUTH,
|
||||
json=user_data,
|
||||
headers={"Content-Type": "application/json"}
|
||||
)
|
||||
update_response.raise_for_status()
|
||||
|
||||
print(f"用户 {username} 密码更新成功")
|
||||
return True
|
||||
|
||||
except requests.exceptions.HTTPError as e:
|
||||
print(f"更新用户密码失败: {e.response.text}")
|
||||
return False
|
||||
|
||||
def delete_user(username):
|
||||
"""
|
||||
删除用户
|
||||
|
||||
参数:
|
||||
username (str): 要删除的用户名
|
||||
|
||||
返回:
|
||||
bool: 删除成功返回True,失败返回False
|
||||
"""
|
||||
try:
|
||||
# 防止删除管理员账户
|
||||
if username == "admin":
|
||||
print("不能删除管理员账户")
|
||||
return False
|
||||
|
||||
# 先查找用户
|
||||
response = requests.post(
|
||||
f"{ES_URL}/{users_index_name}/_search",
|
||||
auth=AUTH,
|
||||
json={
|
||||
"query": {
|
||||
"term": {
|
||||
"username": username
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
response.raise_for_status()
|
||||
results = response.json()["hits"]["hits"]
|
||||
|
||||
if not results:
|
||||
print(f"用户 {username} 不存在")
|
||||
return False
|
||||
|
||||
# 获取用户文档ID
|
||||
doc_id = results[0]["_id"]
|
||||
|
||||
# 删除用户
|
||||
delete_response = requests.delete(
|
||||
f"{ES_URL}/{users_index_name}/_doc/{doc_id}",
|
||||
auth=AUTH
|
||||
)
|
||||
delete_response.raise_for_status()
|
||||
|
||||
print(f"用户 {username} 删除成功")
|
||||
return True
|
||||
|
||||
except requests.exceptions.HTTPError as e:
|
||||
print(f"删除用户失败: {e.response.text}")
|
||||
return False
|
||||
|
||||
def update_user_permission(username, new_permission):
|
||||
"""
|
||||
更新用户权限
|
||||
|
||||
参数:
|
||||
username (str): 用户名
|
||||
new_permission (int): 新权限级别
|
||||
|
||||
返回:
|
||||
bool: 更新成功返回True,失败返回False
|
||||
"""
|
||||
try:
|
||||
# 防止修改管理员权限
|
||||
if username == "admin":
|
||||
print("不能修改管理员权限")
|
||||
return False
|
||||
|
||||
# 先查找用户
|
||||
response = requests.post(
|
||||
f"{ES_URL}/{users_index_name}/_search",
|
||||
auth=AUTH,
|
||||
json={
|
||||
"query": {
|
||||
"term": {
|
||||
"username": username
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
response.raise_for_status()
|
||||
results = response.json()["hits"]["hits"]
|
||||
|
||||
if not results:
|
||||
print(f"用户 {username} 不存在")
|
||||
return False
|
||||
|
||||
# 获取用户文档ID
|
||||
doc_id = results[0]["_id"]
|
||||
user_data = results[0]["_source"]
|
||||
|
||||
# 更新权限
|
||||
user_data["premission"] = new_permission
|
||||
|
||||
# 更新文档
|
||||
update_response = requests.post(
|
||||
f"{ES_URL}/{users_index_name}/_doc/{doc_id}",
|
||||
auth=AUTH,
|
||||
json=user_data,
|
||||
headers={"Content-Type": "application/json"}
|
||||
)
|
||||
update_response.raise_for_status()
|
||||
|
||||
print(f"用户 {username} 权限更新成功")
|
||||
return True
|
||||
|
||||
except requests.exceptions.HTTPError as e:
|
||||
print(f"更新用户权限失败: {e.response.text}")
|
||||
return False
|
||||
|
||||
def search_data_by_user(user_id, keyword=None):
|
||||
"""
|
||||
根据用户ID查询该用户的数据,支持关键词搜索
|
||||
|
||||
参数:
|
||||
user_id (str): 用户ID
|
||||
keyword (str, optional): 搜索关键词
|
||||
|
||||
返回:
|
||||
list: 包含文档ID和源数据的列表
|
||||
"""
|
||||
try:
|
||||
if keyword:
|
||||
# 带关键词的搜索
|
||||
query = {
|
||||
"bool": {
|
||||
"must": [
|
||||
{"term": {"user_id": user_id}},
|
||||
{
|
||||
"multi_match": {
|
||||
"query": keyword,
|
||||
"fields": ["*"],
|
||||
"fuzziness": "AUTO"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
else:
|
||||
# 只按用户ID搜索
|
||||
query = {
|
||||
"term": {"user_id": user_id}
|
||||
}
|
||||
|
||||
response = requests.post(
|
||||
f"{ES_URL}/{data_index_name}/_search",
|
||||
auth=AUTH,
|
||||
json={
|
||||
"query": query,
|
||||
"size": 1000 # 限制返回数量
|
||||
}
|
||||
)
|
||||
response.raise_for_status()
|
||||
results = response.json()["hits"]["hits"]
|
||||
|
||||
# 返回包含文档ID和源数据的列表
|
||||
return [{
|
||||
"_id": hit["_id"],
|
||||
**hit["_source"]
|
||||
} for hit in results]
|
||||
|
||||
except requests.exceptions.HTTPError as e:
|
||||
print(f"查询用户数据失败: {e.response.text}")
|
||||
return []
|
||||
|
||||
def update_data_by_id(doc_id, updated_data, user_id):
|
||||
"""
|
||||
根据文档ID更新数据(仅允许数据所有者修改)
|
||||
|
||||
参数:
|
||||
doc_id (str): 文档ID
|
||||
updated_data (dict): 更新的数据
|
||||
user_id (str): 当前用户ID
|
||||
|
||||
返回:
|
||||
bool: 更新成功返回True,失败返回False
|
||||
"""
|
||||
try:
|
||||
# 先查询文档,验证所有权
|
||||
response = requests.get(
|
||||
f"{ES_URL}/{data_index_name}/_doc/{doc_id}",
|
||||
auth=AUTH
|
||||
)
|
||||
response.raise_for_status()
|
||||
doc = response.json()
|
||||
|
||||
# 检查文档是否存在
|
||||
if not doc.get("found"):
|
||||
print(f"文档 {doc_id} 不存在")
|
||||
return False
|
||||
|
||||
# 检查用户权限(只能修改自己的数据)
|
||||
if doc["_source"].get("user_id") != user_id:
|
||||
print(f"用户 {user_id} 无权修改文档 {doc_id}")
|
||||
return False
|
||||
|
||||
# 保持用户ID不变
|
||||
updated_data["user_id"] = user_id
|
||||
|
||||
# 更新文档
|
||||
update_response = requests.post(
|
||||
f"{ES_URL}/{data_index_name}/_doc/{doc_id}",
|
||||
auth=AUTH,
|
||||
json=updated_data,
|
||||
headers={"Content-Type": "application/json"}
|
||||
)
|
||||
update_response.raise_for_status()
|
||||
|
||||
print(f"文档 {doc_id} 更新成功")
|
||||
return True
|
||||
|
||||
except requests.exceptions.HTTPError as e:
|
||||
print(f"更新文档失败: {e.response.text}")
|
||||
return False
|
||||
|
||||
def delete_data_by_id(doc_id, user_id):
|
||||
"""
|
||||
根据文档ID删除数据(仅允许数据所有者或管理员删除)
|
||||
|
||||
参数:
|
||||
doc_id (str): 文档ID
|
||||
user_id (str): 当前用户ID
|
||||
|
||||
返回:
|
||||
bool: 删除成功返回True,失败返回False
|
||||
"""
|
||||
try:
|
||||
# 先查询文档,验证所有权
|
||||
response = requests.get(
|
||||
f"{ES_URL}/{data_index_name}/_doc/{doc_id}",
|
||||
auth=AUTH
|
||||
)
|
||||
response.raise_for_status()
|
||||
doc = response.json()
|
||||
|
||||
# 检查文档是否存在
|
||||
if not doc.get("found"):
|
||||
print(f"文档 {doc_id} 不存在")
|
||||
return False
|
||||
|
||||
# 检查用户权限(只能删除自己的数据,管理员可以删除所有数据)
|
||||
doc_user_id = doc["_source"].get("user_id")
|
||||
if doc_user_id != user_id:
|
||||
# 检查是否为管理员
|
||||
user_info = get_user_by_username(user_id) # 这里需要用户名,稍后会修改
|
||||
if not user_info or user_info.get("premission") != 0:
|
||||
print(f"用户 {user_id} 无权删除文档 {doc_id}")
|
||||
return False
|
||||
|
||||
# 删除文档
|
||||
delete_response = requests.delete(
|
||||
f"{ES_URL}/{data_index_name}/_doc/{doc_id}",
|
||||
auth=AUTH
|
||||
)
|
||||
delete_response.raise_for_status()
|
||||
|
||||
print(f"文档 {doc_id} 删除成功")
|
||||
return True
|
||||
|
||||
except requests.exceptions.HTTPError as e:
|
||||
print(f"删除文档失败: {e.response.text}")
|
||||
return False
|
||||
|
||||
def update_user_own_password(user_id, old_password, new_password):
|
||||
"""
|
||||
用户修改自己的密码
|
||||
|
||||
参数:
|
||||
user_id (str): 用户ID
|
||||
old_password (str): 旧密码
|
||||
new_password (str): 新密码
|
||||
|
||||
返回:
|
||||
bool: 修改成功返回True,失败返回False
|
||||
"""
|
||||
try:
|
||||
# 先查找用户
|
||||
response = requests.post(
|
||||
f"{ES_URL}/{users_index_name}/_search",
|
||||
auth=AUTH,
|
||||
json={
|
||||
"query": {
|
||||
"term": {
|
||||
"user_id": user_id
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
response.raise_for_status()
|
||||
results = response.json()["hits"]["hits"]
|
||||
|
||||
if not results:
|
||||
print(f"用户 {user_id} 不存在")
|
||||
return False
|
||||
|
||||
user_data = results[0]["_source"]
|
||||
doc_id = results[0]["_id"]
|
||||
|
||||
# 验证旧密码
|
||||
if user_data.get("password") != old_password:
|
||||
print("旧密码错误")
|
||||
return False
|
||||
|
||||
# 更新密码
|
||||
user_data["password"] = new_password
|
||||
|
||||
# 更新文档
|
||||
update_response = requests.post(
|
||||
f"{ES_URL}/{users_index_name}/_doc/{doc_id}",
|
||||
auth=AUTH,
|
||||
json=user_data,
|
||||
headers={"Content-Type": "application/json"}
|
||||
)
|
||||
update_response.raise_for_status()
|
||||
|
||||
print(f"用户 {user_id} 密码修改成功")
|
||||
return True
|
||||
|
||||
except requests.exceptions.HTTPError as e:
|
||||
print(f"修改密码失败: {e.response.text}")
|
||||
return False
|
||||
10
ESTest.py
10
ESTest.py
@@ -1,10 +0,0 @@
|
||||
from elasticsearch import Elasticsearch
|
||||
|
||||
# 连接本地的 Elasticsearch 实例
|
||||
es = Elasticsearch(["http://localhost:9200"])
|
||||
|
||||
# 检查连接是否成功
|
||||
if es.ping():
|
||||
print("连接成功!")
|
||||
else:
|
||||
print("连接失败!")
|
||||
1
accounts/__init__.py
Normal file
1
accounts/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""Accounts app for secure login flow."""
|
||||
6
accounts/apps.py
Normal file
6
accounts/apps.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class AccountsConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'accounts'
|
||||
20
accounts/crypto.py
Normal file
20
accounts/crypto.py
Normal file
@@ -0,0 +1,20 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
|
||||
|
||||
def salt_for_username(username: str) -> bytes:
|
||||
"""Derive a per-username salt using SHA-256(username).
|
||||
|
||||
The salt is deterministic for a given username and does not require storage.
|
||||
"""
|
||||
return hashlib.sha256(username.encode('utf-8')).digest()
|
||||
|
||||
|
||||
def derive_password(password_plain: str, salt: bytes, iterations: int = 100_000, dklen: int = 32) -> bytes:
|
||||
"""PBKDF2-SHA256 derive a fixed-length secret from a plaintext password and salt."""
|
||||
return hashlib.pbkdf2_hmac('sha256', password_plain.encode('utf-8'), salt, iterations, dklen=dklen)
|
||||
|
||||
|
||||
def hmac_sha256(key: bytes, message: bytes) -> bytes:
|
||||
"""Compute HMAC-SHA256 signature for the given message using key bytes."""
|
||||
return hmac.new(key, message, hashlib.sha256).digest()
|
||||
19
accounts/es_client.py
Normal file
19
accounts/es_client.py
Normal file
@@ -0,0 +1,19 @@
|
||||
import base64
|
||||
from elastic.es_connect import get_user_by_username as es_get_user_by_username
|
||||
from .crypto import salt_for_username, derive_password
|
||||
|
||||
def get_user_by_username(username: str):
|
||||
"""
|
||||
期望ES中存储的是明文密码,登录时按用户名盐派生后对nonce做HMAC验证。
|
||||
"""
|
||||
es_user = es_get_user_by_username(username)
|
||||
if es_user:
|
||||
salt = salt_for_username(username)
|
||||
derived = derive_password(es_user.get('password', ''), salt)
|
||||
return {
|
||||
'user_id': es_user.get('user_id', 0),
|
||||
'username': es_user.get('username', ''),
|
||||
'password': base64.b64encode(derived).decode('ascii'),
|
||||
'permission': es_user.get('permission', 1),
|
||||
}
|
||||
return None
|
||||
125
accounts/static/accounts/login.js
Normal file
125
accounts/static/accounts/login.js
Normal file
@@ -0,0 +1,125 @@
|
||||
// Utility: read cookie value
|
||||
function getCookie(name) {
|
||||
const value = `; ${document.cookie}`;
|
||||
const parts = value.split(`; ${name}=`);
|
||||
if (parts.length === 2) return parts.pop().split(';').shift();
|
||||
}
|
||||
|
||||
// Convert base64 string to ArrayBuffer
|
||||
function base64ToArrayBuffer(b64) {
|
||||
const binary = atob(b64);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) {
|
||||
bytes[i] = binary.charCodeAt(i);
|
||||
}
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
// ArrayBuffer to base64
|
||||
function arrayBufferToBase64(buffer) {
|
||||
const bytes = new Uint8Array(buffer);
|
||||
let binary = '';
|
||||
for (let i = 0; i < bytes.byteLength; i++) {
|
||||
binary += String.fromCharCode(bytes[i]);
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
async function deriveKey(password, saltBytes, iterations = 100000, length = 32) {
|
||||
const encoder = new TextEncoder();
|
||||
const keyMaterial = await window.crypto.subtle.importKey(
|
||||
'raw',
|
||||
encoder.encode(password),
|
||||
{ name: 'PBKDF2' },
|
||||
false,
|
||||
['deriveBits']
|
||||
);
|
||||
|
||||
const derivedBits = await window.crypto.subtle.deriveBits(
|
||||
{
|
||||
name: 'PBKDF2',
|
||||
salt: saltBytes,
|
||||
iterations,
|
||||
hash: 'SHA-256'
|
||||
},
|
||||
keyMaterial,
|
||||
length * 8
|
||||
);
|
||||
|
||||
return new Uint8Array(derivedBits);
|
||||
}
|
||||
|
||||
async function hmacSha256(keyBytes, messageBytes) {
|
||||
const key = await window.crypto.subtle.importKey(
|
||||
'raw',
|
||||
keyBytes,
|
||||
{ name: 'HMAC', hash: { name: 'SHA-256' } },
|
||||
false,
|
||||
['sign']
|
||||
);
|
||||
const signature = await window.crypto.subtle.sign('HMAC', key, messageBytes);
|
||||
return new Uint8Array(signature);
|
||||
}
|
||||
|
||||
document.getElementById('loginForm').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const errorEl = document.getElementById('error');
|
||||
errorEl.textContent = '';
|
||||
|
||||
const username = document.getElementById('username').value.trim();
|
||||
const password = document.getElementById('password').value;
|
||||
if (!username || !password) {
|
||||
errorEl.textContent = '请输入账户与密码';
|
||||
return;
|
||||
}
|
||||
|
||||
const btn = document.getElementById('loginBtn');
|
||||
btn.disabled = true;
|
||||
|
||||
try {
|
||||
// Step 1: get challenge (nonce + salt)
|
||||
const csrftoken = getCookie('csrftoken');
|
||||
const chalResp = await fetch('/accounts/challenge/', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRFToken': csrftoken || ''
|
||||
},
|
||||
body: JSON.stringify({ username })
|
||||
});
|
||||
if (!chalResp.ok) {
|
||||
throw new Error('获取挑战失败');
|
||||
}
|
||||
const chal = await chalResp.json();
|
||||
const nonceBytes = new Uint8Array(base64ToArrayBuffer(chal.nonce));
|
||||
const saltBytes = new Uint8Array(base64ToArrayBuffer(chal.salt));
|
||||
|
||||
// Step 2: derive secret and compute HMAC
|
||||
const derived = await deriveKey(password, saltBytes, 100000, 32);
|
||||
const hmac = await hmacSha256(derived, nonceBytes);
|
||||
const hmacB64 = arrayBufferToBase64(hmac);
|
||||
|
||||
// Step 3: submit login with username and hmac
|
||||
const submitResp = await fetch('/accounts/login/submit/', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRFToken': csrftoken || ''
|
||||
},
|
||||
body: JSON.stringify({ username, hmac: hmacB64 })
|
||||
});
|
||||
const submitJson = await submitResp.json();
|
||||
if (!submitResp.ok || !submitJson.ok) {
|
||||
throw new Error(submitJson.message || '登录失败');
|
||||
}
|
||||
// Redirect to home with user_id
|
||||
window.location.href = submitJson.redirect_url;
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
errorEl.textContent = err.message || '发生错误';
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
40
accounts/templates/accounts/login.html
Normal file
40
accounts/templates/accounts/login.html
Normal file
@@ -0,0 +1,40 @@
|
||||
{% load static %}
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>安全登录</title>
|
||||
<link rel="preload" href="{% static 'accounts/login.js' %}" as="script">
|
||||
<style>
|
||||
body { font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif; background: #f5f6fa; }
|
||||
.container { max-width: 360px; margin: 12vh auto; padding: 24px; background: #fff; border-radius: 10px; box-shadow: 0 8px 24px rgba(0,0,0,0.08); }
|
||||
h1 { font-size: 20px; margin: 0 0 16px; }
|
||||
label { display: block; margin: 12px 0 6px; color: #333; }
|
||||
input { width: 100%; padding: 10px 12px; border: 1px solid #dcdde1; border-radius: 6px; }
|
||||
button { width: 100%; margin-top: 16px; padding: 10px 12px; background: #2d8cf0; color: #fff; border: none; border-radius: 6px; cursor: pointer; }
|
||||
button:disabled { background: #9bbcf0; cursor: not-allowed; }
|
||||
.error { color: #d93025; margin-top: 10px; min-height: 20px; }
|
||||
.hint { color: #888; font-size: 12px; margin-top: 10px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1>登录到系统</h1>
|
||||
<form id="loginForm">
|
||||
{% csrf_token %}
|
||||
<label for="username">账户</label>
|
||||
<input id="username" name="username" type="text" autocomplete="username" required />
|
||||
|
||||
<label for="password">密码</label>
|
||||
<input id="password" name="password" type="password" autocomplete="current-password" required />
|
||||
|
||||
<button id="loginBtn" type="submit">登录</button>
|
||||
<div id="error" class="error"></div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script src="{% static 'accounts/login.js' %}"></script>
|
||||
</body>
|
||||
</html>
|
||||
10
accounts/urls.py
Normal file
10
accounts/urls.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from django.urls import path
|
||||
from . import views
|
||||
app_name = "accounts"
|
||||
|
||||
urlpatterns = [
|
||||
path("login/", views.login_page, name="login"),
|
||||
path("challenge/", views.challenge, name="challenge"),
|
||||
path("login/submit/", views.login_submit, name="login_submit"),
|
||||
path("logout/", views.logout, name="logout"),
|
||||
]
|
||||
145
accounts/views.py
Normal file
145
accounts/views.py
Normal file
@@ -0,0 +1,145 @@
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import hmac
|
||||
|
||||
from django.http import JsonResponse, HttpResponseBadRequest
|
||||
from django.shortcuts import render, redirect
|
||||
from django.views.decorators.http import require_http_methods
|
||||
from django.views.decorators.csrf import csrf_protect
|
||||
from django.conf import settings
|
||||
|
||||
from .es_client import get_user_by_username
|
||||
from .crypto import salt_for_username, hmac_sha256
|
||||
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
def login_page(request):
|
||||
return render(request, "accounts/login.html")
|
||||
|
||||
|
||||
@require_http_methods(["POST"])
|
||||
@csrf_protect
|
||||
def challenge(request):
|
||||
try:
|
||||
payload = json.loads(request.body.decode("utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
return HttpResponseBadRequest("Invalid JSON")
|
||||
|
||||
username = payload.get("username", "").strip()
|
||||
if not username:
|
||||
return HttpResponseBadRequest("Username required")
|
||||
|
||||
# Generate nonce and compute per-username salt
|
||||
nonce = os.urandom(16)
|
||||
salt = salt_for_username(username)
|
||||
|
||||
# Persist challenge in session to prevent replay with mismatched user
|
||||
request.session["challenge_nonce"] = base64.b64encode(nonce).decode("ascii")
|
||||
request.session["challenge_username"] = username
|
||||
|
||||
return JsonResponse({
|
||||
"nonce": base64.b64encode(nonce).decode("ascii"),
|
||||
"salt": base64.b64encode(salt).decode("ascii"),
|
||||
})
|
||||
|
||||
|
||||
@require_http_methods(["POST"])
|
||||
@csrf_protect
|
||||
def login_submit(request):
|
||||
try:
|
||||
payload = json.loads(request.body.decode("utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
return HttpResponseBadRequest("Invalid JSON")
|
||||
|
||||
username = payload.get("username", "").strip()
|
||||
client_hmac_b64 = payload.get("hmac", "")
|
||||
if not username or not client_hmac_b64:
|
||||
return HttpResponseBadRequest("Missing fields")
|
||||
|
||||
# Validate challenge stored in session
|
||||
session_username = request.session.get("challenge_username")
|
||||
nonce_b64 = request.session.get("challenge_nonce")
|
||||
if not session_username or not nonce_b64 or session_username != username:
|
||||
return HttpResponseBadRequest("Challenge not found or mismatched user")
|
||||
|
||||
# Lookup user in ES (placeholder)
|
||||
user = get_user_by_username(username)
|
||||
if not user:
|
||||
return JsonResponse({"ok": False, "message": "User not found"}, status=401)
|
||||
|
||||
# Server-side HMAC verification
|
||||
try:
|
||||
nonce = base64.b64decode(nonce_b64)
|
||||
stored_derived_b64 = user.get("password", "")
|
||||
stored_derived = base64.b64decode(stored_derived_b64)
|
||||
server_hmac_b64 = base64.b64encode(hmac_sha256(stored_derived, nonce)).decode("ascii")
|
||||
except Exception:
|
||||
return HttpResponseBadRequest("Verification error")
|
||||
|
||||
if not hmac.compare_digest(server_hmac_b64, client_hmac_b64):
|
||||
return JsonResponse({"ok": False, "message": "Invalid credentials"}, status=401)
|
||||
|
||||
# Successful login: rotate session key and set user session
|
||||
try:
|
||||
request.session.cycle_key()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
request.session["user_id"] = user["user_id"]
|
||||
request.session["username"] = user["username"]
|
||||
request.session["permission"] = user["permission"]
|
||||
|
||||
# Clear challenge to prevent reuse
|
||||
for k in ("challenge_username", "challenge_nonce"):
|
||||
if k in request.session:
|
||||
del request.session[k]
|
||||
|
||||
return JsonResponse({
|
||||
"ok": True,
|
||||
"redirect_url": f"/main/home/?user_id={user['user_id']}",
|
||||
})
|
||||
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
def home(request):
|
||||
# Minimal placeholder page per requirement
|
||||
# Ensure user_id is passed via query and session contains id
|
||||
user_id = request.GET.get("user_id")
|
||||
session_user_id = request.session.get("user_id")
|
||||
context = {
|
||||
"user_id": user_id or session_user_id,
|
||||
}
|
||||
return render(request, "accounts/home.html", context)
|
||||
|
||||
|
||||
@require_http_methods(["POST"])
|
||||
@csrf_protect
|
||||
def logout(request):
|
||||
# Flush the session to clear all data and rotate the key
|
||||
try:
|
||||
request.session.flush()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Return a response that also deletes cookies client-side
|
||||
resp = JsonResponse({"ok": True, "redirect_url": "/accounts/login/"})
|
||||
try:
|
||||
# Delete session cookie
|
||||
resp.delete_cookie(
|
||||
settings.SESSION_COOKIE_NAME,
|
||||
path='/',
|
||||
samesite=settings.SESSION_COOKIE_SAMESITE,
|
||||
secure=settings.SESSION_COOKIE_SECURE,
|
||||
)
|
||||
# Optionally delete CSRF cookie to satisfy "清除cookie" 的要求
|
||||
resp.delete_cookie(
|
||||
settings.CSRF_COOKIE_NAME,
|
||||
path='/',
|
||||
samesite=settings.CSRF_COOKIE_SAMESITE,
|
||||
secure=settings.CSRF_COOKIE_SECURE,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return resp
|
||||
784
app.py
784
app.py
@@ -1,784 +0,0 @@
|
||||
import base64
|
||||
from flask import Flask, request, render_template, redirect, url_for, jsonify, session, flash, send_from_directory
|
||||
from werkzeug.utils import secure_filename
|
||||
import os
|
||||
import uuid
|
||||
from PIL import Image
|
||||
import re
|
||||
import json
|
||||
import requests
|
||||
from functools import wraps
|
||||
from ESConnect import *
|
||||
from json_converter import json_to_string, string_to_json
|
||||
from openai import OpenAI
|
||||
# import config
|
||||
|
||||
# 创建Flask应用实例
|
||||
app = Flask(__name__)
|
||||
# app.config.from_object(config.Config)
|
||||
|
||||
# 设置会话密钥,用于加密会话数据
|
||||
app.secret_key = 'your-secret-key-change-this-in-production'
|
||||
# OCR和信息提取函数,使用大模型API处理图片并提取结构化信息
|
||||
# 权限装饰器
|
||||
def login_required(f):
|
||||
"""要求用户登录的装饰器"""
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if 'user_id' not in session:
|
||||
flash('请先登录', 'error')
|
||||
return redirect(url_for('login'))
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
def admin_required(f):
|
||||
"""要求管理员权限的装饰器"""
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if 'user_id' not in session:
|
||||
flash('请先登录', 'error')
|
||||
return redirect(url_for('login'))
|
||||
if session.get('permission', 1) != 0:
|
||||
flash('权限不足,需要管理员权限', 'error')
|
||||
return redirect(url_for('index'))
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
def user_or_admin_required(f):
|
||||
"""要求普通用户或管理员权限的装饰器"""
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if 'user_id' not in session:
|
||||
flash('请先登录', 'error')
|
||||
return redirect(url_for('login'))
|
||||
permission = session.get('permission', 1)
|
||||
if permission not in [0, 1]:
|
||||
flash('权限不足', 'error')
|
||||
return redirect(url_for('index'))
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
|
||||
def ocr_and_extract_info(image_path):
|
||||
"""
|
||||
使用大模型API进行OCR识别并提取图片中的结构化信息
|
||||
|
||||
参数:
|
||||
image_path (str): 图片文件路径
|
||||
|
||||
返回:
|
||||
dict: 包含提取信息的字典,格式为 {'id': '', 'name': '', 'students': '', 'teacher': ''}
|
||||
"""
|
||||
def encode_image(image_path):
|
||||
"""
|
||||
将图片编码为base64格式
|
||||
|
||||
参数:
|
||||
image_path (str): 图片文件路径
|
||||
|
||||
返回:
|
||||
str: base64编码的图片字符串
|
||||
"""
|
||||
with open(image_path, "rb") as image_file:
|
||||
return base64.b64encode(image_file.read()).decode('utf-8')
|
||||
|
||||
# 将图片转换为base64编码
|
||||
base64_image = encode_image(image_path)
|
||||
|
||||
# 初始化OpenAI客户端,使用百度AI Studio的API
|
||||
client = OpenAI(
|
||||
api_key="188f57db3766e02ed2c7e18373996d84f4112272",
|
||||
# 含有 AI Studio 访问令牌的环境变量,https://aistudio.baidu.com/account/accessToken,
|
||||
base_url="https://aistudio.baidu.com/llm/lmapi/v3", # aistudio 大模型 api 服务域名
|
||||
)
|
||||
|
||||
# 调用大模型API进行图片识别和信息提取
|
||||
chat_completion = client.chat.completions.create(
|
||||
messages=[
|
||||
{'role': 'system', 'content': '你是一个能理解图片和文本的助手,请根据用户提供的信息进行回答。'},
|
||||
{'role': 'user', "content": [
|
||||
{"type": "text", "text": "请识别这张图片中的信息,将你认为重要的数据转换为不包含嵌套的json,不要显示其它信息以便于解析"
|
||||
"直接输出json结果即可"
|
||||
"你可以自行决定使用哪些json字段"},
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {
|
||||
"url": f"data:image/png;base64,{base64_image}"
|
||||
}
|
||||
}
|
||||
]}
|
||||
],
|
||||
model="ernie-4.5-turbo-vl-32k", # 使用百度文心大模型
|
||||
)
|
||||
|
||||
# 获取API返回的文本内容
|
||||
response_text = chat_completion.choices[0].message.content
|
||||
|
||||
# 添加调试信息:输出模型返回的原始字符串
|
||||
print("=" * 50)
|
||||
print("模型返回的原始字符串:")
|
||||
print(response_text)
|
||||
print("=" * 50)
|
||||
|
||||
def parse_respound(text):
|
||||
"""
|
||||
解析API返回的文本,提取JSON数据
|
||||
|
||||
参数:
|
||||
text (str): API返回的文本
|
||||
|
||||
返回:
|
||||
dict or None: 解析成功返回字典,失败返回None
|
||||
"""
|
||||
# 尝试直接解析标准JSON
|
||||
try:
|
||||
result=json.loads(text)
|
||||
if result:
|
||||
print("✓ 成功解析标准JSON格式")
|
||||
return result
|
||||
except json.JSONDecodeError:
|
||||
print("✗ 无法解析标准JSON格式")
|
||||
pass
|
||||
|
||||
# 提取markdown代码块中的内容
|
||||
code_block = re.search(r'```json\n(.*?)```', text, re.DOTALL)
|
||||
if code_block:
|
||||
try:
|
||||
result=json.loads(code_block.group(1))
|
||||
if result:
|
||||
print("✓ 成功解析markdown代码块中的JSON")
|
||||
return result
|
||||
except json.JSONDecodeError:
|
||||
print("✗ 无法解析markdown代码块中的JSON")
|
||||
pass
|
||||
|
||||
# 尝试替换单引号并解析
|
||||
try:
|
||||
fixed_json = text.replace("'", "\"")
|
||||
result=json.loads(fixed_json)
|
||||
if(result):
|
||||
print("✓ 成功解析替换单引号后的JSON")
|
||||
return result
|
||||
except json.JSONDecodeError:
|
||||
print("✗ 无法解析替换单引号后的JSON")
|
||||
pass
|
||||
|
||||
# 解析API返回的文本
|
||||
result_data = parse_respound(response_text)
|
||||
|
||||
# 添加调试信息:输出解析结果
|
||||
print("解析结果:")
|
||||
if result_data:
|
||||
print(f"✓ 解析成功: {result_data}")
|
||||
else:
|
||||
print("✗ 解析失败,返回None")
|
||||
print("=" * 50)
|
||||
|
||||
return result_data
|
||||
|
||||
"""
|
||||
模拟大模型识别图像并返回结构化JSON。
|
||||
实际应调用Qwen-VL或其他OCR+解析服务。
|
||||
"""
|
||||
|
||||
|
||||
# 登录页面路由
|
||||
@app.route('/login', methods=['GET', 'POST'])
|
||||
def login():
|
||||
"""
|
||||
处理用户登录
|
||||
|
||||
GET: 显示登录页面
|
||||
POST: 处理登录表单提交
|
||||
"""
|
||||
if request.method == 'POST':
|
||||
username = request.form.get('username')
|
||||
password = request.form.get('password')
|
||||
|
||||
if not username or not password:
|
||||
flash('请输入用户名和密码', 'error')
|
||||
return render_template('login.html')
|
||||
|
||||
# 验证用户
|
||||
user_data = verify_user(username, password)
|
||||
if user_data:
|
||||
# 登录成功,设置会话
|
||||
session['user_id'] = user_data['user_id']
|
||||
session['username'] = user_data['username']
|
||||
session['permission'] = user_data['premission']
|
||||
flash(f'欢迎回来,{username}!', 'success')
|
||||
return redirect(url_for('index'))
|
||||
else:
|
||||
flash('用户名或密码错误', 'error')
|
||||
return render_template('login.html')
|
||||
|
||||
return render_template('login.html')
|
||||
|
||||
|
||||
# 登出路由
|
||||
@app.route('/logout')
|
||||
def logout():
|
||||
"""
|
||||
处理用户登出
|
||||
"""
|
||||
session.clear()
|
||||
flash('已成功登出', 'info')
|
||||
return redirect(url_for('login'))
|
||||
|
||||
|
||||
# 用户管理页面路由
|
||||
@app.route('/user_management')
|
||||
@admin_required
|
||||
def user_management():
|
||||
"""
|
||||
显示用户管理页面(仅管理员可访问)
|
||||
"""
|
||||
users = get_all_users()
|
||||
return render_template('user_management.html', users=users)
|
||||
|
||||
|
||||
# 注册新用户路由
|
||||
@app.route('/register', methods=['GET', 'POST'])
|
||||
@admin_required
|
||||
def register():
|
||||
"""
|
||||
注册新用户(仅管理员可访问)
|
||||
|
||||
GET: 显示注册页面
|
||||
POST: 处理注册表单提交
|
||||
"""
|
||||
if request.method == 'POST':
|
||||
username = request.form.get('username')
|
||||
password = request.form.get('password')
|
||||
confirm_password = request.form.get('confirm_password')
|
||||
permission = int(request.form.get('permission', 1))
|
||||
|
||||
# 验证输入
|
||||
if not username or not password:
|
||||
flash('请输入用户名和密码', 'error')
|
||||
return render_template('register.html')
|
||||
|
||||
if password != confirm_password:
|
||||
flash('两次输入的密码不一致', 'error')
|
||||
return render_template('register.html')
|
||||
|
||||
if len(password) < 6:
|
||||
flash('密码长度至少6位', 'error')
|
||||
return render_template('register.html')
|
||||
|
||||
# 检查用户名是否已存在
|
||||
existing_user = get_user_by_username(username)
|
||||
if existing_user:
|
||||
flash('用户名已存在', 'error')
|
||||
return render_template('register.html')
|
||||
|
||||
# 创建新用户
|
||||
success = create_user(username, password, permission)
|
||||
if success:
|
||||
flash(f'用户 {username} 创建成功', 'success')
|
||||
return redirect(url_for('user_management'))
|
||||
else:
|
||||
flash('创建用户失败', 'error')
|
||||
return render_template('register.html')
|
||||
|
||||
return render_template('register.html')
|
||||
|
||||
|
||||
# 修改用户密码路由
|
||||
@app.route('/change_password/<username>', methods=['POST'])
|
||||
@admin_required
|
||||
def change_password(username):
|
||||
"""
|
||||
修改用户密码(仅管理员可访问)
|
||||
"""
|
||||
new_password = request.form.get('new_password')
|
||||
confirm_password = request.form.get('confirm_password')
|
||||
|
||||
if not new_password or not confirm_password:
|
||||
flash('请输入新密码', 'error')
|
||||
return redirect(url_for('user_management'))
|
||||
|
||||
if new_password != confirm_password:
|
||||
flash('两次输入的密码不一致', 'error')
|
||||
return redirect(url_for('user_management'))
|
||||
|
||||
if len(new_password) < 6:
|
||||
flash('密码长度至少6位', 'error')
|
||||
return redirect(url_for('user_management'))
|
||||
|
||||
success = update_user_password(username, new_password)
|
||||
if success:
|
||||
flash(f'用户 {username} 密码修改成功', 'success')
|
||||
else:
|
||||
flash(f'修改用户 {username} 密码失败', 'error')
|
||||
|
||||
return redirect(url_for('user_management'))
|
||||
|
||||
|
||||
# 修改用户权限路由
|
||||
@app.route('/change_permission/<username>', methods=['POST'])
|
||||
@admin_required
|
||||
def change_permission(username):
|
||||
"""
|
||||
修改用户权限(仅管理员可访问)
|
||||
"""
|
||||
new_permission = int(request.form.get('permission', 1))
|
||||
|
||||
success = update_user_permission(username, new_permission)
|
||||
if success:
|
||||
flash(f'用户 {username} 权限修改成功', 'success')
|
||||
else:
|
||||
flash(f'修改用户 {username} 权限失败', 'error')
|
||||
|
||||
return redirect(url_for('user_management'))
|
||||
|
||||
|
||||
# 删除用户路由
|
||||
@app.route('/delete_user/<username>', methods=['POST'])
|
||||
@admin_required
|
||||
def delete_user_route(username):
|
||||
"""
|
||||
删除用户(仅管理员可访问)
|
||||
"""
|
||||
success = delete_user(username)
|
||||
if success:
|
||||
flash(f'用户 {username} 删除成功', 'success')
|
||||
else:
|
||||
flash(f'删除用户 {username} 失败', 'error')
|
||||
|
||||
return redirect(url_for('user_management'))
|
||||
|
||||
|
||||
# 个人设置页面路由
|
||||
@app.route('/profile')
|
||||
@login_required
|
||||
def profile():
|
||||
"""
|
||||
显示个人设置页面
|
||||
"""
|
||||
return render_template('profile.html')
|
||||
|
||||
|
||||
# 修改个人密码路由
|
||||
@app.route('/change_own_password', methods=['POST'])
|
||||
@login_required
|
||||
def change_own_password():
|
||||
"""
|
||||
用户修改自己的密码
|
||||
"""
|
||||
old_password = request.form.get('old_password')
|
||||
new_password = request.form.get('new_password')
|
||||
confirm_password = request.form.get('confirm_password')
|
||||
|
||||
# 验证输入
|
||||
if not old_password or not new_password or not confirm_password:
|
||||
flash('请填写所有密码字段', 'error')
|
||||
return redirect(url_for('profile'))
|
||||
|
||||
if new_password != confirm_password:
|
||||
flash('两次输入的新密码不一致', 'error')
|
||||
return redirect(url_for('profile'))
|
||||
|
||||
if len(new_password) < 6:
|
||||
flash('新密码长度至少6位', 'error')
|
||||
return redirect(url_for('profile'))
|
||||
|
||||
# 调用修改密码函数
|
||||
success = update_user_own_password(session['user_id'], old_password, new_password)
|
||||
if success:
|
||||
flash('密码修改成功', 'success')
|
||||
else:
|
||||
flash('密码修改失败,请检查旧密码是否正确', 'error')
|
||||
|
||||
return redirect(url_for('profile'))
|
||||
|
||||
|
||||
# 个人数据页面路由
|
||||
@app.route('/my_data')
|
||||
@login_required
|
||||
def my_data():
|
||||
"""
|
||||
显示用户自己的数据
|
||||
"""
|
||||
user_id = session['user_id']
|
||||
keyword = request.args.get('keyword', '')
|
||||
|
||||
# 查询用户自己的数据
|
||||
if keyword:
|
||||
data = search_data_by_user(user_id, keyword)
|
||||
else:
|
||||
data = search_data_by_user(user_id)
|
||||
|
||||
# 将data字段从字符串转换回JSON格式以便显示
|
||||
processed_data = []
|
||||
for item in data:
|
||||
if 'data' in item and item['data']:
|
||||
try:
|
||||
# 将data字段的字符串转换回JSON
|
||||
original_data = string_to_json(item['data'])
|
||||
# 合并原始数据和其他字段
|
||||
display_item = {
|
||||
'_id': item['_id'],
|
||||
'image': item.get('image', ''),
|
||||
**original_data # 展开原始数据字段
|
||||
}
|
||||
processed_data.append(display_item)
|
||||
except Exception as e:
|
||||
# 如果转换失败,保持原始格式
|
||||
processed_data.append(item)
|
||||
else:
|
||||
processed_data.append(item)
|
||||
|
||||
return render_template('my_data.html', data=processed_data, keyword=keyword)
|
||||
|
||||
# 首页路由
|
||||
@app.route('/')
|
||||
@login_required
|
||||
def index():
|
||||
"""
|
||||
渲染首页模板
|
||||
|
||||
返回:
|
||||
str: 渲染后的HTML页面
|
||||
"""
|
||||
return render_template('index.html')
|
||||
|
||||
# 图片上传路由
|
||||
@app.route('/upload', methods=['POST'])
|
||||
@user_or_admin_required
|
||||
def upload_image():
|
||||
"""
|
||||
处理图片上传请求,调用OCR识别但不存储结果
|
||||
|
||||
返回:
|
||||
JSON: 识别结果,供用户编辑确认
|
||||
"""
|
||||
# 获取上传的文件
|
||||
file = request.files.get('file')
|
||||
if not file:
|
||||
return jsonify({"error": "No file uploaded"}), 400
|
||||
|
||||
# 保存上传的图片
|
||||
filename = f"{uuid.uuid4()}_{file.filename}"
|
||||
image_path = os.path.join("image", filename)
|
||||
file.save(image_path)
|
||||
|
||||
# 调用大模型进行识别
|
||||
try:
|
||||
print(f"开始处理图片: {image_path}")
|
||||
original_data = ocr_and_extract_info(image_path) # 获取原始JSON数据
|
||||
if original_data:
|
||||
print(f"识别成功: {original_data}")
|
||||
# 返回识别结果和图片文件名,供用户编辑确认
|
||||
return jsonify({
|
||||
"message": "识别成功,请确认数据后点击录入",
|
||||
"data": original_data,
|
||||
"image": filename
|
||||
})
|
||||
else:
|
||||
print("✗ 无法识别图片内容")
|
||||
return jsonify({"error": "无法识别图片内容"}), 400
|
||||
except Exception as e:
|
||||
print(f"✗ 处理过程中发生错误: {str(e)}")
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
# 确认录入路由
|
||||
@app.route('/confirm', methods=['POST'])
|
||||
@user_or_admin_required
|
||||
def confirm_data():
|
||||
"""
|
||||
确认并录入用户编辑后的数据
|
||||
|
||||
返回:
|
||||
JSON: 录入成功或失败的响应
|
||||
"""
|
||||
try:
|
||||
# 获取前端提交的数据
|
||||
request_data = request.get_json()
|
||||
if not request_data:
|
||||
return jsonify({"error": "没有接收到数据"}), 400
|
||||
|
||||
# 获取编辑后的数据和图片文件名
|
||||
edited_data = request_data.get('data', {})
|
||||
image_filename = request_data.get('image', '')
|
||||
|
||||
if not edited_data:
|
||||
return jsonify({"error": "数据不能为空"}), 400
|
||||
|
||||
# 使用json_converter将JSON数据转换为字符串
|
||||
data_string = json_to_string(edited_data)
|
||||
print(f"转换后的数据字符串: {data_string}")
|
||||
|
||||
# 构造新的数据结构,只包含data和image字段,并添加用户ID
|
||||
processed_data = {
|
||||
"data": data_string,
|
||||
"image": image_filename, # 存储图片文件名
|
||||
"user_id": session['user_id'] # 添加用户ID关联
|
||||
}
|
||||
print(f"准备存储的数据: {processed_data}")
|
||||
|
||||
# 存入ES
|
||||
insert_data(processed_data)
|
||||
print("✓ 数据成功存储到Elasticsearch")
|
||||
|
||||
return jsonify({"message": "数据录入成功", "data": edited_data})
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ 录入过程中发生错误: {str(e)}")
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
# 搜索路由
|
||||
@app.route('/search')
|
||||
@user_or_admin_required
|
||||
def search():
|
||||
"""
|
||||
处理搜索请求,从Elasticsearch中检索匹配的数据
|
||||
|
||||
返回:
|
||||
JSON: 搜索结果列表
|
||||
"""
|
||||
keyword = request.args.get('q')
|
||||
if not keyword:
|
||||
return jsonify([])
|
||||
results = search_by_any_field(keyword)
|
||||
|
||||
# 处理搜索结果,将data字段转换回JSON格式
|
||||
processed_results = []
|
||||
for result in results:
|
||||
if '_source' in result and 'data' in result['_source']:
|
||||
try:
|
||||
# 将data字段的字符串转换回JSON
|
||||
original_data = string_to_json(result['_source']['data'])
|
||||
# 构造新的结果格式
|
||||
processed_result = {
|
||||
'_id': result.get('_id', ''),
|
||||
'_source': {
|
||||
'image': result['_source'].get('image', ''),
|
||||
**original_data # 展开原始数据字段
|
||||
}
|
||||
}
|
||||
processed_results.append(processed_result)
|
||||
except Exception as e:
|
||||
# 如果转换失败,保持原始格式
|
||||
processed_results.append(result)
|
||||
else:
|
||||
processed_results.append(result)
|
||||
|
||||
print(processed_results)
|
||||
return jsonify(processed_results)
|
||||
|
||||
# 结果页面路由
|
||||
@app.route('/results')
|
||||
@user_or_admin_required
|
||||
def results_page():
|
||||
"""
|
||||
渲染搜索结果页面
|
||||
|
||||
返回:
|
||||
str: 渲染后的HTML页面
|
||||
"""
|
||||
return render_template('results.html')
|
||||
|
||||
# 显示所有数据路由
|
||||
@app.route('/all')
|
||||
@admin_required
|
||||
def show_all():
|
||||
"""
|
||||
获取所有数据并渲染到页面
|
||||
|
||||
返回:
|
||||
str: 渲染后的HTML页面,包含所有数据
|
||||
"""
|
||||
all_data = search_all()
|
||||
# 将data字段从字符串转换回JSON格式以便显示
|
||||
processed_data = []
|
||||
for item in all_data:
|
||||
if 'data' in item and item['data']:
|
||||
try:
|
||||
# 将data字段的字符串转换回JSON
|
||||
original_data = string_to_json(item['data'])
|
||||
# 合并原始数据和其他字段
|
||||
display_item = {
|
||||
'_id': item['_id'],
|
||||
'image': item.get('image', ''),
|
||||
**original_data # 展开原始数据字段
|
||||
}
|
||||
processed_data.append(display_item)
|
||||
except Exception as e:
|
||||
# 如果转换失败,保持原始格式
|
||||
processed_data.append(item)
|
||||
else:
|
||||
processed_data.append(item)
|
||||
|
||||
return render_template('all.html', data=processed_data)
|
||||
|
||||
# 添加图片路由
|
||||
@app.route('/image/<filename>')
|
||||
def serve_image(filename):
|
||||
"""
|
||||
提供图片文件服务
|
||||
|
||||
参数:
|
||||
filename (str): 图片文件名
|
||||
|
||||
返回:
|
||||
Response: 图片文件响应
|
||||
"""
|
||||
from flask import send_from_directory
|
||||
return send_from_directory('image', filename)
|
||||
|
||||
# 删除数据路由
|
||||
@app.route('/delete/<doc_id>', methods=['POST'])
|
||||
@login_required
|
||||
def delete_entry(doc_id):
|
||||
"""
|
||||
根据文档ID删除数据
|
||||
|
||||
参数:
|
||||
doc_id (str): 要删除的文档ID
|
||||
|
||||
返回:
|
||||
重定向到所有数据页面或错误信息
|
||||
"""
|
||||
user_id = session['user_id']
|
||||
user_permission = session.get('permission', 1)
|
||||
|
||||
# 管理员可以删除所有数据,普通用户只能删除自己的数据
|
||||
if user_permission == 0: # 管理员
|
||||
success = delete_by_id(doc_id)
|
||||
redirect_url = 'show_all'
|
||||
else: # 普通用户
|
||||
success = delete_data_by_id(doc_id, user_id)
|
||||
redirect_url = 'my_data'
|
||||
|
||||
if success:
|
||||
return redirect(url_for(redirect_url))
|
||||
else:
|
||||
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'])
|
||||
@login_required
|
||||
def edit_entry(doc_id):
|
||||
"""
|
||||
编辑数据条目(用户只能编辑自己的数据)
|
||||
"""
|
||||
if request.method == 'GET':
|
||||
# 获取要编辑的数据
|
||||
try:
|
||||
# 先获取文档检查权限
|
||||
response = requests.get(
|
||||
f"{ES_URL}/{data_index_name}/_doc/{doc_id}",
|
||||
auth=AUTH
|
||||
)
|
||||
response.raise_for_status()
|
||||
doc = response.json()
|
||||
|
||||
if not doc.get("found"):
|
||||
flash('数据不存在', 'error')
|
||||
return redirect(url_for('my_data'))
|
||||
|
||||
# 检查权限
|
||||
user_id = session['user_id']
|
||||
user_permission = session.get('permission', 1)
|
||||
doc_user_id = doc["_source"].get("user_id")
|
||||
|
||||
# 管理员可以编辑所有数据,普通用户只能编辑自己的数据
|
||||
if user_permission != 0 and doc_user_id != user_id:
|
||||
flash('您无权编辑此数据', 'error')
|
||||
return redirect(url_for('my_data'))
|
||||
|
||||
# 解析数据
|
||||
data_str = doc["_source"].get("data", "{}")
|
||||
original_data = string_to_json(data_str)
|
||||
|
||||
edit_data = {
|
||||
'_id': doc_id,
|
||||
'image': doc["_source"].get('image', ''),
|
||||
**original_data
|
||||
}
|
||||
|
||||
return render_template('edit.html', data=edit_data)
|
||||
|
||||
except Exception as e:
|
||||
flash('获取数据失败', 'error')
|
||||
return redirect(url_for('my_data'))
|
||||
|
||||
else: # POST 请求 - 保存编辑
|
||||
try:
|
||||
# 获取编辑后的数据
|
||||
edited_data = {}
|
||||
for key, value in request.form.items():
|
||||
if key != '_id' and key != 'image':
|
||||
edited_data[key] = value
|
||||
|
||||
# 转换为字符串格式
|
||||
data_string = json_to_string(edited_data)
|
||||
|
||||
# 构造更新数据
|
||||
updated_data = {
|
||||
"data": data_string,
|
||||
"image": request.form.get('image', ''),
|
||||
"user_id": session['user_id']
|
||||
}
|
||||
|
||||
# 更新数据
|
||||
success = update_data_by_id(doc_id, updated_data, session['user_id'])
|
||||
|
||||
if success:
|
||||
flash('数据更新成功', 'success')
|
||||
else:
|
||||
flash('数据更新失败', 'error')
|
||||
|
||||
# 根据用户权限重定向
|
||||
if session.get('permission', 1) == 0:
|
||||
return redirect(url_for('show_all'))
|
||||
else:
|
||||
return redirect(url_for('my_data'))
|
||||
|
||||
except Exception as e:
|
||||
flash('保存数据失败', 'error')
|
||||
return redirect(url_for('my_data'))
|
||||
|
||||
# 主程序入口
|
||||
if __name__ == '__main__':
|
||||
# 创建Elasticsearch索引
|
||||
create_index_with_mapping()
|
||||
# 创建图片存储目录
|
||||
os.makedirs("image", exist_ok=True)
|
||||
# 启动Flask应用
|
||||
app.run(use_reloader=False)
|
||||
BIN
db.sqlite3
Normal file
BIN
db.sqlite3
Normal file
Binary file not shown.
0
elastic/__init__.py
Normal file
0
elastic/__init__.py
Normal file
3
elastic/admin.py
Normal file
3
elastic/admin.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
||||
24
elastic/apps.py
Normal file
24
elastic/apps.py
Normal file
@@ -0,0 +1,24 @@
|
||||
from django.apps import AppConfig
|
||||
import os
|
||||
import sys
|
||||
|
||||
class ElasticConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "elastic"
|
||||
|
||||
def ready(self):
|
||||
# 避免在 migrate、collectstatic 等管理命令中执行
|
||||
if os.environ.get('RUN_MAIN') != 'true':
|
||||
# Django 开发服务器会启动两个进程,只在主进程执行
|
||||
return
|
||||
|
||||
# 避免在 manage.py 命令(除 runserver 外)中执行
|
||||
if 'runserver' not in sys.argv:
|
||||
return
|
||||
|
||||
# 延迟导入,避免循环导入或过早加载
|
||||
from .es_connect import create_index_with_mapping
|
||||
try:
|
||||
create_index_with_mapping()
|
||||
except Exception as e:
|
||||
print(f"❌ ES 初始化失败: {e}")
|
||||
39
elastic/documents.py
Normal file
39
elastic/documents.py
Normal file
@@ -0,0 +1,39 @@
|
||||
from django_elasticsearch_dsl import Document, fields, Index
|
||||
from .models import AchievementData, User, ElasticNews
|
||||
from .indexes import *
|
||||
|
||||
ACHIEVEMENT_INDEX = Index(ACHIEVEMENT_INDEX_NAME)
|
||||
ACHIEVEMENT_INDEX.settings(number_of_shards=1, number_of_replicas=0)
|
||||
USER_INDEX = Index(USER_INDEX_NAME)
|
||||
USER_INDEX.settings(number_of_shards=1, number_of_replicas=0)
|
||||
|
||||
|
||||
|
||||
@ACHIEVEMENT_INDEX.doc_type
|
||||
class AchievementDocument(Document):
|
||||
"""获奖数据文档映射"""
|
||||
writer_id = fields.TextField(fields={'keyword': {'type': 'keyword'}})
|
||||
data = fields.TextField(
|
||||
analyzer='ik_max_word',
|
||||
search_analyzer='ik_smart',
|
||||
fields={'keyword': {'type': 'keyword'}}
|
||||
)
|
||||
image = fields.KeywordField()
|
||||
|
||||
class Django:
|
||||
model = AchievementData
|
||||
# fields列表应该只包含需要特殊处理的字段,或者可以完全省略
|
||||
# 因为我们已经显式定义了所有字段
|
||||
|
||||
@USER_INDEX.doc_type
|
||||
class UserDocument(Document):
|
||||
"""用户数据文档映射"""
|
||||
user_id = fields.LongField()
|
||||
username = fields.KeywordField()
|
||||
password = fields.KeywordField()
|
||||
permission = fields.IntegerField()
|
||||
|
||||
class Django:
|
||||
model = User
|
||||
# fields列表应该只包含需要特殊处理的字段,或者可以完全省略
|
||||
# 因为我们已经显式定义了所有字段
|
||||
379
elastic/es_connect.py
Normal file
379
elastic/es_connect.py
Normal file
@@ -0,0 +1,379 @@
|
||||
"""
|
||||
Django版本的ES连接和操作模块
|
||||
迁移自Flask项目的ESConnect.py
|
||||
"""
|
||||
from elasticsearch import Elasticsearch
|
||||
from elasticsearch_dsl import connections
|
||||
from .documents import AchievementDocument, UserDocument
|
||||
from .indexes import ACHIEVEMENT_INDEX_NAME, USER_INDEX_NAME
|
||||
import hashlib
|
||||
import time
|
||||
|
||||
# 使用Django的ES连接配置
|
||||
connections.create_connection(hosts=['localhost:9200'])
|
||||
|
||||
# 获取默认的ES客户端
|
||||
es = connections.get_connection()
|
||||
|
||||
DATA_INDEX_NAME = ACHIEVEMENT_INDEX_NAME
|
||||
USERS_INDEX_NAME = USER_INDEX_NAME
|
||||
|
||||
def create_index_with_mapping():
|
||||
"""创建索引和映射配置(仅当索引不存在时)"""
|
||||
# 获取 Elasticsearch 客户端(与 Document 使用的客户端一致)
|
||||
try:
|
||||
# --- 1. 处理获奖数据索引 ---
|
||||
if not es.indices.exists(index=DATA_INDEX_NAME):
|
||||
AchievementDocument.init()
|
||||
print(f"✅ 创建索引 {DATA_INDEX_NAME} 并设置映射")
|
||||
else:
|
||||
print(f"ℹ️ 索引 {DATA_INDEX_NAME} 已存在,跳过创建")
|
||||
|
||||
# --- 2. 处理用户索引 ---
|
||||
if not es.indices.exists(index=USERS_INDEX_NAME):
|
||||
UserDocument.init()
|
||||
print(f"✅ 创建索引 {USERS_INDEX_NAME} 并设置映射")
|
||||
else:
|
||||
print(f"ℹ️ 索引 {USERS_INDEX_NAME} 已存在,跳过创建")
|
||||
|
||||
# --- 3. 创建默认管理员用户(可选:也可检查用户是否已存在)---
|
||||
# 这里简单处理:每次初始化都写入(可能重复),建议加唯一性判断
|
||||
admin_user = {
|
||||
"user_id": 0,
|
||||
"username": "admin",
|
||||
"password": "admin", # ⚠️ 生产环境务必加密!
|
||||
"permission": 0
|
||||
}
|
||||
# 可选:检查 admin 是否已存在(根据 user_id 或 username)
|
||||
from elasticsearch_dsl import Search
|
||||
s = Search(using=es, index=USERS_INDEX_NAME).query("match", username="admin")
|
||||
if s.count() == 0:
|
||||
write_user_data(admin_user)
|
||||
print("✅ 默认管理员用户已创建")
|
||||
else:
|
||||
print("ℹ️ 默认管理员用户已存在,跳过创建")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 创建索引失败: {str(e)}")
|
||||
# raise # 可选:在 AppConfig 中捕获,这里可以 re-raise 便于调试
|
||||
|
||||
def get_doc_id(data):
|
||||
"""
|
||||
根据数据内容生成唯一ID(用于去重)
|
||||
|
||||
参数:
|
||||
data (dict): 包含文档数据的字典
|
||||
|
||||
返回:
|
||||
str: 基于数据内容生成的MD5哈希值作为唯一ID
|
||||
"""
|
||||
data_str = data.get('data', '')
|
||||
image_str = data.get('image', '')
|
||||
unique_str = f"{data_str}{image_str}"
|
||||
return hashlib.md5(unique_str.encode('utf-8')).hexdigest()
|
||||
|
||||
def insert_data(data):
|
||||
"""
|
||||
向Elasticsearch插入数据
|
||||
|
||||
参数:
|
||||
data (dict): 要插入的数据
|
||||
|
||||
返回:
|
||||
bool: 插入成功返回True,失败返回False
|
||||
"""
|
||||
try:
|
||||
# 使用Django-elasticsearch-dsl的方式插入数据
|
||||
achievement = AchievementDocument(
|
||||
writer_id=data.get('writer_id', ''),
|
||||
data=data.get('data', ''),
|
||||
image=data.get('image', '')
|
||||
)
|
||||
achievement.save()
|
||||
print(f"文档写入成功,内容: {data}")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"文档写入失败: {str(e)}, 数据: {data}")
|
||||
return False
|
||||
|
||||
def search_data(query):
|
||||
"""
|
||||
在Elasticsearch中搜索数据
|
||||
|
||||
参数:
|
||||
query (str): 搜索关键词
|
||||
|
||||
返回:
|
||||
list: 包含搜索结果的列表
|
||||
"""
|
||||
try:
|
||||
# 使用Django-elasticsearch-dsl进行搜索
|
||||
search = AchievementDocument.search()
|
||||
search = search.query("multi_match", query=query, fields=['*'])
|
||||
response = search.execute()
|
||||
|
||||
results = []
|
||||
for hit in response:
|
||||
results.append({
|
||||
"_id": hit.meta.id,
|
||||
"writer_id": hit.writer_id,
|
||||
"data": hit.data,
|
||||
"image": hit.image
|
||||
})
|
||||
|
||||
return results
|
||||
except Exception as e:
|
||||
print(f"搜索失败: {str(e)}")
|
||||
return []
|
||||
|
||||
def search_all():
|
||||
"""获取所有文档"""
|
||||
try:
|
||||
search = AchievementDocument.search()
|
||||
search = search.query("match_all")
|
||||
response = search.execute()
|
||||
|
||||
results = []
|
||||
for hit in response:
|
||||
results.append({
|
||||
"_id": hit.meta.id,
|
||||
"writer_id": hit.writer_id,
|
||||
"data": hit.data,
|
||||
"image": hit.image
|
||||
})
|
||||
|
||||
return results
|
||||
except Exception as e:
|
||||
print(f"获取所有文档失败: {str(e)}")
|
||||
return []
|
||||
|
||||
def delete_by_id(doc_id):
|
||||
"""
|
||||
根据 doc_id 删除文档
|
||||
|
||||
参数:
|
||||
doc_id (str): 要删除的文档ID
|
||||
|
||||
返回:
|
||||
bool: 删除成功返回True,失败返回False
|
||||
"""
|
||||
try:
|
||||
# 使用Django-elasticsearch-dsl删除文档
|
||||
achievement = AchievementDocument.get(id=doc_id)
|
||||
achievement.delete()
|
||||
print(f"文档 {doc_id} 删除成功")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"删除失败: {str(e)}")
|
||||
return False
|
||||
|
||||
def update_by_id(doc_id, updated_data):
|
||||
"""
|
||||
根据文档ID更新数据
|
||||
|
||||
参数:
|
||||
doc_id (str): 要更新的文档ID
|
||||
updated_data (dict): 更新的数据内容
|
||||
|
||||
返回:
|
||||
bool: 更新成功返回True,失败返回False
|
||||
"""
|
||||
try:
|
||||
# 获取文档
|
||||
achievement = AchievementDocument.get(id=doc_id)
|
||||
|
||||
# 更新字段
|
||||
if 'writer_id' in updated_data:
|
||||
achievement.writer_id = updated_data['writer_id']
|
||||
if 'data' in updated_data:
|
||||
achievement.data = updated_data['data']
|
||||
if 'image' in updated_data:
|
||||
achievement.image = updated_data['image']
|
||||
|
||||
achievement.save()
|
||||
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:
|
||||
achievement = AchievementDocument.get(id=doc_id)
|
||||
return {
|
||||
"_id": achievement.meta.id,
|
||||
"writer_id": achievement.writer_id,
|
||||
"data": achievement.data,
|
||||
"image": achievement.image
|
||||
}
|
||||
except Exception as e:
|
||||
print(f"获取文档失败: {str(e)}")
|
||||
return None
|
||||
|
||||
def search_by_any_field(keyword):
|
||||
"""
|
||||
在任意字段中搜索关键词(支持模糊搜索)
|
||||
|
||||
参数:
|
||||
keyword (str): 搜索关键词
|
||||
|
||||
返回:
|
||||
list: 包含搜索结果的列表
|
||||
"""
|
||||
try:
|
||||
search = AchievementDocument.search()
|
||||
|
||||
# 使用multi_match查询,在所有字段中搜索
|
||||
search = search.query("multi_match",
|
||||
query=keyword,
|
||||
fields=['*'],
|
||||
fuzziness="AUTO")
|
||||
|
||||
response = search.execute()
|
||||
|
||||
results = []
|
||||
for hit in response:
|
||||
results.append({
|
||||
"_id": hit.meta.id,
|
||||
"writer_id": hit.writer_id,
|
||||
"data": hit.data,
|
||||
"image": hit.image
|
||||
})
|
||||
|
||||
return results
|
||||
except Exception as e:
|
||||
print(f"模糊搜索失败: {str(e)}")
|
||||
return []
|
||||
|
||||
def write_user_data(user_data):
|
||||
"""
|
||||
写入用户数据到 ES
|
||||
|
||||
参数:
|
||||
user_data (dict): 用户数据
|
||||
|
||||
返回:
|
||||
bool: 写入成功返回True,失败返回False
|
||||
"""
|
||||
try:
|
||||
user = UserDocument(
|
||||
user_id=user_data.get('user_id'),
|
||||
username=user_data.get('username'),
|
||||
password=user_data.get('password'),
|
||||
permission=user_data.get('permission', 1)
|
||||
)
|
||||
user.save()
|
||||
print(f"用户数据写入成功: {user_data.get('username')}")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"用户数据写入失败: {str(e)}")
|
||||
return False
|
||||
|
||||
def get_user_by_username(username):
|
||||
"""
|
||||
根据用户名获取用户数据
|
||||
|
||||
参数:
|
||||
username (str): 用户名
|
||||
|
||||
返回:
|
||||
dict or None: 用户数据或None
|
||||
"""
|
||||
try:
|
||||
search = UserDocument.search()
|
||||
search = search.query("term", username=username)
|
||||
response = search.execute()
|
||||
|
||||
if response.hits:
|
||||
hit = response.hits[0]
|
||||
return {
|
||||
"user_id": hit.user_id,
|
||||
"username": hit.username,
|
||||
"password": hit.password,
|
||||
"permission": hit.permission
|
||||
}
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"获取用户数据失败: {str(e)}")
|
||||
return None
|
||||
|
||||
def get_all_users():
|
||||
"""获取所有用户"""
|
||||
try:
|
||||
search = UserDocument.search()
|
||||
search = search.query("match_all")
|
||||
response = search.execute()
|
||||
|
||||
users = []
|
||||
for hit in response:
|
||||
users.append({
|
||||
"user_id": hit.user_id,
|
||||
"username": hit.username,
|
||||
"permission": hit.permission
|
||||
})
|
||||
|
||||
return users
|
||||
except Exception as e:
|
||||
print(f"获取所有用户失败: {str(e)}")
|
||||
return []
|
||||
|
||||
def delete_user_by_username(username):
|
||||
"""
|
||||
根据用户名删除用户
|
||||
|
||||
参数:
|
||||
username (str): 用户名
|
||||
|
||||
返回:
|
||||
bool: 删除成功返回True,失败返回False
|
||||
"""
|
||||
try:
|
||||
search = UserDocument.search()
|
||||
search = search.query("term", username=username)
|
||||
response = search.execute()
|
||||
|
||||
if response.hits:
|
||||
user = response.hits[0]
|
||||
user.delete()
|
||||
print(f"用户 {username} 删除成功")
|
||||
return True
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"删除用户失败: {str(e)}")
|
||||
return False
|
||||
|
||||
def update_user_permission(username, new_permission):
|
||||
"""
|
||||
更新用户权限
|
||||
|
||||
参数:
|
||||
username (str): 用户名
|
||||
new_permission (int): 新权限级别
|
||||
|
||||
返回:
|
||||
bool: 更新成功返回True,失败返回False
|
||||
"""
|
||||
try:
|
||||
search = UserDocument.search()
|
||||
search = search.query("term", username=username)
|
||||
response = search.execute()
|
||||
|
||||
if response.hits:
|
||||
user = response.hits[0]
|
||||
user.permission = new_permission
|
||||
user.save()
|
||||
print(f"用户 {username} 权限更新为 {new_permission}")
|
||||
return True
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"更新用户权限失败: {str(e)}")
|
||||
return False
|
||||
4
elastic/indexes.py
Normal file
4
elastic/indexes.py
Normal file
@@ -0,0 +1,4 @@
|
||||
INDEX_NAME = "wordsearch266666"
|
||||
USER_NAME = "users"
|
||||
ACHIEVEMENT_INDEX_NAME = INDEX_NAME
|
||||
USER_INDEX_NAME = USER_NAME
|
||||
0
elastic/migrations/__init__.py
Normal file
0
elastic/migrations/__init__.py
Normal file
41
elastic/models.py
Normal file
41
elastic/models.py
Normal file
@@ -0,0 +1,41 @@
|
||||
from django.db import models
|
||||
|
||||
class AchievementData(models.Model):
|
||||
"""获奖数据模型,对应Flask项目中的wordsearch266666索引"""
|
||||
writer_id = models.CharField(max_length=100, verbose_name="作者ID")
|
||||
data = models.TextField(verbose_name="数据内容")
|
||||
image = models.CharField(max_length=500, blank=True, null=True, verbose_name="图片路径")
|
||||
created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
|
||||
updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
|
||||
|
||||
class Meta:
|
||||
verbose_name = "获奖数据"
|
||||
verbose_name_plural = verbose_name
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.writer_id} - {self.data[:50]}"
|
||||
|
||||
|
||||
class User(models.Model):
|
||||
"""用户模型,对应Flask项目中的users索引"""
|
||||
user_id = models.BigIntegerField(unique=True, verbose_name="用户ID")
|
||||
username = models.CharField(max_length=100, unique=True, verbose_name="用户名")
|
||||
password = models.CharField(max_length=100, verbose_name="密码")
|
||||
permission = models.IntegerField(default=1, verbose_name="权限级别")
|
||||
created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
|
||||
|
||||
class Meta:
|
||||
verbose_name = "用户"
|
||||
verbose_name_plural = verbose_name
|
||||
|
||||
def __str__(self):
|
||||
return self.username
|
||||
|
||||
# 保留原有的ElasticNews模型用于兼容
|
||||
class ElasticNews(models.Model):
|
||||
title = models.CharField(max_length=100)
|
||||
content = models.TextField()
|
||||
|
||||
class Meta:
|
||||
verbose_name = "新闻"
|
||||
verbose_name_plural = verbose_name
|
||||
176
elastic/templates/elastic/manage.html
Normal file
176
elastic/templates/elastic/manage.html
Normal file
@@ -0,0 +1,176 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>数据管理</title>
|
||||
<style>
|
||||
body { font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif; background:#fafafa; }
|
||||
.container { max-width: 1100px; margin: 6vh auto; background:#fff; border-radius:10px; box-shadow:0 6px 18px rgba(0,0,0,0.06); padding:20px; }
|
||||
table { width:100%; border-collapse: collapse; }
|
||||
th, td { border-bottom:1px solid #eee; padding:8px; text-align:left; vertical-align: top; }
|
||||
img { max-width: 120px; border:1px solid #eee; border-radius:6px; }
|
||||
.btn { padding:6px 10px; border:none; border-radius:6px; cursor:pointer; }
|
||||
.btn-primary { background:#1677ff; color:#fff; }
|
||||
.btn-danger { background:#ff4d4f; color:#fff; }
|
||||
.btn-secondary { background:#f0f0f0; }
|
||||
.muted { color:#666; font-size:12px; }
|
||||
.modal { position: fixed; inset: 0; display: none; background: rgba(0,0,0,0.4); align-items: center; justify-content: center; }
|
||||
.modal .dialog { width: 720px; max-width: 92vw; background:#fff; border-radius:10px; padding:16px; }
|
||||
textarea { width:100%; min-height: 240px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size:14px; }
|
||||
#kvForm { border:1px solid #eee; border-radius:6px; padding:8px; max-height:300px; overflow:auto; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h2>数据管理</h2>
|
||||
<p class="muted">仅管理员可见。可查看、编辑、删除所有记录。</p>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>图片</th>
|
||||
<th>数据</th>
|
||||
<th>作者</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for it in items %}
|
||||
<tr data-id="{{ it.id }}" data-writer="{{ it.writer_id }}" data-image="{{ it.image }}">
|
||||
<td style="max-width:140px; word-break:break-all;">{{ it.id }}</td>
|
||||
<td>
|
||||
{% if it.image %}
|
||||
<img src="/media/{{ it.image }}" onerror="this.src='';" />
|
||||
<div class="muted">/media/{{ it.image }}</div>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>
|
||||
<pre style="white-space:pre-wrap; word-wrap:break-word;">{{ it.data|safe }}</pre>
|
||||
</td>
|
||||
<td>{{ it.writer_id }}</td>
|
||||
<td>
|
||||
<button class="btn btn-primary" onclick="openEdit('{{ it.id }}')">编辑</button>
|
||||
<button class="btn btn-danger" onclick="doDelete('{{ it.id }}')">删除</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div id="modal" class="modal">
|
||||
<div class="dialog">
|
||||
<h3>编辑</h3>
|
||||
<div style="display:flex; gap:8px; align-items:center; margin-bottom:8px;">
|
||||
<button id="addFieldBtn" class="btn btn-secondary" type="button">添加字段</button>
|
||||
<button id="syncFromTextBtn" class="btn btn-secondary" type="button">从文本区刷新表单</button>
|
||||
<span id="editMsg" class="muted"></span>
|
||||
</div>
|
||||
<div id="kvForm"></div>
|
||||
<div style="margin-top:8px;">
|
||||
<textarea id="resultBox" placeholder="JSON"></textarea>
|
||||
</div>
|
||||
<div style="margin-top:12px; display:flex; gap:8px;">
|
||||
<button class="btn btn-primary" onclick="saveEdit()">保存</button>
|
||||
<button class="btn" onclick="closeModal()">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function getCookie(name) {
|
||||
const value = `; ${document.cookie}`;
|
||||
const parts = value.split(`; ${name}=`);
|
||||
if (parts.length === 2) return parts.pop().split(';').shift();
|
||||
}
|
||||
|
||||
const modal = document.getElementById('modal');
|
||||
const kvForm = document.getElementById('kvForm');
|
||||
const resultBox = document.getElementById('resultBox');
|
||||
const editMsg = document.getElementById('editMsg');
|
||||
const addFieldBtn = document.getElementById('addFieldBtn');
|
||||
const syncFromTextBtn = document.getElementById('syncFromTextBtn');
|
||||
|
||||
let currentId = '';
|
||||
let currentWriter = '';
|
||||
let currentImage = '';
|
||||
|
||||
function createRow(k = '', v = '') {
|
||||
const row = document.createElement('div');
|
||||
row.style.display = 'grid';
|
||||
row.style.gridTemplateColumns = '1fr 1fr auto';
|
||||
row.style.gap = '8px';
|
||||
row.style.marginBottom = '6px';
|
||||
const kI = document.createElement('input'); kI.type='text'; kI.placeholder='字段名'; kI.value=k;
|
||||
const vI = document.createElement('input'); vI.type='text'; vI.placeholder='字段值'; vI.value = typeof v==='object'? JSON.stringify(v): (v??'');
|
||||
const del = document.createElement('button'); del.type='button'; del.className='btn'; del.textContent='删除'; del.onclick=()=>{ kvForm.removeChild(row); syncTextarea(); };
|
||||
kI.oninput = syncTextarea; vI.oninput = syncTextarea;
|
||||
row.appendChild(kI); row.appendChild(vI); row.appendChild(del);
|
||||
return row;
|
||||
}
|
||||
|
||||
function renderForm(obj){
|
||||
kvForm.innerHTML='';
|
||||
Object.keys(obj||{}).forEach(k=> kvForm.appendChild(createRow(k, obj[k])));
|
||||
if (!kvForm.children.length) kvForm.appendChild(createRow());
|
||||
syncTextarea();
|
||||
}
|
||||
function formToObject(){
|
||||
const o={};
|
||||
Array.from(kvForm.children).forEach(row=>{
|
||||
const [kI,vI] = row.querySelectorAll('input');
|
||||
const k=(kI.value||'').trim(); if(!k) return;
|
||||
const raw=vI.value; try{ o[k]=JSON.parse(raw);}catch(_){ o[k]=raw; }
|
||||
});
|
||||
return o;
|
||||
}
|
||||
function syncTextarea(){ resultBox.value = JSON.stringify(formToObject(), null, 2); }
|
||||
|
||||
addFieldBtn.onclick = ()=>{ kvForm.appendChild(createRow()); syncTextarea(); };
|
||||
syncFromTextBtn.onclick = ()=>{ try{ renderForm(JSON.parse(resultBox.value||'{}')); }catch(e){ editMsg.textContent='JSON无效'; } };
|
||||
|
||||
function openEdit(id){
|
||||
const tr = document.querySelector(`tr[data-id="${id}"]`);
|
||||
currentId = id;
|
||||
currentWriter = tr?.getAttribute('data-writer') || '';
|
||||
currentImage = tr?.getAttribute('data-image') || '';
|
||||
fetch(`/elastic/data/${id}/`, { credentials:'same-origin' })
|
||||
.then(r=>r.json()).then(d=>{
|
||||
if(d.status!=='success') throw new Error('获取失败');
|
||||
const rec=d.data||{};
|
||||
const dataStr = rec.data || '{}';
|
||||
let obj={}; try{ obj = typeof dataStr==='string'? JSON.parse(dataStr): (dataStr||{});}catch(_){ obj={}; }
|
||||
renderForm(obj);
|
||||
modal.style.display='flex';
|
||||
}).catch(e=>{ alert(e.message||'发生错误'); });
|
||||
}
|
||||
function closeModal(){ modal.style.display='none'; currentId=''; }
|
||||
function saveEdit(){
|
||||
const body = {
|
||||
writer_id: currentWriter,
|
||||
data: JSON.stringify(formToObject()),
|
||||
image: currentImage,
|
||||
};
|
||||
fetch(`/elastic/data/${currentId}/update/`, {
|
||||
method:'PUT', credentials:'same-origin',
|
||||
headers:{ 'Content-Type':'application/json', 'X-CSRFToken': getCookie('csrftoken')||'' },
|
||||
body: JSON.stringify(body),
|
||||
}).then(r=>r.json()).then(d=>{
|
||||
if(d.status!=='success') throw new Error('保存失败');
|
||||
location.reload();
|
||||
}).catch(e=>{ editMsg.textContent = e.message||'发生错误'; });
|
||||
}
|
||||
function doDelete(id){
|
||||
if(!confirm('确认删除该记录?')) return;
|
||||
fetch(`/elastic/data/${id}/delete/`, {
|
||||
method:'DELETE', credentials:'same-origin',
|
||||
headers:{ 'X-CSRFToken': getCookie('csrftoken')||'' }
|
||||
}).then(r=>r.json()).then(d=>{
|
||||
if(d.status!=='success') throw new Error('删除失败');
|
||||
location.reload();
|
||||
}).catch(e=> alert(e.message||'发生错误'));
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
228
elastic/templates/elastic/upload.html
Normal file
228
elastic/templates/elastic/upload.html
Normal file
@@ -0,0 +1,228 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>图片上传与识别</title>
|
||||
<style>
|
||||
body { font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif; background: #fafafa; }
|
||||
.container { max-width: 900px; margin: 6vh auto; background: #fff; border-radius: 10px; box-shadow: 0 6px 18px rgba(0,0,0,0.06); padding: 24px; }
|
||||
.row { display: flex; gap: 16px; }
|
||||
.col { flex: 1; }
|
||||
textarea { width: 100%; min-height: 260px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 14px; }
|
||||
img { max-width: 100%; border: 1px solid #eee; border-radius: 6px; }
|
||||
.btn { padding: 8px 12px; border: none; border-radius: 6px; cursor: pointer; }
|
||||
.btn-primary { background: #1677ff; color: #fff; }
|
||||
.btn-secondary { background: #f0f0f0; }
|
||||
.muted { color: #666; font-size: 12px; }
|
||||
.error { color: #d14343; }
|
||||
.success { color: #179957; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h2>图片上传与识别</h2>
|
||||
<p class="muted">选择图片后上传,服务端调用大模型解析为可编辑的 JSON,再确认入库。</p>
|
||||
|
||||
<form id="uploadForm" enctype="multipart/form-data">
|
||||
{% csrf_token %}
|
||||
<input type="file" id="fileInput" name="file" accept="image/*" />
|
||||
<button type="submit" class="btn btn-primary">上传并识别</button>
|
||||
<span id="uploadMsg" class="muted"></span>
|
||||
</form>
|
||||
|
||||
<div class="row" style="margin-top:16px;">
|
||||
<div class="col">
|
||||
<h4>图片预览</h4>
|
||||
<img id="preview" alt="预览" />
|
||||
</div>
|
||||
<div class="col">
|
||||
<h4>识别结果(可编辑)</h4>
|
||||
<div style="display:flex; gap:8px; align-items:center; margin-bottom:8px;">
|
||||
<button id="addFieldBtn" class="btn btn-secondary" type="button">添加字段</button>
|
||||
<button id="syncFromTextBtn" class="btn btn-secondary" type="button">从文本区刷新表单</button>
|
||||
</div>
|
||||
<div id="kvForm" style="border:1px solid #eee; border-radius:6px; padding:8px; max-height:300px; overflow:auto;"></div>
|
||||
<div style="margin-top:8px;">
|
||||
<textarea id="resultBox" placeholder="识别结果JSON将显示在这里"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="margin-top:16px;">
|
||||
<button id="confirmBtn" class="btn btn-primary" disabled>确认并入库</button>
|
||||
<button id="clearBtn" class="btn btn-secondary" type="button">清空</button>
|
||||
<span id="confirmMsg" class="muted"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function getCookie(name) {
|
||||
const value = `; ${document.cookie}`;
|
||||
const parts = value.split(`; ${name}=`);
|
||||
if (parts.length === 2) return parts.pop().split(';').shift();
|
||||
}
|
||||
|
||||
const uploadForm = document.getElementById('uploadForm');
|
||||
const fileInput = document.getElementById('fileInput');
|
||||
const preview = document.getElementById('preview');
|
||||
const resultBox = document.getElementById('resultBox');
|
||||
const uploadMsg = document.getElementById('uploadMsg');
|
||||
const confirmBtn = document.getElementById('confirmBtn');
|
||||
const clearBtn = document.getElementById('clearBtn');
|
||||
const confirmMsg = document.getElementById('confirmMsg');
|
||||
const kvForm = document.getElementById('kvForm');
|
||||
const addFieldBtn = document.getElementById('addFieldBtn');
|
||||
const syncFromTextBtn = document.getElementById('syncFromTextBtn');
|
||||
|
||||
let currentImageRel = '';
|
||||
|
||||
function createRow(k = '', v = '') {
|
||||
const row = document.createElement('div');
|
||||
row.style.display = 'grid';
|
||||
row.style.gridTemplateColumns = '1fr 1fr auto';
|
||||
row.style.gap = '8px';
|
||||
row.style.marginBottom = '6px';
|
||||
const keyInput = document.createElement('input');
|
||||
keyInput.type = 'text';
|
||||
keyInput.placeholder = '字段名';
|
||||
keyInput.value = k;
|
||||
const valInput = document.createElement('input');
|
||||
valInput.type = 'text';
|
||||
valInput.placeholder = '字段值';
|
||||
valInput.value = typeof v === 'object' ? JSON.stringify(v) : (v ?? '');
|
||||
const delBtn = document.createElement('button');
|
||||
delBtn.type = 'button';
|
||||
delBtn.className = 'btn btn-secondary';
|
||||
delBtn.textContent = '删除';
|
||||
delBtn.onclick = () => { kvForm.removeChild(row); syncTextarea(); };
|
||||
keyInput.oninput = syncTextarea;
|
||||
valInput.oninput = syncTextarea;
|
||||
row.appendChild(keyInput);
|
||||
row.appendChild(valInput);
|
||||
row.appendChild(delBtn);
|
||||
return row;
|
||||
}
|
||||
|
||||
function renderFormFromObject(obj) {
|
||||
kvForm.innerHTML = '';
|
||||
Object.keys(obj || {}).forEach(k => {
|
||||
kvForm.appendChild(createRow(k, obj[k]));
|
||||
});
|
||||
if (!kvForm.children.length) kvForm.appendChild(createRow());
|
||||
syncTextarea();
|
||||
}
|
||||
|
||||
function objectFromForm() {
|
||||
const obj = {};
|
||||
Array.from(kvForm.children).forEach(row => {
|
||||
const [kInput, vInput] = row.querySelectorAll('input');
|
||||
const k = (kInput.value || '').trim();
|
||||
if (!k) return;
|
||||
const raw = vInput.value;
|
||||
try {
|
||||
obj[k] = JSON.parse(raw);
|
||||
} catch (_) {
|
||||
obj[k] = raw;
|
||||
}
|
||||
});
|
||||
return obj;
|
||||
}
|
||||
|
||||
function syncTextarea() {
|
||||
const obj = objectFromForm();
|
||||
resultBox.value = JSON.stringify(obj, null, 2);
|
||||
}
|
||||
|
||||
addFieldBtn.addEventListener('click', () => {
|
||||
kvForm.appendChild(createRow());
|
||||
syncTextarea();
|
||||
});
|
||||
|
||||
syncFromTextBtn.addEventListener('click', () => {
|
||||
try {
|
||||
const obj = JSON.parse(resultBox.value || '{}');
|
||||
renderFormFromObject(obj);
|
||||
} catch (e) {
|
||||
uploadMsg.textContent = '文本区不是有效JSON';
|
||||
uploadMsg.className = 'error';
|
||||
}
|
||||
});
|
||||
|
||||
uploadForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
uploadMsg.textContent = '';
|
||||
confirmMsg.textContent = '';
|
||||
confirmBtn.disabled = true;
|
||||
resultBox.value = '';
|
||||
currentImageRel = '';
|
||||
|
||||
const file = fileInput.files[0];
|
||||
if (!file) {
|
||||
uploadMsg.textContent = '请选择图片文件';
|
||||
uploadMsg.className = 'error';
|
||||
return;
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
try {
|
||||
const resp = await fetch('/elastic/upload/', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'X-CSRFToken': getCookie('csrftoken') || '' },
|
||||
body: formData,
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (!resp.ok || data.status !== 'success') {
|
||||
throw new Error(data.message || '上传识别失败');
|
||||
}
|
||||
uploadMsg.textContent = data.message || '识别成功';
|
||||
uploadMsg.className = 'success';
|
||||
preview.src = data.image_url;
|
||||
renderFormFromObject(data.data || {});
|
||||
currentImageRel = data.image;
|
||||
confirmBtn.disabled = false;
|
||||
} catch (e) {
|
||||
uploadMsg.textContent = e.message || '发生错误';
|
||||
uploadMsg.className = 'error';
|
||||
}
|
||||
});
|
||||
|
||||
confirmBtn.addEventListener('click', async () => {
|
||||
confirmMsg.textContent = '';
|
||||
try {
|
||||
const edited = objectFromForm();
|
||||
const resp = await fetch('/elastic/confirm/', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRFToken': getCookie('csrftoken') || ''
|
||||
},
|
||||
body: JSON.stringify({ data: edited, image: currentImageRel })
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (!resp.ok || data.status !== 'success') {
|
||||
throw new Error(data.message || '录入失败');
|
||||
}
|
||||
confirmMsg.textContent = data.message || '录入成功';
|
||||
confirmMsg.className = 'success';
|
||||
} catch (e) {
|
||||
confirmMsg.textContent = e.message || '发生错误';
|
||||
confirmMsg.className = 'error';
|
||||
}
|
||||
});
|
||||
|
||||
clearBtn.addEventListener('click', () => {
|
||||
fileInput.value = '';
|
||||
preview.src = '';
|
||||
resultBox.value = '';
|
||||
kvForm.innerHTML = '';
|
||||
uploadMsg.textContent = '';
|
||||
confirmMsg.textContent = '';
|
||||
confirmBtn.disabled = true;
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
3
elastic/tests.py
Normal file
3
elastic/tests.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
||||
34
elastic/urls.py
Normal file
34
elastic/urls.py
Normal file
@@ -0,0 +1,34 @@
|
||||
from django.urls import path
|
||||
from . import views
|
||||
|
||||
app_name = 'elastic'
|
||||
|
||||
urlpatterns = [
|
||||
# ES索引管理
|
||||
# path('init-index/', views.init_index, name='init_index'),
|
||||
|
||||
# 数据操作
|
||||
path('data/', views.add_data, name='add_data'),
|
||||
path('data/<str:doc_id>/', views.get_data, name='get_data'),
|
||||
path('data/<str:doc_id>/update/', views.update_data, name='update_data'),
|
||||
path('data/<str:doc_id>/delete/', views.delete_data, name='delete_data'),
|
||||
|
||||
# 搜索功能
|
||||
path('search/', views.search, name='search'),
|
||||
path('fuzzy-search/', views.fuzzy_search, name='fuzzy_search'),
|
||||
path('all-data/', views.get_all_data, name='get_all_data'),
|
||||
|
||||
# 用户管理
|
||||
path('users/', views.get_users, name='get_users'),
|
||||
path('users/add/', views.add_user, name='add_user'),
|
||||
path('users/<str:username>/delete/', views.delete_user, name='delete_user'),
|
||||
path('users/<str:username>/update/', views.update_user, name='update_user'),
|
||||
|
||||
# 图片上传与确认
|
||||
path('upload-page/', views.upload_page, name='upload_page'),
|
||||
path('upload/', views.upload, name='upload'),
|
||||
path('confirm/', views.confirm, name='confirm'),
|
||||
|
||||
# 管理页面
|
||||
path('manage/', views.manage_page, name='manage_page'),
|
||||
]
|
||||
406
elastic/views.py
Normal file
406
elastic/views.py
Normal file
@@ -0,0 +1,406 @@
|
||||
"""
|
||||
ES相关的API视图
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
import base64
|
||||
import json
|
||||
from django.conf import settings
|
||||
from django.http import JsonResponse
|
||||
from django.shortcuts import render
|
||||
from django.views.decorators.http import require_http_methods
|
||||
from django.views.decorators.csrf import ensure_csrf_cookie
|
||||
from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie
|
||||
from .es_connect import *
|
||||
from openai import OpenAI
|
||||
|
||||
|
||||
@require_http_methods(["GET", "POST"])
|
||||
@csrf_exempt
|
||||
def init_index(request):
|
||||
"""初始化ES索引"""
|
||||
print("⚠️ init_index 被调用了!")
|
||||
try:
|
||||
create_index_with_mapping()
|
||||
return JsonResponse({"status": "success", "message": "索引初始化成功"})
|
||||
except Exception as e:
|
||||
return JsonResponse({"status": "error", "message": str(e)}, status=500)
|
||||
|
||||
|
||||
@require_http_methods(["POST"])
|
||||
@csrf_exempt
|
||||
def add_data(request):
|
||||
"""添加数据到ES"""
|
||||
try:
|
||||
data = json.loads(request.body.decode('utf-8'))
|
||||
success = insert_data(data)
|
||||
if success:
|
||||
return JsonResponse({"status": "success", "message": "数据添加成功"})
|
||||
else:
|
||||
return JsonResponse({"status": "error", "message": "数据添加失败"}, status=500)
|
||||
except Exception as e:
|
||||
return JsonResponse({"status": "error", "message": str(e)}, status=500)
|
||||
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
def search(request):
|
||||
"""搜索数据"""
|
||||
try:
|
||||
query = request.GET.get('q', '')
|
||||
if not query:
|
||||
return JsonResponse({"status": "error", "message": "搜索关键词不能为空"}, status=400)
|
||||
|
||||
results = search_data(query)
|
||||
return JsonResponse({"status": "success", "data": results})
|
||||
except Exception as e:
|
||||
return JsonResponse({"status": "error", "message": str(e)}, status=500)
|
||||
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
def fuzzy_search(request):
|
||||
"""模糊搜索"""
|
||||
try:
|
||||
keyword = request.GET.get('keyword', '')
|
||||
if not keyword:
|
||||
return JsonResponse({"status": "error", "message": "搜索关键词不能为空"}, status=400)
|
||||
|
||||
results = search_by_any_field(keyword)
|
||||
return JsonResponse({"status": "success", "data": results})
|
||||
except Exception as e:
|
||||
return JsonResponse({"status": "error", "message": str(e)}, status=500)
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
def get_all_data(request):
|
||||
"""获取所有数据"""
|
||||
try:
|
||||
results = search_all()
|
||||
return JsonResponse({"status": "success", "data": results})
|
||||
except Exception as e:
|
||||
return JsonResponse({"status": "error", "message": str(e)}, status=500)
|
||||
|
||||
|
||||
@require_http_methods(["DELETE"])
|
||||
@csrf_exempt
|
||||
def delete_data(request, doc_id):
|
||||
"""删除数据(需登录;管理员或作者本人)"""
|
||||
if not request.session.get("user_id"):
|
||||
return JsonResponse({"status": "error", "message": "未登录"}, status=401)
|
||||
try:
|
||||
existing = get_by_id(doc_id)
|
||||
if not existing:
|
||||
return JsonResponse({"status": "error", "message": "数据不存在"}, status=404)
|
||||
is_admin = (request.session.get("permission", 1) == 0)
|
||||
is_owner = str(existing.get("writer_id", "")) == str(request.session.get("user_id"))
|
||||
if not (is_admin or is_owner):
|
||||
return JsonResponse({"status": "error", "message": "无权限"}, status=403)
|
||||
success = delete_by_id(doc_id)
|
||||
if success:
|
||||
return JsonResponse({"status": "success", "message": "数据删除成功"})
|
||||
else:
|
||||
return JsonResponse({"status": "error", "message": "数据删除失败"}, status=500)
|
||||
except Exception as e:
|
||||
return JsonResponse({"status": "error", "message": str(e)}, status=500)
|
||||
|
||||
|
||||
@require_http_methods(["PUT"])
|
||||
@csrf_exempt
|
||||
def update_data(request, doc_id):
|
||||
"""更新数据(需登录;管理员或作者本人)"""
|
||||
if not request.session.get("user_id"):
|
||||
return JsonResponse({"status": "error", "message": "未登录"}, status=401)
|
||||
try:
|
||||
payload = json.loads(request.body.decode('utf-8'))
|
||||
except Exception:
|
||||
return JsonResponse({"status": "error", "message": "JSON无效"}, status=400)
|
||||
try:
|
||||
existing = get_by_id(doc_id)
|
||||
if not existing:
|
||||
return JsonResponse({"status": "error", "message": "数据不存在"}, status=404)
|
||||
is_admin = (request.session.get("permission", 1) == 0)
|
||||
is_owner = str(existing.get("writer_id", "")) == str(request.session.get("user_id"))
|
||||
if not (is_admin or is_owner):
|
||||
return JsonResponse({"status": "error", "message": "无权限"}, status=403)
|
||||
|
||||
updated = {}
|
||||
if "writer_id" in payload:
|
||||
updated["writer_id"] = payload["writer_id"]
|
||||
if "image" in payload:
|
||||
updated["image"] = payload["image"]
|
||||
if "data" in payload:
|
||||
v = payload["data"]
|
||||
if isinstance(v, dict):
|
||||
updated["data"] = json.dumps(v, ensure_ascii=False)
|
||||
else:
|
||||
updated["data"] = str(v)
|
||||
|
||||
success = update_by_id(doc_id, updated)
|
||||
if success:
|
||||
return JsonResponse({"status": "success", "message": "数据更新成功"})
|
||||
else:
|
||||
return JsonResponse({"status": "error", "message": "数据更新失败"}, status=500)
|
||||
except Exception as e:
|
||||
return JsonResponse({"status": "error", "message": str(e)}, status=500)
|
||||
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
def get_data(request, doc_id):
|
||||
"""获取单个数据"""
|
||||
try:
|
||||
result = get_by_id(doc_id)
|
||||
if result:
|
||||
return JsonResponse({"status": "success", "data": result})
|
||||
else:
|
||||
return JsonResponse({"status": "error", "message": "数据不存在"}, status=404)
|
||||
except Exception as e:
|
||||
return JsonResponse({"status": "error", "message": str(e)}, status=500)
|
||||
|
||||
|
||||
@require_http_methods(["POST"])
|
||||
@csrf_exempt
|
||||
def add_user(request):
|
||||
"""添加用户"""
|
||||
try:
|
||||
data = json.loads(request.body.decode('utf-8'))
|
||||
success = write_user_data(data)
|
||||
if success:
|
||||
return JsonResponse({"status": "success", "message": "用户添加成功"})
|
||||
else:
|
||||
return JsonResponse({"status": "error", "message": "用户添加失败"}, status=500)
|
||||
except Exception as e:
|
||||
return JsonResponse({"status": "error", "message": str(e)}, status=500)
|
||||
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
def get_users(request):
|
||||
"""获取所有用户"""
|
||||
try:
|
||||
users = get_all_users()
|
||||
return JsonResponse({"status": "success", "data": users})
|
||||
except Exception as e:
|
||||
return JsonResponse({"status": "error", "message": str(e)}, status=500)
|
||||
|
||||
|
||||
@require_http_methods(["DELETE"])
|
||||
@csrf_exempt
|
||||
def delete_user(request, username):
|
||||
"""删除用户"""
|
||||
try:
|
||||
success = delete_user_by_username(username)
|
||||
if success:
|
||||
return JsonResponse({"status": "success", "message": "用户删除成功"})
|
||||
else:
|
||||
return JsonResponse({"status": "error", "message": "用户删除失败"}, status=500)
|
||||
except Exception as e:
|
||||
return JsonResponse({"status": "error", "message": str(e)}, status=500)
|
||||
|
||||
|
||||
@require_http_methods(["PUT"])
|
||||
@csrf_exempt
|
||||
def update_user(request, username):
|
||||
"""更新用户权限"""
|
||||
try:
|
||||
data = json.loads(request.body.decode('utf-8'))
|
||||
new_permission = data.get('permission', 1)
|
||||
success = update_user_permission(username, new_permission)
|
||||
if success:
|
||||
return JsonResponse({"status": "success", "message": "用户权限更新成功"})
|
||||
else:
|
||||
return JsonResponse({"status": "error", "message": "用户权限更新失败"}, status=500)
|
||||
except Exception as e:
|
||||
return JsonResponse({"status": "error", "message": str(e)}, status=500)
|
||||
|
||||
|
||||
# 辅助:JSON 转换(兼容 a.py 行为)
|
||||
def json_to_string(obj):
|
||||
try:
|
||||
return json.dumps(obj, ensure_ascii=False)
|
||||
except Exception:
|
||||
return str(obj)
|
||||
|
||||
|
||||
def string_to_json(s):
|
||||
try:
|
||||
return json.loads(s)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
# 移植自 a.py 的核心:调用大模型进行 OCR/信息抽取
|
||||
def ocr_and_extract_info(image_path: str):
|
||||
def encode_image(path: str) -> str:
|
||||
with open(path, "rb") as f:
|
||||
return base64.b64encode(f.read()).decode("utf-8")
|
||||
|
||||
base64_image = encode_image(image_path)
|
||||
|
||||
api_key = getattr(settings, "AISTUDIO_API_KEY", "")
|
||||
base_url = getattr(settings, "OPENAI_BASE_URL", "https://aistudio.baidu.com/llm/lmapi/v3")
|
||||
if not api_key:
|
||||
raise RuntimeError("缺少 AISTUDIO_API_KEY,请在环境变量或 settings 中配置")
|
||||
|
||||
client = OpenAI(api_key=api_key, base_url=base_url)
|
||||
|
||||
chat_completion = client.chat.completions.create(
|
||||
messages=[
|
||||
{"role": "system", "content": "你是一个能理解图片和文本的助手,请根据用户提供的信息进行回答。"},
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "请识别这张图片中的信息,将你认为重要的数据转换为不包含嵌套的json,不要显示其它信息以便于解析直接输出json结果即可你可以自行决定使用哪些json字段"},
|
||||
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{base64_image}"}},
|
||||
],
|
||||
},
|
||||
],
|
||||
model="ernie-4.5-turbo-vl-32k",
|
||||
)
|
||||
|
||||
response_text = chat_completion.choices[0].message.content
|
||||
|
||||
def parse_response(text: str):
|
||||
try:
|
||||
result = json.loads(text)
|
||||
if result:
|
||||
return result
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
m = re.search(r"```json\n(.*?)```", text, re.DOTALL)
|
||||
if m:
|
||||
try:
|
||||
result = json.loads(m.group(1))
|
||||
if result:
|
||||
return result
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
try:
|
||||
fixed = text.replace("'", '"')
|
||||
result = json.loads(fixed)
|
||||
if result:
|
||||
return result
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
return None
|
||||
|
||||
return parse_response(response_text)
|
||||
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
@ensure_csrf_cookie
|
||||
def upload_page(request):
|
||||
session_user_id = request.session.get("user_id")
|
||||
if session_user_id is None:
|
||||
from django.shortcuts import redirect
|
||||
return redirect("/accounts/login/")
|
||||
user_id_qs = request.GET.get("user_id")
|
||||
context = {"user_id": user_id_qs or session_user_id}
|
||||
return render(request, "elastic/upload.html", context)
|
||||
|
||||
|
||||
# 上传并识别(不入库)
|
||||
@require_http_methods(["POST"])
|
||||
def upload(request):
|
||||
if not request.session.get("user_id"):
|
||||
fallback_uid = request.POST.get("user_id") or request.GET.get("user_id")
|
||||
if fallback_uid:
|
||||
request.session["user_id"] = fallback_uid
|
||||
request.session.setdefault("permission", 1)
|
||||
else:
|
||||
return JsonResponse({"status": "error", "message": "未登录"}, status=401)
|
||||
|
||||
file = request.FILES.get("file")
|
||||
if not file:
|
||||
return JsonResponse({"status": "error", "message": "未选择文件"}, status=400)
|
||||
|
||||
images_dir = os.path.join(settings.MEDIA_ROOT, "images")
|
||||
os.makedirs(images_dir, exist_ok=True)
|
||||
filename = f"{uuid.uuid4()}_{file.name}"
|
||||
abs_path = os.path.join(images_dir, filename)
|
||||
|
||||
with open(abs_path, "wb") as dst:
|
||||
for chunk in file.chunks():
|
||||
dst.write(chunk)
|
||||
|
||||
try:
|
||||
data = ocr_and_extract_info(abs_path)
|
||||
if not data:
|
||||
return JsonResponse({"status": "error", "message": "无法识别图片内容"}, status=400)
|
||||
|
||||
rel_path = f"images/{filename}"
|
||||
image_url = request.build_absolute_uri(settings.MEDIA_URL + rel_path)
|
||||
return JsonResponse({
|
||||
"status": "success",
|
||||
"message": "识别成功,请确认数据后点击录入",
|
||||
"data": data,
|
||||
"image": rel_path,
|
||||
"image_url": image_url,
|
||||
})
|
||||
except Exception as e:
|
||||
return JsonResponse({"status": "error", "message": str(e)}, status=500)
|
||||
|
||||
|
||||
# 确认并入库
|
||||
@require_http_methods(["POST"])
|
||||
def confirm(request):
|
||||
if not request.session.get("user_id"):
|
||||
# 允许从payload中带入user_id作为后备(便于前端已知用户时继续操作)
|
||||
try:
|
||||
payload_for_uid = json.loads(request.body.decode("utf-8"))
|
||||
except Exception:
|
||||
payload_for_uid = {}
|
||||
fb_uid = (payload_for_uid or {}).get("user_id")
|
||||
if fb_uid:
|
||||
request.session["user_id"] = fb_uid
|
||||
request.session.setdefault("permission", 1)
|
||||
else:
|
||||
return JsonResponse({"status": "error", "message": "未登录"}, status=401)
|
||||
|
||||
try:
|
||||
payload = json.loads(request.body.decode("utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
return JsonResponse({"status": "error", "message": "JSON无效"}, status=400)
|
||||
|
||||
edited = payload.get("data") or {}
|
||||
image_rel = payload.get("image") or ""
|
||||
if not isinstance(edited, dict) or not edited:
|
||||
return JsonResponse({"status": "error", "message": "数据不能为空"}, status=400)
|
||||
|
||||
to_store = {
|
||||
"writer_id": str(request.session.get("user_id")),
|
||||
"data": json_to_string(edited),
|
||||
"image": image_rel,
|
||||
}
|
||||
|
||||
ok = insert_data(to_store)
|
||||
if not ok:
|
||||
return JsonResponse({"status": "error", "message": "写入ES失败"}, status=500)
|
||||
|
||||
return JsonResponse({"status": "success", "message": "数据录入成功", "data": edited})
|
||||
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
@ensure_csrf_cookie
|
||||
def manage_page(request):
|
||||
session_user_id = request.session.get("user_id")
|
||||
if session_user_id is None:
|
||||
from django.shortcuts import redirect
|
||||
return redirect("/accounts/login/")
|
||||
is_admin = (request.session.get("permission", 1) == 0)
|
||||
raw_results = search_all()
|
||||
if not is_admin:
|
||||
uid = str(session_user_id)
|
||||
raw_results = [r for r in raw_results if str(r.get("writer_id", "")) == uid]
|
||||
# 规范化键,避免模板点号访问下划线前缀字段
|
||||
results = []
|
||||
for r in raw_results:
|
||||
results.append({
|
||||
"id": r.get("_id", ""),
|
||||
"writer_id": r.get("writer_id", ""),
|
||||
"image": r.get("image", ""),
|
||||
"data": r.get("data", ""),
|
||||
})
|
||||
user_id_qs = request.GET.get("user_id")
|
||||
context = {"items": results, "user_id": user_id_qs or session_user_id}
|
||||
return render(request, "elastic/manage.html", context)
|
||||
@@ -1,100 +0,0 @@
|
||||
import json
|
||||
|
||||
|
||||
def json_to_string(json_data):
|
||||
"""
|
||||
将JSON数据转换为使用指定分隔符的字符串
|
||||
使用 |###| 作为键值对分隔符
|
||||
使用 |##| 作为列表元素分隔符
|
||||
|
||||
Args:
|
||||
json_data (dict): 要转换的JSON数据
|
||||
|
||||
Returns:
|
||||
str: 转换后的字符串
|
||||
"""
|
||||
if not isinstance(json_data, dict):
|
||||
raise ValueError("输入必须是字典类型")
|
||||
|
||||
result_parts = []
|
||||
|
||||
for key, value in json_data.items():
|
||||
if isinstance(value, list):
|
||||
# 处理列表:使用 |##| 分隔列表元素
|
||||
list_str = "|##|".join(str(item) for item in value)
|
||||
result_parts.append(f"{key}:[{list_str}]")
|
||||
else:
|
||||
# 处理普通值
|
||||
result_parts.append(f"{key}:{value}")
|
||||
|
||||
# 使用 |###| 分隔键值对
|
||||
return "|###|".join(result_parts)
|
||||
|
||||
|
||||
def string_to_json(data_string):
|
||||
"""
|
||||
将使用指定分隔符的字符串转换回JSON格式
|
||||
解析使用 |###| 分隔的键值对
|
||||
解析使用 |##| 分隔的列表元素
|
||||
|
||||
Args:
|
||||
data_string (str): 要转换的字符串
|
||||
|
||||
Returns:
|
||||
dict: 转换后的JSON数据
|
||||
"""
|
||||
if not isinstance(data_string, str):
|
||||
raise ValueError("输入必须是字符串类型")
|
||||
|
||||
if not data_string.strip():
|
||||
return {}
|
||||
|
||||
result = {}
|
||||
|
||||
# 使用 |###| 分割键值对
|
||||
pairs = data_string.split("|###|")
|
||||
|
||||
for pair in pairs:
|
||||
if ":" not in pair:
|
||||
continue
|
||||
|
||||
# 分割键和值
|
||||
key, value = pair.split(":", 1)
|
||||
key = key.strip()
|
||||
value = value.strip()
|
||||
|
||||
# 检查是否是列表格式 [...]
|
||||
if value.startswith("[") and value.endswith("]"):
|
||||
# 处理列表
|
||||
list_content = value[1:-1] # 去掉方括号
|
||||
if list_content:
|
||||
# 使用 |##| 分割列表元素
|
||||
items = list_content.split("|##|")
|
||||
# 尝试转换为适当的数据类型
|
||||
converted_items = []
|
||||
for item in items:
|
||||
item = item.strip()
|
||||
# 尝试转换为数字
|
||||
try:
|
||||
if "." in item:
|
||||
converted_items.append(float(item))
|
||||
else:
|
||||
converted_items.append(int(item))
|
||||
except ValueError:
|
||||
# 如果不是数字,保持为字符串
|
||||
converted_items.append(item)
|
||||
result[key] = converted_items
|
||||
else:
|
||||
result[key] = []
|
||||
else:
|
||||
# 处理普通值,尝试转换为适当的数据类型
|
||||
try:
|
||||
if "." in value:
|
||||
result[key] = float(value)
|
||||
else:
|
||||
result[key] = int(value)
|
||||
except ValueError:
|
||||
# 如果不是数字,保持为字符串
|
||||
result[key] = value
|
||||
|
||||
return result
|
||||
1
main/__init__.py
Normal file
1
main/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""Main app for home page (login required)."""
|
||||
6
main/apps.py
Normal file
6
main/apps.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class MainConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'main'
|
||||
72
main/templates/main/home.html
Normal file
72
main/templates/main/home.html
Normal file
@@ -0,0 +1,72 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>主页</title>
|
||||
<style>
|
||||
body { font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif; background: #fafafa; }
|
||||
.container { max-width: 720px; margin: 8vh auto; padding: 24px; }
|
||||
.card { background: #fff; border-radius: 10px; box-shadow: 0 6px 18px rgba(0,0,0,0.06); padding: 24px; }
|
||||
</style>
|
||||
{% csrf_token %}
|
||||
<!-- CSRF token to assist logout POST via cookie/header -->
|
||||
</head>
|
||||
<body>
|
||||
<div class="container" style="display:flex; gap:16px;">
|
||||
<aside style="width:220px; background:#fff; border-radius:10px; box-shadow: 0 6px 18px rgba(0,0,0,0.06); padding:16px; height: fit-content;">
|
||||
<h3 style="margin-top:0; font-size:16px;">导航</h3>
|
||||
<nav>
|
||||
<ul style="list-style:none; padding-left:0; line-height:1.9;">
|
||||
<li><a href="/" style="text-decoration:none; color:#1677ff;">主页</a></li>
|
||||
<li><a href="/elastic/upload-page/" style="text-decoration:none; color:#1677ff;">图片上传与识别</a></li>
|
||||
<li><a href="/elastic/manage/" style="text-decoration:none; color:#1677ff;">数据管理(管理员)</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
<hr/>
|
||||
<button id="logoutBtn" style="padding:8px 12px; width:100%; background:#ff4d4f; color:#fff; border:none; border-radius:6px; cursor:pointer;">退出登录</button>
|
||||
<div id="logoutMsg" class="muted" style="margin-top:8px;"></div>
|
||||
</aside>
|
||||
|
||||
<div class="card" style="flex:1;">
|
||||
<h2>主页(留白)</h2>
|
||||
<p>用户ID:{{ user_id }}</p>
|
||||
<p>这里留白即可,主页不由当前实现负责。</p>
|
||||
<p class="muted">提示:已使用安全的会话 Cookie 管理登录状态。</p>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function getCookie(name) {
|
||||
const value = `; ${document.cookie}`;
|
||||
const parts = value.split(`; ${name}=`);
|
||||
if (parts.length === 2) return parts.pop().split(';').shift();
|
||||
}
|
||||
document.getElementById('logoutBtn').addEventListener('click', async () => {
|
||||
const msg = document.getElementById('logoutMsg');
|
||||
msg.textContent = '';
|
||||
const csrftoken = getCookie('csrftoken');
|
||||
try {
|
||||
const resp = await fetch('/accounts/logout/', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRFToken': csrftoken || ''
|
||||
},
|
||||
body: JSON.stringify({})
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (!resp.ok || !data.ok) {
|
||||
throw new Error('登出失败');
|
||||
}
|
||||
document.cookie = 'sessionid=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
|
||||
document.cookie = 'csrftoken=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
|
||||
window.location.href = data.redirect_url;
|
||||
} catch (e) {
|
||||
msg.textContent = e.message || '发生错误';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
9
main/urls.py
Normal file
9
main/urls.py
Normal file
@@ -0,0 +1,9 @@
|
||||
from django.urls import path
|
||||
from . import views
|
||||
|
||||
|
||||
app_name = "main"
|
||||
|
||||
urlpatterns = [
|
||||
path("home/", views.home, name="home"),
|
||||
]
|
||||
17
main/views.py
Normal file
17
main/views.py
Normal file
@@ -0,0 +1,17 @@
|
||||
from django.shortcuts import render, redirect
|
||||
from django.views.decorators.http import require_http_methods
|
||||
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
def home(request):
|
||||
# Enforce login: require session user_id
|
||||
session_user_id = request.session.get("user_id")
|
||||
if session_user_id is None:
|
||||
return redirect("/accounts/login/")
|
||||
|
||||
# Show user_id (prefer query param if present, but don't trust it)
|
||||
user_id_qs = request.GET.get("user_id")
|
||||
context = {
|
||||
"user_id": user_id_qs or session_user_id,
|
||||
}
|
||||
return render(request, "main/home.html", context)
|
||||
22
manage.py
Normal file
22
manage.py
Normal file
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env python
|
||||
"""Django's command-line utility for administrative tasks."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
"""Run administrative tasks."""
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Achievement_Inputing.settings')
|
||||
try:
|
||||
from django.core.management import execute_from_command_line
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"Couldn't import Django. Are you sure it's installed and "
|
||||
"available on your PYTHONPATH environment variable? Did you "
|
||||
"forget to activate a virtual environment?"
|
||||
) from exc
|
||||
execute_from_command_line(sys.argv)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,6 +1,6 @@
|
||||
flask==3.1.1
|
||||
pillow==11.1.0
|
||||
openai==1.88.0
|
||||
elasticsearch==7.17.0
|
||||
pandas==2.2.3
|
||||
requests
|
||||
Django==5.2.8
|
||||
elasticsearch==8.17.1
|
||||
django-elasticsearch-dsl==7.3.0
|
||||
requests==2.32.3
|
||||
openai==1.52.2
|
||||
Pillow==10.4.0
|
||||
|
||||
@@ -1,414 +0,0 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}数据操作 - 紫金·稷下薪火·云枢智海师生成果共创系统{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<style>
|
||||
/* 基础样式重置 */
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
|
||||
/* 容器样式 - 调整为靠左靠上 */
|
||||
.container {
|
||||
max-width: 1200px;
|
||||
margin: 0; /* 移除自动居中 */
|
||||
padding: 20px 0 0 20px; /* 顶部和左侧留白 */
|
||||
}
|
||||
|
||||
/* 标题样式 - 减少底部边距 */
|
||||
h2 {
|
||||
color: #2c3e50;
|
||||
border-bottom: 2px solid #3498db;
|
||||
padding-bottom: 8px;
|
||||
margin-bottom: 15px; /* 减少间距 */
|
||||
}
|
||||
|
||||
/* 描述文字样式 */
|
||||
p {
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
/* 卡片容器样式 */
|
||||
.data-cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
|
||||
gap: 20px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
/* 卡片样式 */
|
||||
.data-card {
|
||||
background-color: white;
|
||||
border-radius: 8px;
|
||||
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 {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
|
||||
}
|
||||
|
||||
/* 卡片头部样式 */
|
||||
.card-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 15px;
|
||||
padding-bottom: 15px;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.card-header h3 {
|
||||
margin: 0;
|
||||
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;
|
||||
color: #333;
|
||||
min-width: 120px;
|
||||
margin-right: 10px;
|
||||
}
|
||||
|
||||
.field-value {
|
||||
color: #666;
|
||||
flex: 1;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
/* 卡片图片样式 */
|
||||
.card-image {
|
||||
text-align: center;
|
||||
margin-top: 15px;
|
||||
padding-top: 15px;
|
||||
border-top: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.card-image img {
|
||||
max-width: 100%;
|
||||
max-height: 200px;
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
/* 操作按钮样式 */
|
||||
.action-button {
|
||||
padding: 6px 16px;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-weight: 500;
|
||||
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 {
|
||||
background: linear-gradient(to right, #ff416c, #ff4b2b);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.delete-btn:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 8px rgba(255, 75, 43, 0.3);
|
||||
}
|
||||
|
||||
/* 返回按钮样式 */
|
||||
.back-btn {
|
||||
display: inline-block;
|
||||
padding: 10px 20px;
|
||||
background: linear-gradient(to right, #0066cc, #003399);
|
||||
color: white;
|
||||
text-decoration: none;
|
||||
border-radius: 6px;
|
||||
margin-top: 15px; /* 减少顶部间距 */
|
||||
margin-left: 20px; /* 左侧对齐 */
|
||||
transition: transform 0.3s;
|
||||
}
|
||||
|
||||
.back-btn:hover {
|
||||
transform: translateY(-3px);
|
||||
box-shadow: 0 5px 15px rgba(0, 102, 204, 0.4);
|
||||
}
|
||||
|
||||
/* 空数据提示 */
|
||||
.no-data {
|
||||
text-align: center;
|
||||
padding: 40px 0;
|
||||
color: #a0aec0;
|
||||
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>
|
||||
|
||||
<div class="container">
|
||||
<h2>所有已录入的奖项信息</h2>
|
||||
<p>在此页面可以查看所有已录入的成果信息,并进行编辑和删除操作</p>
|
||||
|
||||
<!-- 批量操作区域 -->
|
||||
<div class="batch-operations" style="margin-bottom: 20px; padding: 15px; background-color: #f8f9fa; border-radius: 8px; border: 1px solid #e0e0e0;">
|
||||
<div style="display: flex; align-items: center; gap: 15px;">
|
||||
<div style="display: flex; align-items: center; gap: 8px;">
|
||||
<input type="checkbox" id="select-all" onchange="toggleSelectAll(this.checked)">
|
||||
<label for="select-all" style="font-weight: 600; color: #333;">全选</label>
|
||||
</div>
|
||||
<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;">
|
||||
批量删除选中项
|
||||
</button>
|
||||
<span id="selected-count" style="color: #666; font-size: 14px;">已选择 0 项</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="data-cards">
|
||||
{% if data %}
|
||||
{% for item in data %}
|
||||
<div class="data-card">
|
||||
<div class="card-header">
|
||||
<div style="display: flex; align-items: center; gap: 15px;">
|
||||
<input type="checkbox" class="doc-checkbox" value="{{ item._id }}" onchange="updateSelectedCount()">
|
||||
<h3>记录 {{ loop.index }}</h3>
|
||||
</div>
|
||||
<div class="card-actions">
|
||||
<a href="{{ url_for('edit_entry', doc_id=item._id) }}" class="action-button edit-btn">编辑</a>
|
||||
<button type="button" class="action-button delete-btn" onclick="deleteRecord('{{ item._id }}')">删除</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card-content">
|
||||
{% if item.data %}
|
||||
{# 从原始数据中解析字段 #}
|
||||
{% 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>
|
||||
|
||||
<a href="{{ url_for('index') }}" class="back-btn">返回首页</a>
|
||||
</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 %}
|
||||
@@ -1,275 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{% block title %}紫金·稷下薪火·云枢智海师生成果共创系统{% endblock %}</title>
|
||||
<style>
|
||||
:root {
|
||||
--primary: #4361ee;
|
||||
--primary-light: #4895ef;
|
||||
--secondary: #3f37c9;
|
||||
--accent: #f72585;
|
||||
--light: #f8f9fa;
|
||||
--dark: #212529;
|
||||
--success: #4cc9f0;
|
||||
--warning: #fcaa18;
|
||||
--radius: 8px;
|
||||
--shadow: 0 4px 12px rgba(0,0,0,0.1);
|
||||
--transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background-color: #f5f7fb;
|
||||
color: #333;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.header {
|
||||
background: linear-gradient(135deg, var(--primary), var(--secondary));
|
||||
color: white;
|
||||
padding: 15px 20px;
|
||||
box-shadow: var(--shadow);
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.header:before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: -50%;
|
||||
left: -50%;
|
||||
width: 200%;
|
||||
height: 200%;
|
||||
background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 60%);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
font-size: 24px;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.header h1 span {
|
||||
color: #ffcc00;
|
||||
text-shadow: 0 0 5px rgba(0,0,0,0.2);
|
||||
}
|
||||
|
||||
.user-info {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
.user-info .username {
|
||||
font-size: 14px;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.user-info .permission-badge {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
padding: 4px 8px;
|
||||
border-radius: 12px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.user-info .permission-badge.admin {
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
.user-info .permission-badge.user {
|
||||
background: var(--success);
|
||||
}
|
||||
|
||||
.logout-btn {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border: 1px solid rgba(255, 255, 255, 0.3);
|
||||
color: white;
|
||||
padding: 6px 12px;
|
||||
border-radius: 4px;
|
||||
text-decoration: none;
|
||||
font-size: 12px;
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.logout-btn:hover {
|
||||
background: rgba(255, 255, 255, 0.3);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
width: 240px;
|
||||
height: calc(100vh - 60px);
|
||||
float: left;
|
||||
background: linear-gradient(to bottom, #ffffff, #f5f7fb);
|
||||
padding: 20px 0;
|
||||
box-shadow: 2px 0 10px rgba(0,0,0,0.05);
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.sidebar a {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 15px 25px;
|
||||
text-decoration: none;
|
||||
color: var(--dark);
|
||||
font-size: 16px;
|
||||
transition: var(--transition);
|
||||
border-left: 3px solid transparent;
|
||||
}
|
||||
|
||||
.sidebar a:hover {
|
||||
background-color: rgba(67, 97, 238, 0.08);
|
||||
border-left-color: var(--primary);
|
||||
}
|
||||
|
||||
.sidebar a.active {
|
||||
background-color: rgba(67, 97, 238, 0.15);
|
||||
border-left-color: var(--primary);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.sidebar a i {
|
||||
margin-right: 12px;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.content {
|
||||
margin-left: 240px;
|
||||
padding: 30px;
|
||||
background-color: white;
|
||||
min-height: calc(100vh - 60px);
|
||||
box-shadow: -2px 0 10px rgba(0,0,0,0.05);
|
||||
}
|
||||
|
||||
.card {
|
||||
background: white;
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow);
|
||||
padding: 25px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.sidebar {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
display: flex;
|
||||
justify-content: space-around;
|
||||
padding: 10px 0;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
.sidebar a {
|
||||
padding: 12px 15px;
|
||||
border-left: none;
|
||||
text-align: center;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.sidebar a i {
|
||||
display: block;
|
||||
margin-right: 0;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.content {
|
||||
margin-left: 0;
|
||||
padding: 20px 15px;
|
||||
min-height: calc(100vh - 110px);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="header">
|
||||
<h1><span>紫金</span> 稷下薪火·云枢智海师生成果共创系统</h1>
|
||||
<div class="user-info">
|
||||
<span class="username">{{ session.username }}</span>
|
||||
{% if session.permission == 0 %}
|
||||
<span class="permission-badge admin">管理员</span>
|
||||
{% elif session.permission == 1 %}
|
||||
<span class="permission-badge user">普通用户</span>
|
||||
{% endif %}
|
||||
<a href="{{ url_for('logout') }}" class="logout-btn">登出</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sidebar">
|
||||
<a href="{{ url_for('index') }}" {% if request.endpoint == 'index' %}class="active"{% endif %}>
|
||||
<i>📊</i> 录入成果
|
||||
</a>
|
||||
<a href="{{ url_for('results_page') }}" {% if request.endpoint == 'results_page' %}class="active"{% endif %}>
|
||||
<i>📈</i> 查询统计
|
||||
</a>
|
||||
<a href="{{ url_for('my_data') }}" {% if request.endpoint == 'my_data' or request.endpoint == 'edit_entry' %}class="active"{% endif %}>
|
||||
<i>📋</i> 我的数据
|
||||
</a>
|
||||
{% if session.permission == 0 %}
|
||||
<a href="{{ url_for('show_all') }}" {% if request.endpoint == 'show_all' %}class="active"{% endif %}>
|
||||
<i>📁</i> 数据操作
|
||||
</a>
|
||||
{% endif %}
|
||||
<a href="{{ url_for('profile') }}" {% if request.endpoint == 'profile' %}class="active"{% endif %}>
|
||||
<i>⚙️</i> 个人设置
|
||||
</a>
|
||||
{% if session.permission == 0 %}
|
||||
<a href="{{ url_for('user_management') }}" {% if request.endpoint == 'user_management' or request.endpoint == 'register' %}class="active"{% endif %}>
|
||||
<i>👥</i> 用户管理
|
||||
</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<!-- Flash消息显示 -->
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
<div class="flash-messages" style="margin-bottom: 20px;">
|
||||
{% for category, message in messages %}
|
||||
<div class="flash-message {{ category }}" style="padding: 10px; border-radius: 5px; margin-bottom: 10px;">{{ message }}</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<style>
|
||||
.flash-message.error {
|
||||
background-color: #f8d7da;
|
||||
color: #721c24;
|
||||
border: 1px solid #f5c6cb;
|
||||
}
|
||||
.flash-message.success {
|
||||
background-color: #d4edda;
|
||||
color: #155724;
|
||||
border: 1px solid #c3e6cb;
|
||||
}
|
||||
.flash-message.info {
|
||||
background-color: #d1ecf1;
|
||||
color: #0c5460;
|
||||
border: 1px solid #bee5eb;
|
||||
}
|
||||
</style>
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
{% block content %}
|
||||
{% endblock %}
|
||||
</div>
|
||||
|
||||
<!-- 添加字体图标库 -->
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,316 +0,0 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}编辑数据{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="edit-container">
|
||||
<div class="edit-header">
|
||||
<h1>编辑数据</h1>
|
||||
<p>修改您的数据信息</p>
|
||||
</div>
|
||||
|
||||
<form method="POST" class="edit-form" id="editForm">
|
||||
<!-- 隐藏字段 -->
|
||||
<input type="hidden" name="_id" value="{{ data._id }}">
|
||||
<input type="hidden" name="image" value="{{ data.image }}">
|
||||
|
||||
<!-- 图片显示 -->
|
||||
{% if data.image %}
|
||||
<div class="image-preview">
|
||||
<h3>关联图片</h3>
|
||||
<img src="{{ url_for('serve_image', filename=data.image) }}" alt="数据图片" onclick="openImageModal('{{ url_for('serve_image', filename=data.image) }}')">
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<!-- 数据字段编辑 -->
|
||||
<div class="fields-container">
|
||||
<h3>数据字段</h3>
|
||||
{% for key, value in data.items() %}
|
||||
{% if key not in ['_id', 'image', 'user_id'] %}
|
||||
<div class="form-group">
|
||||
<label for="{{ key }}">{{ key }}:</label>
|
||||
<input type="text" id="{{ key }}" name="{{ key }}" value="{{ value }}" class="form-input">
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
<!-- 操作按钮 -->
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="btn btn-primary">
|
||||
<i class="icon">💾</i>
|
||||
保存修改
|
||||
</button>
|
||||
<a href="{{ url_for('my_data') }}" class="btn btn-secondary">
|
||||
<i class="icon">↩️</i>
|
||||
取消
|
||||
</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- 图片预览模态框 -->
|
||||
<div id="imageModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<span class="close" onclick="closeImageModal()">×</span>
|
||||
<img id="modalImage" src="" alt="图片预览">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.edit-container {
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.edit-header {
|
||||
text-align: center;
|
||||
margin-bottom: 30px;
|
||||
padding: 30px;
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.edit-header h1 {
|
||||
color: #333;
|
||||
font-size: 28px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.edit-header p {
|
||||
color: #666;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.edit-form {
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
padding: 30px;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.image-preview {
|
||||
margin-bottom: 30px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.image-preview h3 {
|
||||
color: #333;
|
||||
margin-bottom: 15px;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.image-preview img {
|
||||
max-width: 100%;
|
||||
max-height: 300px;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
transition: transform 0.3s ease;
|
||||
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.image-preview img:hover {
|
||||
transform: scale(1.02);
|
||||
}
|
||||
|
||||
.fields-container {
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.fields-container h3 {
|
||||
color: #333;
|
||||
margin-bottom: 20px;
|
||||
font-size: 18px;
|
||||
padding-bottom: 10px;
|
||||
border-bottom: 2px solid #e9ecef;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
margin-bottom: 8px;
|
||||
color: #555;
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
text-transform: capitalize;
|
||||
}
|
||||
|
||||
.form-input {
|
||||
width: 100%;
|
||||
padding: 12px 16px;
|
||||
border: 2px solid #e9ecef;
|
||||
border-radius: 8px;
|
||||
font-size: 16px;
|
||||
transition: all 0.3s ease;
|
||||
background: #f8f9fa;
|
||||
}
|
||||
|
||||
.form-input:focus {
|
||||
outline: none;
|
||||
border-color: #667eea;
|
||||
background: white;
|
||||
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
display: flex;
|
||||
gap: 15px;
|
||||
justify-content: center;
|
||||
padding-top: 20px;
|
||||
border-top: 1px solid #e9ecef;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 12px 24px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
transition: all 0.3s ease;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: #6c757d;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: #5a6268;
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
/* 模态框样式 */
|
||||
.modal {
|
||||
display: none;
|
||||
position: fixed;
|
||||
z-index: 1000;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0, 0, 0, 0.8);
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
position: relative;
|
||||
margin: 5% auto;
|
||||
padding: 20px;
|
||||
width: 90%;
|
||||
max-width: 800px;
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.close {
|
||||
position: absolute;
|
||||
top: 15px;
|
||||
right: 25px;
|
||||
font-size: 28px;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.close:hover {
|
||||
color: #333;
|
||||
}
|
||||
|
||||
#modalImage {
|
||||
max-width: 100%;
|
||||
max-height: 70vh;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.edit-container {
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.edit-form {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.btn {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
// 图片预览功能
|
||||
function openImageModal(imageSrc) {
|
||||
document.getElementById('modalImage').src = imageSrc;
|
||||
document.getElementById('imageModal').style.display = 'block';
|
||||
}
|
||||
|
||||
function closeImageModal() {
|
||||
document.getElementById('imageModal').style.display = 'none';
|
||||
}
|
||||
|
||||
// 点击模态框外部关闭
|
||||
window.onclick = function(event) {
|
||||
const imageModal = document.getElementById('imageModal');
|
||||
if (event.target === imageModal) {
|
||||
closeImageModal();
|
||||
}
|
||||
}
|
||||
|
||||
// 表单验证
|
||||
document.getElementById('editForm').addEventListener('submit', function(e) {
|
||||
const inputs = this.querySelectorAll('.form-input');
|
||||
let hasEmptyFields = false;
|
||||
|
||||
inputs.forEach(input => {
|
||||
if (!input.value.trim()) {
|
||||
hasEmptyFields = true;
|
||||
input.style.borderColor = '#dc3545';
|
||||
} else {
|
||||
input.style.borderColor = '#e9ecef';
|
||||
}
|
||||
});
|
||||
|
||||
if (hasEmptyFields) {
|
||||
e.preventDefault();
|
||||
alert('请填写所有字段!');
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
// 输入时清除错误状态
|
||||
document.querySelectorAll('.form-input').forEach(input => {
|
||||
input.addEventListener('input', function() {
|
||||
if (this.value.trim()) {
|
||||
this.style.borderColor = '#e9ecef';
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -1,256 +0,0 @@
|
||||
{% 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 %}
|
||||
@@ -1,617 +0,0 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}录入成果 - 紫金·稷下薪火·云枢智海师生成果共创系统{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="card">
|
||||
<h2 style="color: var(--primary); border-bottom: 2px solid var(--primary); padding-bottom: 10px;">
|
||||
<i class="fas fa-cloud-upload-alt"></i> 成果录入
|
||||
</h2>
|
||||
<p class="mb-4">请上传包含成果信息的图片(如获奖证书、论文封面等),系统将自动识别关键信息</p>
|
||||
|
||||
<form id="upload-form" enctype="multipart/form-data" class="mb-4">
|
||||
<div class="mb-3">
|
||||
<label for="file" class="form-label">选择图片文件</label>
|
||||
<input type="file" name="file" accept="image/*" id="file" class="form-control" required>
|
||||
<div class="form-text">支持JPG、PNG、GIF等格式,文件大小不超过10MB</div>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary btn-lg">
|
||||
<i class="fas fa-upload"></i> 上传图片
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<!-- 编辑确认区域 -->
|
||||
<div id="edit-section" class="mt-4" style="display: none;">
|
||||
<div class="card">
|
||||
<h3 style="color: var(--primary); border-bottom: 2px solid var(--primary); padding-bottom: 10px;">
|
||||
<i class="fas fa-edit"></i> 识别结果 - 请确认并编辑数据
|
||||
</h3>
|
||||
<p class="mb-4">系统已识别出以下信息,您可以修改字段名和对应的数据值,确认无误后点击录入按钮</p>
|
||||
|
||||
<form id="edit-form">
|
||||
<div id="edit-fields"></div>
|
||||
<div class="mt-4 text-center">
|
||||
<button type="button" id="confirm-btn" class="btn btn-success btn-lg">
|
||||
<i class="fas fa-check"></i> 确认录入
|
||||
</button>
|
||||
<button type="button" id="cancel-btn" class="btn btn-secondary btn-lg ml-3">
|
||||
<i class="fas fa-times"></i> 取消
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let currentData = null;
|
||||
let currentImage = null;
|
||||
|
||||
document.getElementById("upload-form").addEventListener("submit", function (e) {
|
||||
e.preventDefault();
|
||||
let formData = new FormData(this);
|
||||
const editSection = document.getElementById("edit-section");
|
||||
|
||||
// 显示上传进度动画
|
||||
editSection.innerHTML = `
|
||||
<div class="card">
|
||||
<div class="progress-container">
|
||||
<div class="progress-bar"></div>
|
||||
<p class="progress-text">正在处理图片,请稍候...</p>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
editSection.style.display = "block";
|
||||
|
||||
fetch("/upload", { method: "POST", body: formData })
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
if(data.error) {
|
||||
editSection.innerHTML = `
|
||||
<div class="card">
|
||||
<div class="alert alert-danger">
|
||||
<i class="fas fa-exclamation-circle"></i> 错误: ${data.error}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else {
|
||||
// 存储当前数据
|
||||
currentData = data.data;
|
||||
currentImage = data.image;
|
||||
|
||||
// 生成编辑表单
|
||||
generateEditForm(data.data);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
editSection.innerHTML = `
|
||||
<div class="card">
|
||||
<div class="alert alert-danger">
|
||||
<i class="fas fa-exclamation-circle"></i> 上传失败: ${error}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
});
|
||||
|
||||
function generateEditForm(data) {
|
||||
const editSection = document.getElementById("edit-section");
|
||||
let fieldsHtml = "";
|
||||
|
||||
Object.entries(data).forEach(([key, value], index) => {
|
||||
fieldsHtml += `
|
||||
<div class="field-row mb-3">
|
||||
<div class="row">
|
||||
<div class="col-md-4">
|
||||
<label class="form-label">字段名</label>
|
||||
<input type="text" class="form-control field-name" value="${key}" data-original-key="${key}">
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">数据值</label>
|
||||
<input type="text" class="form-control field-value" value="${value}">
|
||||
</div>
|
||||
<div class="col-md-2 d-flex align-items-end">
|
||||
<button type="button" class="btn btn-danger btn-sm delete-field" title="删除此字段">
|
||||
<i class="fas fa-trash"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
|
||||
editSection.innerHTML = `
|
||||
<div class="card">
|
||||
<h3 style="color: var(--primary); border-bottom: 2px solid var(--primary); padding-bottom: 10px;">
|
||||
<i class="fas fa-edit"></i> 识别结果 - 请确认并编辑数据
|
||||
</h3>
|
||||
<p class="mb-4">系统已识别出以下信息,您可以修改字段名和对应的数据值,确认无误后点击录入按钮</p>
|
||||
|
||||
<form id="edit-form">
|
||||
<div id="edit-fields">
|
||||
${fieldsHtml}
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<button type="button" id="add-field-btn" class="btn btn-outline-primary">
|
||||
<i class="fas fa-plus"></i> 添加字段
|
||||
</button>
|
||||
</div>
|
||||
<div class="mt-4 text-center">
|
||||
<button type="button" id="confirm-btn" class="btn btn-success btn-lg">
|
||||
<i class="fas fa-check"></i> 确认录入
|
||||
</button>
|
||||
<button type="button" id="cancel-btn" class="btn btn-secondary btn-lg ml-3">
|
||||
<i class="fas fa-times"></i> 取消
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// 绑定删除按钮事件
|
||||
document.querySelectorAll('.delete-field').forEach(btn => {
|
||||
btn.addEventListener('click', function() {
|
||||
this.closest('.field-row').remove();
|
||||
});
|
||||
});
|
||||
|
||||
// 绑定添加字段按钮事件
|
||||
document.getElementById('add-field-btn').addEventListener('click', function() {
|
||||
const editFields = document.getElementById('edit-fields');
|
||||
const newFieldHtml = `
|
||||
<div class="field-row mb-3">
|
||||
<div class="row">
|
||||
<div class="col-md-4">
|
||||
<label class="form-label">字段名</label>
|
||||
<input type="text" class="form-control field-name" value="" data-original-key="">
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">数据值</label>
|
||||
<input type="text" class="form-control field-value" value="">
|
||||
</div>
|
||||
<div class="col-md-2 d-flex align-items-end">
|
||||
<button type="button" class="btn btn-danger btn-sm delete-field" title="删除此字段">
|
||||
<i class="fas fa-trash"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
editFields.insertAdjacentHTML('beforeend', newFieldHtml);
|
||||
|
||||
// 为新添加的删除按钮绑定事件
|
||||
const newDeleteBtn = editFields.lastElementChild.querySelector('.delete-field');
|
||||
newDeleteBtn.addEventListener('click', function() {
|
||||
this.closest('.field-row').remove();
|
||||
});
|
||||
});
|
||||
|
||||
// 绑定确认和取消按钮事件
|
||||
bindConfirmCancelEvents();
|
||||
}
|
||||
|
||||
function bindConfirmCancelEvents() {
|
||||
// 确认录入按钮事件
|
||||
document.getElementById("confirm-btn").addEventListener("click", function() {
|
||||
const fieldRows = document.querySelectorAll('.field-row');
|
||||
const editedData = {};
|
||||
|
||||
// 收集编辑后的数据
|
||||
fieldRows.forEach(row => {
|
||||
const fieldName = row.querySelector('.field-name').value.trim();
|
||||
const fieldValue = row.querySelector('.field-value').value.trim();
|
||||
if (fieldName && fieldValue) {
|
||||
editedData[fieldName] = fieldValue;
|
||||
}
|
||||
});
|
||||
|
||||
if (Object.keys(editedData).length === 0) {
|
||||
alert('请至少保留一个有效的字段!');
|
||||
return;
|
||||
}
|
||||
|
||||
// 发送确认请求
|
||||
fetch("/confirm", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({
|
||||
data: editedData,
|
||||
image: currentImage
|
||||
})
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
const editSection = document.getElementById("edit-section");
|
||||
|
||||
if(data.error) {
|
||||
editSection.innerHTML = `
|
||||
<div class="card">
|
||||
<div class="alert alert-danger">
|
||||
<i class="fas fa-exclamation-circle"></i> 录入失败: ${data.error}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else {
|
||||
editSection.innerHTML = `
|
||||
<div class="card">
|
||||
<div class="alert alert-success">
|
||||
<i class="fas fa-check-circle"></i> ${data.message}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
// 重置表单
|
||||
document.getElementById("upload-form").reset();
|
||||
// 3秒后隐藏成功消息
|
||||
setTimeout(() => {
|
||||
editSection.style.display = "none";
|
||||
}, 3000);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
const editSection = document.getElementById("edit-section");
|
||||
editSection.innerHTML = `
|
||||
<div class="card">
|
||||
<div class="alert alert-danger">
|
||||
<i class="fas fa-exclamation-circle"></i> 录入失败: ${error}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
});
|
||||
|
||||
// 取消按钮事件
|
||||
document.getElementById("cancel-btn").addEventListener("click", function() {
|
||||
const editSection = document.getElementById("edit-section");
|
||||
editSection.style.display = "none";
|
||||
currentData = null;
|
||||
currentImage = null;
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.btn-primary {
|
||||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||||
border: none;
|
||||
border-radius: 30px;
|
||||
padding: 12px 24px;
|
||||
font-weight: 500;
|
||||
transition: var(--transition);
|
||||
box-shadow: 0 4px 8px rgba(67, 97, 238, 0.2);
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background: linear-gradient(135deg, var(--primary-light), var(--primary));
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 12px rgba(67, 97, 238, 0.3);
|
||||
}
|
||||
|
||||
.form-control {
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 8px;
|
||||
font-size: 16px;
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.form-control:hover {
|
||||
border-color: var(--primary);
|
||||
}
|
||||
|
||||
.progress-container {
|
||||
background-color: #f8f9fa;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
width: 100%;
|
||||
height: 8px;
|
||||
background-color: #e9ecef;
|
||||
border-radius: 4px;
|
||||
margin-bottom: 15px;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.progress-bar::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: -100%;
|
||||
width: 80%;
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, transparent, #4cc9f0, transparent);
|
||||
animation: progress 1.5s infinite;
|
||||
}
|
||||
|
||||
@keyframes progress {
|
||||
0% { left: -100%; }
|
||||
100% { left: 200%; }
|
||||
}
|
||||
|
||||
.progress-text {
|
||||
color: #6c757d;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.alert {
|
||||
padding: 15px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.alert-danger {
|
||||
background-color: #ffe3e3;
|
||||
color: #d32f2f;
|
||||
border-left: 4px solid #d32f2f;
|
||||
}
|
||||
|
||||
.result-card {
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
box-shadow: var(--shadow);
|
||||
padding: 20px;
|
||||
border-left: 4px solid var(--success);
|
||||
}
|
||||
|
||||
.result-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding-bottom: 15px;
|
||||
border-bottom: 1px solid #eee;
|
||||
}
|
||||
|
||||
.result-header h3 {
|
||||
color: var(--success);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.timestamp {
|
||||
color: #6c757d;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.result-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 12px 0;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.result-label {
|
||||
font-weight: 500;
|
||||
color: #495057;
|
||||
}
|
||||
|
||||
.result-value {
|
||||
color: #333;
|
||||
max-width: 70%;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.result-footer {
|
||||
margin-top: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.success-message {
|
||||
color: var(--success);
|
||||
font-weight: 500;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.info-message {
|
||||
color: var(--primary);
|
||||
font-weight: 500;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.btn-outline-primary {
|
||||
border: 1px solid var(--primary);
|
||||
color: var(--primary);
|
||||
border-radius: 6px;
|
||||
padding: 8px 16px;
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.btn-outline-primary:hover {
|
||||
background-color: var(--primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-success {
|
||||
background: linear-gradient(135deg, #28a745, #20c997);
|
||||
border: none;
|
||||
border-radius: 30px;
|
||||
padding: 12px 24px;
|
||||
font-weight: 500;
|
||||
transition: var(--transition);
|
||||
box-shadow: 0 4px 8px rgba(40, 167, 69, 0.2);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-success:hover {
|
||||
background: linear-gradient(135deg, #20c997, #28a745);
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 12px rgba(40, 167, 69, 0.3);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: linear-gradient(135deg, #6c757d, #495057);
|
||||
border: none;
|
||||
border-radius: 30px;
|
||||
padding: 12px 24px;
|
||||
font-weight: 500;
|
||||
transition: var(--transition);
|
||||
box-shadow: 0 4px 8px rgba(108, 117, 125, 0.2);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: linear-gradient(135deg, #495057, #6c757d);
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 12px rgba(108, 117, 125, 0.3);
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background-color: #dc3545;
|
||||
border-color: #dc3545;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-danger:hover {
|
||||
background-color: #c82333;
|
||||
border-color: #bd2130;
|
||||
}
|
||||
|
||||
.btn-sm {
|
||||
padding: 0.25rem 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
border-radius: 0.2rem;
|
||||
}
|
||||
|
||||
.ml-3 {
|
||||
margin-left: 1rem;
|
||||
}
|
||||
|
||||
.btn-outline-primary {
|
||||
color: var(--primary);
|
||||
border-color: var(--primary);
|
||||
background-color: transparent;
|
||||
padding: 8px 16px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid var(--primary);
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.btn-outline-primary:hover {
|
||||
background-color: var(--primary);
|
||||
border-color: var(--primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.alert-danger {
|
||||
color: #721c24;
|
||||
background-color: #f8d7da;
|
||||
border-color: #f5c6cb;
|
||||
padding: 0.75rem 1.25rem;
|
||||
margin-bottom: 1rem;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 0.25rem;
|
||||
}
|
||||
|
||||
.alert-success {
|
||||
background-color: #d4edda;
|
||||
color: #155724;
|
||||
border-left: 4px solid #28a745;
|
||||
}
|
||||
|
||||
#edit-section .card {
|
||||
border-left: 4px solid var(--primary);
|
||||
}
|
||||
|
||||
.form-label {
|
||||
font-weight: 500;
|
||||
color: #495057;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.field-row {
|
||||
background-color: white;
|
||||
padding: 15px;
|
||||
border-radius: 5px;
|
||||
border: 1px solid #e0e0e0;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.field-row:hover {
|
||||
border-color: var(--primary);
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
margin-right: -15px;
|
||||
margin-left: -15px;
|
||||
}
|
||||
|
||||
.col-md-4, .col-md-6, .col-md-2 {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
padding-right: 15px;
|
||||
padding-left: 15px;
|
||||
}
|
||||
|
||||
.col-md-2 {
|
||||
flex: 0 0 16.666667%;
|
||||
max-width: 16.666667%;
|
||||
}
|
||||
|
||||
.col-md-4 {
|
||||
flex: 0 0 33.333333%;
|
||||
max-width: 33.333333%;
|
||||
}
|
||||
|
||||
.col-md-6 {
|
||||
flex: 0 0 50%;
|
||||
max-width: 50%;
|
||||
}
|
||||
|
||||
.d-flex {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.align-items-end {
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
.text-center {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.mb-3 {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.mb-4 {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.mt-4 {
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.btn-lg {
|
||||
padding: 0.5rem 1rem;
|
||||
font-size: 1.25rem;
|
||||
border-radius: 0.3rem;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.col-md-2, .col-md-4, .col-md-6 {
|
||||
flex: 0 0 100%;
|
||||
max-width: 100%;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.field-row .row {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.btn-lg {
|
||||
width: 100%;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.ml-3 {
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
@@ -1,162 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>用户登录 - 成果录入系统</title>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Microsoft YaHei', Arial, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.login-container {
|
||||
background: white;
|
||||
padding: 40px;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
}
|
||||
|
||||
.login-header {
|
||||
text-align: center;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.login-header h1 {
|
||||
color: #333;
|
||||
font-size: 28px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.login-header p {
|
||||
color: #666;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
margin-bottom: 5px;
|
||||
color: #333;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.form-group input {
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
border: 2px solid #ddd;
|
||||
border-radius: 5px;
|
||||
font-size: 16px;
|
||||
transition: border-color 0.3s;
|
||||
}
|
||||
|
||||
.form-group input:focus {
|
||||
outline: none;
|
||||
border-color: #667eea;
|
||||
}
|
||||
|
||||
.login-btn {
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
font-size: 16px;
|
||||
cursor: pointer;
|
||||
transition: transform 0.2s;
|
||||
}
|
||||
|
||||
.login-btn:hover {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.flash-messages {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.flash-message {
|
||||
padding: 10px;
|
||||
border-radius: 5px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.flash-message.error {
|
||||
background-color: #f8d7da;
|
||||
color: #721c24;
|
||||
border: 1px solid #f5c6cb;
|
||||
}
|
||||
|
||||
.flash-message.success {
|
||||
background-color: #d4edda;
|
||||
color: #155724;
|
||||
border: 1px solid #c3e6cb;
|
||||
}
|
||||
|
||||
.flash-message.info {
|
||||
background-color: #d1ecf1;
|
||||
color: #0c5460;
|
||||
border: 1px solid #bee5eb;
|
||||
}
|
||||
|
||||
.login-footer {
|
||||
text-align: center;
|
||||
margin-top: 20px;
|
||||
color: #666;
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="login-container">
|
||||
<div class="login-header">
|
||||
<h1>用户登录</h1>
|
||||
<p>成果录入系统</p>
|
||||
</div>
|
||||
|
||||
<!-- Flash消息显示 -->
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
<div class="flash-messages">
|
||||
{% for category, message in messages %}
|
||||
<div class="flash-message {{ category }}">{{ message }}</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
<form method="POST">
|
||||
<div class="form-group">
|
||||
<label for="username">用户名</label>
|
||||
<input type="text" id="username" name="username" required>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="password">密码</label>
|
||||
<input type="password" id="password" name="password" required>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="login-btn">登录</button>
|
||||
</form>
|
||||
|
||||
<div class="login-footer">
|
||||
<p>默认管理员账号:admin / admin</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,503 +0,0 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}我的数据{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="content-header">
|
||||
<h1>我的数据</h1>
|
||||
<p>查看和管理您录入的所有数据</p>
|
||||
</div>
|
||||
|
||||
<!-- 搜索框 -->
|
||||
<div class="search-container">
|
||||
<form method="GET" action="{{ url_for('my_data') }}" class="search-form">
|
||||
<div class="search-input-group">
|
||||
<input type="text" name="keyword" value="{{ keyword }}" placeholder="搜索我的数据..." class="search-input">
|
||||
<button type="submit" class="search-btn">
|
||||
<i class="search-icon">🔍</i>
|
||||
搜索
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
{% if keyword %}
|
||||
<div class="search-info">
|
||||
<span>搜索关键词: "{{ keyword }}"</span>
|
||||
<a href="{{ url_for('my_data') }}" class="clear-search">清除搜索</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- 数据统计 -->
|
||||
<div class="data-stats">
|
||||
<div class="stat-item">
|
||||
<span class="stat-number">{{ data|length }}</span>
|
||||
<span class="stat-label">条记录</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 数据列表 -->
|
||||
<div class="data-container">
|
||||
{% if data %}
|
||||
<div class="data-grid">
|
||||
{% for item in data %}
|
||||
<div class="data-card">
|
||||
<!-- 图片显示 -->
|
||||
{% if item.image %}
|
||||
<div class="card-image">
|
||||
<img src="{{ url_for('serve_image', filename=item.image) }}" alt="数据图片" onclick="openImageModal('{{ url_for('serve_image', filename=item.image) }}')">
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<!-- 数据内容 -->
|
||||
<div class="card-content">
|
||||
{% for key, value in item.items() %}
|
||||
{% if key not in ['_id', 'image', 'user_id'] %}
|
||||
<div class="data-field">
|
||||
<span class="field-label">{{ key }}:</span>
|
||||
<span class="field-value">{{ value }}</span>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
<!-- 操作按钮 -->
|
||||
<div class="card-actions">
|
||||
<a href="{{ url_for('edit_entry', doc_id=item._id) }}" class="btn btn-edit">
|
||||
<i class="icon">✏️</i>
|
||||
编辑
|
||||
</a>
|
||||
<button onclick="confirmDelete('{{ item._id }}')" class="btn btn-delete">
|
||||
<i class="icon">🗑️</i>
|
||||
删除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="empty-state">
|
||||
<div class="empty-icon">📝</div>
|
||||
<h3>暂无数据</h3>
|
||||
<p>{% if keyword %}没有找到匹配 "{{ keyword }}" 的数据{% else %}您还没有录入任何数据{% endif %}</p>
|
||||
<a href="{{ url_for('index') }}" class="btn btn-primary">开始录入数据</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- 图片预览模态框 -->
|
||||
<div id="imageModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<span class="close" onclick="closeImageModal()">×</span>
|
||||
<img id="modalImage" src="" alt="图片预览">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 删除确认模态框 -->
|
||||
<div id="deleteModal" class="modal">
|
||||
<div class="modal-content modal-small">
|
||||
<h3>确认删除</h3>
|
||||
<p>您确定要删除这条数据吗?此操作不可撤销。</p>
|
||||
<div class="modal-actions">
|
||||
<button onclick="closeDeleteModal()" class="btn btn-secondary">取消</button>
|
||||
<form id="deleteForm" method="POST" style="display: inline;" onsubmit="handleDeleteSubmit(event)">
|
||||
<button type="submit" class="btn btn-danger">确认删除</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.content-header {
|
||||
margin-bottom: 30px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.content-header h1 {
|
||||
color: #333;
|
||||
font-size: 28px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.content-header p {
|
||||
color: #666;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.search-container {
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
padding: 20px;
|
||||
margin-bottom: 20px;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.search-form {
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.search-input-group {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
max-width: 500px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
flex: 1;
|
||||
padding: 12px 16px;
|
||||
border: 2px solid #e9ecef;
|
||||
border-radius: 8px;
|
||||
font-size: 16px;
|
||||
transition: border-color 0.3s ease;
|
||||
}
|
||||
|
||||
.search-input:focus {
|
||||
outline: none;
|
||||
border-color: #667eea;
|
||||
}
|
||||
|
||||
.search-btn {
|
||||
padding: 12px 20px;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
font-weight: 600;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
.search-btn:hover {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.search-info {
|
||||
text-align: center;
|
||||
color: #666;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.clear-search {
|
||||
color: #667eea;
|
||||
text-decoration: none;
|
||||
margin-left: 10px;
|
||||
}
|
||||
|
||||
.clear-search:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.data-stats {
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
padding: 20px;
|
||||
margin-bottom: 20px;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.stat-item {
|
||||
display: inline-flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.stat-number {
|
||||
font-size: 32px;
|
||||
font-weight: 700;
|
||||
color: #667eea;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 14px;
|
||||
color: #666;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.data-container {
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
padding: 20px;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.data-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.data-card {
|
||||
border: 2px solid #e9ecef;
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
transition: all 0.3s ease;
|
||||
background: #f8f9fa;
|
||||
}
|
||||
|
||||
.data-card:hover {
|
||||
border-color: #667eea;
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
|
||||
}
|
||||
|
||||
.card-image {
|
||||
height: 200px;
|
||||
overflow: hidden;
|
||||
background: #f0f0f0;
|
||||
}
|
||||
|
||||
.card-image img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
cursor: pointer;
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
|
||||
.card-image img:hover {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
|
||||
.card-content {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.data-field {
|
||||
margin-bottom: 12px;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.field-label {
|
||||
font-weight: 600;
|
||||
color: #555;
|
||||
min-width: 80px;
|
||||
}
|
||||
|
||||
.field-value {
|
||||
color: #333;
|
||||
flex: 1;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.card-actions {
|
||||
padding: 15px 20px;
|
||||
background: white;
|
||||
border-top: 1px solid #e9ecef;
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 8px 16px;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
text-decoration: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.btn-edit {
|
||||
background: #28a745;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-edit:hover {
|
||||
background: #218838;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.btn-delete {
|
||||
background: #dc3545;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-delete:hover {
|
||||
background: #c82333;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
padding: 12px 24px;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: #6c757d;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: #5a6268;
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background: #dc3545;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-danger:hover {
|
||||
background: #c82333;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
padding: 60px 20px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.empty-icon {
|
||||
font-size: 64px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.empty-state h3 {
|
||||
font-size: 24px;
|
||||
margin-bottom: 10px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.empty-state p {
|
||||
font-size: 16px;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
/* 模态框样式 */
|
||||
.modal {
|
||||
display: none;
|
||||
position: fixed;
|
||||
z-index: 1000;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0, 0, 0, 0.8);
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
position: relative;
|
||||
margin: 5% auto;
|
||||
padding: 20px;
|
||||
width: 90%;
|
||||
max-width: 800px;
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.modal-small {
|
||||
max-width: 400px;
|
||||
margin: 15% auto;
|
||||
}
|
||||
|
||||
.close {
|
||||
position: absolute;
|
||||
top: 15px;
|
||||
right: 25px;
|
||||
font-size: 28px;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.close:hover {
|
||||
color: #333;
|
||||
}
|
||||
|
||||
#modalImage {
|
||||
max-width: 100%;
|
||||
max-height: 70vh;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.modal-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
justify-content: center;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.data-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.search-input-group {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.card-actions {
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
// 图片预览功能
|
||||
function openImageModal(imageSrc) {
|
||||
document.getElementById('modalImage').src = imageSrc;
|
||||
document.getElementById('imageModal').style.display = 'block';
|
||||
}
|
||||
|
||||
function closeImageModal() {
|
||||
document.getElementById('imageModal').style.display = 'none';
|
||||
}
|
||||
|
||||
// 删除确认功能
|
||||
function confirmDelete(docId) {
|
||||
document.getElementById('deleteForm').action = '/delete/' + docId;
|
||||
document.getElementById('deleteModal').style.display = 'block';
|
||||
}
|
||||
|
||||
function closeDeleteModal() {
|
||||
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) {
|
||||
const imageModal = document.getElementById('imageModal');
|
||||
const deleteModal = document.getElementById('deleteModal');
|
||||
|
||||
if (event.target === imageModal) {
|
||||
closeImageModal();
|
||||
}
|
||||
if (event.target === deleteModal) {
|
||||
closeDeleteModal();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -1,538 +0,0 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}个人设置{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="content-header">
|
||||
<h1>个人设置</h1>
|
||||
<p>管理您的个人信息和账户设置</p>
|
||||
</div>
|
||||
|
||||
<!-- 用户信息卡片 -->
|
||||
<div class="card">
|
||||
<h3 style="margin-bottom: 20px; color: var(--primary); font-size: 18px;">
|
||||
<i style="margin-right: 8px;">👤</i>
|
||||
用户信息
|
||||
</h3>
|
||||
|
||||
<div class="info-grid">
|
||||
<div class="info-item">
|
||||
<span class="info-label">用户名:</span>
|
||||
<span class="info-value">{{ session.username }}</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="info-label">权限级别:</span>
|
||||
<span class="permission-badge {{ 'admin' if session.permission == 0 else 'user' }}">
|
||||
{{ '管理员' if session.permission == 0 else '普通用户' }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 修改密码卡片 -->
|
||||
<div class="card">
|
||||
<h3 style="margin-bottom: 20px; color: var(--primary); font-size: 18px;">
|
||||
<i style="margin-right: 8px;">🔒</i>
|
||||
修改密码
|
||||
</h3>
|
||||
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
{% for category, message in messages %}
|
||||
<div class="alert alert-{{ 'success' if category == 'success' else 'error' }}">
|
||||
{{ message }}
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
<form method="POST" action="{{ url_for('change_own_password') }}" class="password-form" id="passwordForm">
|
||||
<div class="form-group">
|
||||
<label for="old_password">当前密码:</label>
|
||||
<input type="password" id="old_password" name="old_password" required class="form-input">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="new_password">新密码:</label>
|
||||
<input type="password" id="new_password" name="new_password" required class="form-input" minlength="6">
|
||||
<small class="form-help">密码长度至少6位</small>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="confirm_password">确认新密码:</label>
|
||||
<input type="password" id="confirm_password" name="confirm_password" required class="form-input">
|
||||
<small class="form-help" id="password-match-msg"></small>
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="btn btn-primary" id="submitBtn">
|
||||
<i style="margin-right: 5px;">💾</i>
|
||||
修改密码
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.content-header {
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.content-header h1 {
|
||||
color: var(--primary);
|
||||
font-size: 28px;
|
||||
margin-bottom: 8px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.content-header p {
|
||||
color: #666;
|
||||
font-size: 16px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.info-grid {
|
||||
display: grid;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
.info-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 12px 0;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.info-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.info-label {
|
||||
font-weight: 500;
|
||||
color: #555;
|
||||
}
|
||||
|
||||
.info-value {
|
||||
color: #333;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.permission-badge {
|
||||
padding: 4px 12px;
|
||||
border-radius: 20px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.permission-badge.admin {
|
||||
background: var(--accent);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.permission-badge.user {
|
||||
background: var(--success);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.password-form {
|
||||
max-width: 400px;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
margin-bottom: 5px;
|
||||
font-weight: 500;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.form-input {
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
border: 2px solid #e1e5e9;
|
||||
border-radius: var(--radius);
|
||||
font-size: 14px;
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.form-input:focus {
|
||||
outline: none;
|
||||
border-color: var(--primary);
|
||||
box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.1);
|
||||
}
|
||||
|
||||
.form-help {
|
||||
display: block;
|
||||
margin-top: 5px;
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
margin-top: 25px;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 12px 24px;
|
||||
border: none;
|
||||
border-radius: var(--radius);
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background: var(--secondary);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.alert {
|
||||
padding: 12px 16px;
|
||||
border-radius: var(--radius);
|
||||
margin-bottom: 20px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.alert-success {
|
||||
background: #d4edda;
|
||||
color: #155724;
|
||||
border: 1px solid #c3e6cb;
|
||||
}
|
||||
|
||||
.alert-error {
|
||||
background: #f8d7da;
|
||||
color: #721c24;
|
||||
border: 1px solid #f5c6cb;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.password-form {
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.info-item {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 5px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const newPassword = document.getElementById('new_password');
|
||||
const confirmPassword = document.getElementById('confirm_password');
|
||||
const submitBtn = document.getElementById('submitBtn');
|
||||
const matchMsg = document.getElementById('password-match-msg');
|
||||
|
||||
function checkPasswordMatch() {
|
||||
if (confirmPassword.value === '') {
|
||||
matchMsg.textContent = '';
|
||||
matchMsg.style.color = '#666';
|
||||
return;
|
||||
}
|
||||
|
||||
if (newPassword.value === confirmPassword.value) {
|
||||
matchMsg.textContent = '✓ 密码匹配';
|
||||
matchMsg.style.color = '#28a745';
|
||||
submitBtn.disabled = false;
|
||||
} else {
|
||||
matchMsg.textContent = '✗ 密码不匹配';
|
||||
matchMsg.style.color = '#dc3545';
|
||||
submitBtn.disabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
newPassword.addEventListener('input', checkPasswordMatch);
|
||||
confirmPassword.addEventListener('input', checkPasswordMatch);
|
||||
|
||||
// 表单验证
|
||||
document.getElementById('passwordForm').addEventListener('submit', function(e) {
|
||||
if (newPassword.value !== confirmPassword.value) {
|
||||
e.preventDefault();
|
||||
alert('新密码和确认密码不匹配!');
|
||||
}
|
||||
|
||||
if (newPassword.value.length < 6) {
|
||||
e.preventDefault();
|
||||
alert('密码长度至少6位!');
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
.permission-admin {
|
||||
background: #e3f2fd;
|
||||
color: #1976d2;
|
||||
}
|
||||
|
||||
.permission-user {
|
||||
background: #f3e5f5;
|
||||
color: #7b1fa2;
|
||||
}
|
||||
|
||||
.password-form {
|
||||
background: white;
|
||||
border: 2px solid #e9ecef;
|
||||
border-radius: 12px;
|
||||
padding: 25px;
|
||||
}
|
||||
|
||||
.password-form h3 {
|
||||
color: #333;
|
||||
margin-bottom: 20px;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
margin-bottom: 8px;
|
||||
color: #555;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.form-group input {
|
||||
width: 100%;
|
||||
padding: 12px 16px;
|
||||
border: 2px solid #e9ecef;
|
||||
border-radius: 8px;
|
||||
font-size: 16px;
|
||||
transition: all 0.3s ease;
|
||||
background: #f8f9fa;
|
||||
}
|
||||
|
||||
.form-group input:focus {
|
||||
outline: none;
|
||||
border-color: #667eea;
|
||||
background: white;
|
||||
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
|
||||
}
|
||||
|
||||
.btn {
|
||||
width: 100%;
|
||||
padding: 12px 24px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: #6c757d;
|
||||
color: white;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: #5a6268;
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.flash-messages {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.flash-message {
|
||||
padding: 12px 16px;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 10px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.flash-error {
|
||||
background: #f8d7da;
|
||||
color: #721c24;
|
||||
border: 1px solid #f5c6cb;
|
||||
}
|
||||
|
||||
.flash-success {
|
||||
background: #d4edda;
|
||||
color: #155724;
|
||||
border: 1px solid #c3e6cb;
|
||||
}
|
||||
|
||||
.flash-info {
|
||||
background: #d1ecf1;
|
||||
color: #0c5460;
|
||||
border: 1px solid #bee5eb;
|
||||
}
|
||||
|
||||
.navigation-links {
|
||||
text-align: center;
|
||||
margin-top: 30px;
|
||||
padding-top: 20px;
|
||||
border-top: 1px solid #e9ecef;
|
||||
}
|
||||
|
||||
.nav-link {
|
||||
display: inline-block;
|
||||
margin: 0 15px;
|
||||
color: #667eea;
|
||||
text-decoration: none;
|
||||
font-weight: 500;
|
||||
transition: color 0.3s ease;
|
||||
}
|
||||
|
||||
.nav-link:hover {
|
||||
color: #764ba2;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.profile-container {
|
||||
padding: 30px 20px;
|
||||
margin: 10px;
|
||||
}
|
||||
|
||||
.profile-header h1 {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
.info-item {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 5px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="profile-container">
|
||||
<!-- Flash Messages -->
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
<div class="flash-messages">
|
||||
{% for category, message in messages %}
|
||||
<div class="flash-message flash-{{ category }}">
|
||||
{{ message }}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
<div class="profile-header">
|
||||
<h1>个人设置</h1>
|
||||
<p>管理您的账户信息和密码</p>
|
||||
</div>
|
||||
|
||||
<!-- 用户信息显示 -->
|
||||
<div class="user-info">
|
||||
<h3>账户信息</h3>
|
||||
<div class="info-item">
|
||||
<span class="info-label">用户名:</span>
|
||||
<span class="info-value">{{ session.user_id }}</span>
|
||||
</div>
|
||||
<div class="info-item">
|
||||
<span class="info-label">权限级别:</span>
|
||||
<span class="permission-badge {{ 'permission-admin' if session.permission == 0 else 'permission-user' }}">
|
||||
{{ '管理员' if session.permission == 0 else '普通用户' }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 修改密码表单 -->
|
||||
<form method="POST" action="{{ url_for('change_own_password') }}" class="password-form" id="passwordForm">
|
||||
<h3>修改密码</h3>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="old_password">当前密码:</label>
|
||||
<input type="password" id="old_password" name="old_password" required>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="new_password">新密码:</label>
|
||||
<input type="password" id="new_password" name="new_password" required minlength="6">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="confirm_password">确认新密码:</label>
|
||||
<input type="password" id="confirm_password" name="confirm_password" required minlength="6">
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary">更新密码</button>
|
||||
</form>
|
||||
|
||||
<!-- 导航链接 -->
|
||||
<div class="navigation-links">
|
||||
<a href="{{ url_for('index') }}" class="nav-link">返回首页</a>
|
||||
<a href="{{ url_for('my_data') }}" class="nav-link">我的数据</a>
|
||||
{% if session.permission == 0 %}
|
||||
<a href="{{ url_for('user_management') }}" class="nav-link">用户管理</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// 密码确认验证
|
||||
document.getElementById('passwordForm').addEventListener('submit', function(e) {
|
||||
const newPassword = document.getElementById('new_password').value;
|
||||
const confirmPassword = document.getElementById('confirm_password').value;
|
||||
|
||||
if (newPassword !== confirmPassword) {
|
||||
e.preventDefault();
|
||||
alert('新密码和确认密码不一致,请重新输入!');
|
||||
return false;
|
||||
}
|
||||
|
||||
if (newPassword.length < 6) {
|
||||
e.preventDefault();
|
||||
alert('新密码长度至少6位!');
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
// 输入实时验证
|
||||
document.getElementById('confirm_password').addEventListener('input', function() {
|
||||
const newPassword = document.getElementById('new_password').value;
|
||||
const confirmPassword = this.value;
|
||||
|
||||
if (confirmPassword && newPassword !== confirmPassword) {
|
||||
this.style.borderColor = '#dc3545';
|
||||
this.style.background = '#fff5f5';
|
||||
} else {
|
||||
this.style.borderColor = '#e9ecef';
|
||||
this.style.background = '#f8f9fa';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,440 +0,0 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}注册新用户{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="register-container">
|
||||
<div class="register-card">
|
||||
<div class="register-header">
|
||||
<h1>注册新用户</h1>
|
||||
<p>创建新的系统用户账户</p>
|
||||
</div>
|
||||
|
||||
<form method="POST" class="register-form">
|
||||
<div class="form-group">
|
||||
<label for="username">
|
||||
<i class="fas fa-user"></i>
|
||||
用户名
|
||||
</label>
|
||||
<input type="text"
|
||||
id="username"
|
||||
name="username"
|
||||
required
|
||||
minlength="3"
|
||||
maxlength="20"
|
||||
placeholder="请输入用户名(3-20个字符)">
|
||||
<small class="form-text">用户名长度为3-20个字符,只能包含字母、数字和下划线</small>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="password">
|
||||
<i class="fas fa-lock"></i>
|
||||
密码
|
||||
</label>
|
||||
<input type="password"
|
||||
id="password"
|
||||
name="password"
|
||||
required
|
||||
minlength="6"
|
||||
placeholder="请输入密码(至少6位)">
|
||||
<small class="form-text">密码长度至少6位,建议包含字母和数字</small>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="confirm_password">
|
||||
<i class="fas fa-lock"></i>
|
||||
确认密码
|
||||
</label>
|
||||
<input type="password"
|
||||
id="confirm_password"
|
||||
name="confirm_password"
|
||||
required
|
||||
minlength="6"
|
||||
placeholder="请再次输入密码">
|
||||
<small class="form-text">请再次输入相同的密码进行确认</small>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="permission">
|
||||
<i class="fas fa-user-cog"></i>
|
||||
权限级别
|
||||
</label>
|
||||
<select id="permission" name="permission" required>
|
||||
<option value="">请选择权限级别</option>
|
||||
<option value="1">普通用户 - 可以录入和查询数据</option>
|
||||
<option value="0">管理员 - 拥有所有权限</option>
|
||||
</select>
|
||||
<small class="form-text">
|
||||
<strong>普通用户:</strong>可以上传图片、录入数据、查询数据<br>
|
||||
<strong>管理员:</strong>拥有所有权限,包括用户管理和数据管理
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="btn btn-primary">
|
||||
<i class="fas fa-user-plus"></i>
|
||||
创建用户
|
||||
</button>
|
||||
<a href="{{ url_for('user_management') }}" class="btn btn-secondary">
|
||||
<i class="fas fa-arrow-left"></i>
|
||||
返回用户管理
|
||||
</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.register-container {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-height: calc(100vh - 200px);
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.register-card {
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 20px rgba(0,0,0,0.1);
|
||||
padding: 40px;
|
||||
width: 100%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.register-header {
|
||||
text-align: center;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.register-header h1 {
|
||||
color: #333;
|
||||
margin-bottom: 10px;
|
||||
font-size: 28px;
|
||||
}
|
||||
|
||||
.register-header p {
|
||||
color: #666;
|
||||
font-size: 16px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.register-form {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 25px;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
margin-bottom: 8px;
|
||||
font-weight: 600;
|
||||
color: #333;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.form-group label i {
|
||||
margin-right: 8px;
|
||||
color: #007bff;
|
||||
width: 16px;
|
||||
}
|
||||
|
||||
.form-group input,
|
||||
.form-group select {
|
||||
width: 100%;
|
||||
padding: 12px 16px;
|
||||
border: 2px solid #e0e0e0;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
transition: all 0.3s ease;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.form-group input:focus,
|
||||
.form-group select:focus {
|
||||
outline: none;
|
||||
border-color: #007bff;
|
||||
box-shadow: 0 0 0 3px rgba(0,123,255,0.1);
|
||||
}
|
||||
|
||||
.form-group input:invalid {
|
||||
border-color: #dc3545;
|
||||
}
|
||||
|
||||
.form-group input:valid {
|
||||
border-color: #28a745;
|
||||
}
|
||||
|
||||
.form-text {
|
||||
display: block;
|
||||
margin-top: 5px;
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
display: flex;
|
||||
gap: 15px;
|
||||
margin-top: 30px;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 12px 24px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
transition: all 0.3s ease;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.btn i {
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background-color: #007bff;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background-color: #0056b3;
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(0,123,255,0.3);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background-color: #6c757d;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background-color: #545b62;
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(108,117,125,0.3);
|
||||
}
|
||||
|
||||
/* 响应式设计 */
|
||||
@media (max-width: 768px) {
|
||||
.register-container {
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.register-card {
|
||||
padding: 30px 20px;
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.btn {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
/* 密码强度指示器 */
|
||||
.password-strength {
|
||||
margin-top: 5px;
|
||||
height: 4px;
|
||||
background-color: #e0e0e0;
|
||||
border-radius: 2px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.password-strength-bar {
|
||||
height: 100%;
|
||||
width: 0%;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.strength-weak {
|
||||
background-color: #dc3545;
|
||||
width: 33%;
|
||||
}
|
||||
|
||||
.strength-medium {
|
||||
background-color: #ffc107;
|
||||
width: 66%;
|
||||
}
|
||||
|
||||
.strength-strong {
|
||||
background-color: #28a745;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* 表单验证样式 */
|
||||
.form-group.error input,
|
||||
.form-group.error select {
|
||||
border-color: #dc3545;
|
||||
box-shadow: 0 0 0 3px rgba(220,53,69,0.1);
|
||||
}
|
||||
|
||||
.form-group.success input,
|
||||
.form-group.success select {
|
||||
border-color: #28a745;
|
||||
box-shadow: 0 0 0 3px rgba(40,167,69,0.1);
|
||||
}
|
||||
|
||||
.error-message {
|
||||
color: #dc3545;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.success-message {
|
||||
color: #28a745;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
display: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
// 表单验证
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const form = document.querySelector('.register-form');
|
||||
const username = document.getElementById('username');
|
||||
const password = document.getElementById('password');
|
||||
const confirmPassword = document.getElementById('confirm_password');
|
||||
const permission = document.getElementById('permission');
|
||||
|
||||
// 用户名验证
|
||||
username.addEventListener('input', function() {
|
||||
const value = this.value;
|
||||
const formGroup = this.closest('.form-group');
|
||||
|
||||
if (value.length < 3) {
|
||||
setFieldError(formGroup, '用户名至少需要3个字符');
|
||||
} else if (value.length > 20) {
|
||||
setFieldError(formGroup, '用户名不能超过20个字符');
|
||||
} else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
|
||||
setFieldError(formGroup, '用户名只能包含字母、数字和下划线');
|
||||
} else {
|
||||
setFieldSuccess(formGroup, '用户名格式正确');
|
||||
}
|
||||
});
|
||||
|
||||
// 密码验证
|
||||
password.addEventListener('input', function() {
|
||||
const value = this.value;
|
||||
const formGroup = this.closest('.form-group');
|
||||
|
||||
if (value.length < 6) {
|
||||
setFieldError(formGroup, '密码至少需要6个字符');
|
||||
} else {
|
||||
setFieldSuccess(formGroup, '密码长度符合要求');
|
||||
}
|
||||
|
||||
// 检查确认密码
|
||||
if (confirmPassword.value) {
|
||||
validateConfirmPassword();
|
||||
}
|
||||
});
|
||||
|
||||
// 确认密码验证
|
||||
confirmPassword.addEventListener('input', validateConfirmPassword);
|
||||
|
||||
function validateConfirmPassword() {
|
||||
const formGroup = confirmPassword.closest('.form-group');
|
||||
|
||||
if (confirmPassword.value !== password.value) {
|
||||
setFieldError(formGroup, '两次输入的密码不一致');
|
||||
} else if (confirmPassword.value.length >= 6) {
|
||||
setFieldSuccess(formGroup, '密码确认正确');
|
||||
}
|
||||
}
|
||||
|
||||
// 权限选择验证
|
||||
permission.addEventListener('change', function() {
|
||||
const formGroup = this.closest('.form-group');
|
||||
|
||||
if (this.value === '') {
|
||||
setFieldError(formGroup, '请选择权限级别');
|
||||
} else {
|
||||
setFieldSuccess(formGroup, '权限级别已选择');
|
||||
}
|
||||
});
|
||||
|
||||
// 表单提交验证
|
||||
form.addEventListener('submit', function(e) {
|
||||
let isValid = true;
|
||||
|
||||
// 验证用户名
|
||||
if (username.value.length < 3 || username.value.length > 20 || !/^[a-zA-Z0-9_]+$/.test(username.value)) {
|
||||
isValid = false;
|
||||
setFieldError(username.closest('.form-group'), '用户名格式不正确');
|
||||
}
|
||||
|
||||
// 验证密码
|
||||
if (password.value.length < 6) {
|
||||
isValid = false;
|
||||
setFieldError(password.closest('.form-group'), '密码长度至少6位');
|
||||
}
|
||||
|
||||
// 验证确认密码
|
||||
if (password.value !== confirmPassword.value) {
|
||||
isValid = false;
|
||||
setFieldError(confirmPassword.closest('.form-group'), '两次输入的密码不一致');
|
||||
}
|
||||
|
||||
// 验证权限选择
|
||||
if (permission.value === '') {
|
||||
isValid = false;
|
||||
setFieldError(permission.closest('.form-group'), '请选择权限级别');
|
||||
}
|
||||
|
||||
if (!isValid) {
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
function setFieldError(formGroup, message) {
|
||||
formGroup.classList.remove('success');
|
||||
formGroup.classList.add('error');
|
||||
|
||||
let errorMsg = formGroup.querySelector('.error-message');
|
||||
if (!errorMsg) {
|
||||
errorMsg = document.createElement('div');
|
||||
errorMsg.className = 'error-message';
|
||||
formGroup.appendChild(errorMsg);
|
||||
}
|
||||
errorMsg.textContent = message;
|
||||
errorMsg.style.display = 'block';
|
||||
|
||||
const successMsg = formGroup.querySelector('.success-message');
|
||||
if (successMsg) {
|
||||
successMsg.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
function setFieldSuccess(formGroup, message) {
|
||||
formGroup.classList.remove('error');
|
||||
formGroup.classList.add('success');
|
||||
|
||||
let successMsg = formGroup.querySelector('.success-message');
|
||||
if (!successMsg) {
|
||||
successMsg = document.createElement('div');
|
||||
successMsg.className = 'success-message';
|
||||
formGroup.appendChild(successMsg);
|
||||
}
|
||||
successMsg.textContent = message;
|
||||
successMsg.style.display = 'block';
|
||||
|
||||
const errorMsg = formGroup.querySelector('.error-message');
|
||||
if (errorMsg) {
|
||||
errorMsg.style.display = 'none';
|
||||
}
|
||||
}
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -1,362 +0,0 @@
|
||||
|
||||
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}查询统计 - 紫金·稷下薪火·云枢智海师生成果共创系统{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<style>
|
||||
/* 基础样式重置 */
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
|
||||
/* 主体布局 */
|
||||
.container {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
/* 标题样式 */
|
||||
h2 {
|
||||
color: #2c3e50;
|
||||
border-bottom: 2px solid #3498db;
|
||||
padding-bottom: 10px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
/* 搜索区域样式 */
|
||||
.search-container {
|
||||
background: #f8f9fa;
|
||||
padding: 25px;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.search-form {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
flex: 1;
|
||||
padding: 12px 15px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 6px;
|
||||
font-size: 16px;
|
||||
transition: border-color 0.3s;
|
||||
}
|
||||
|
||||
.search-input:focus {
|
||||
border-color: #3498db;
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
|
||||
}
|
||||
|
||||
.search-button {
|
||||
padding: 12px 25px;
|
||||
background: linear-gradient(135deg, #3498db, #1a5276);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-weight: bold;
|
||||
transition: transform 0.2s, box-shadow 0.2s;
|
||||
}
|
||||
|
||||
.search-button:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 8px rgba(52, 152, 219, 0.4);
|
||||
}
|
||||
|
||||
/* 结果区域样式 */
|
||||
.results-container {
|
||||
min-height: 300px;
|
||||
}
|
||||
|
||||
.result-item {
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
margin-bottom: 20px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.05);
|
||||
border-left: 4px solid #3498db;
|
||||
transition: transform 0.3s;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.result-item:hover {
|
||||
transform: translateY(-3px);
|
||||
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
.result-preview {
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.result-preview .field-item {
|
||||
display: inline-block;
|
||||
margin-right: 20px;
|
||||
margin-bottom: 8px;
|
||||
padding: 5px 10px;
|
||||
background: #f8f9fa;
|
||||
border-radius: 4px;
|
||||
border: 1px solid #e9ecef;
|
||||
}
|
||||
|
||||
.result-preview .field-label {
|
||||
font-weight: bold;
|
||||
color: #2c3e50;
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
.result-preview .field-value {
|
||||
color: #34495e;
|
||||
}
|
||||
|
||||
.result-details {
|
||||
display: none;
|
||||
border-top: 1px solid #e9ecef;
|
||||
padding-top: 15px;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
.result-details.expanded {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.result-details .field-item {
|
||||
margin-bottom: 10px;
|
||||
padding: 8px 12px;
|
||||
background: #f8f9fa;
|
||||
border-radius: 4px;
|
||||
border-left: 3px solid #3498db;
|
||||
}
|
||||
|
||||
.result-details .field-label {
|
||||
font-weight: bold;
|
||||
color: #2c3e50;
|
||||
display: inline-block;
|
||||
min-width: 120px;
|
||||
}
|
||||
|
||||
.result-details .field-value {
|
||||
color: #34495e;
|
||||
}
|
||||
|
||||
.expand-indicator {
|
||||
float: right;
|
||||
color: #3498db;
|
||||
font-size: 14px;
|
||||
transition: all 0.3s;
|
||||
}
|
||||
|
||||
.result-item.expanded .expand-indicator {
|
||||
color: #2c3e50;
|
||||
}
|
||||
|
||||
.image-container {
|
||||
margin-top: 15px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.result-image {
|
||||
max-width: 100%;
|
||||
max-height: 300px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
|
||||
cursor: pointer;
|
||||
transition: transform 0.3s;
|
||||
}
|
||||
|
||||
.result-image:hover {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
|
||||
.image-modal {
|
||||
display: none;
|
||||
position: fixed;
|
||||
z-index: 1000;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0,0,0,0.8);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.image-modal img {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
max-width: 90%;
|
||||
max-height: 90%;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.close-modal {
|
||||
position: absolute;
|
||||
top: 20px;
|
||||
right: 30px;
|
||||
color: white;
|
||||
font-size: 30px;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* 加载状态 */
|
||||
.loading {
|
||||
text-align: center;
|
||||
padding: 40px;
|
||||
color: #7f8c8d;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
/* 错误信息 */
|
||||
.error {
|
||||
color: #e74c3c;
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
background: rgba(231, 76, 60, 0.1);
|
||||
border-radius: 6px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="container">
|
||||
<h2>奖项成果查询</h2>
|
||||
<p>输入关键词(如姓名、奖项名等)搜索已录入的成果信息</p>
|
||||
|
||||
<div class="search-container">
|
||||
<form id="search-form" class="search-form">
|
||||
<input type="text" name="q" class="search-input" placeholder="输入关键词(如姓名、奖项名等)" required>
|
||||
<button type="submit" class="search-button">搜索</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div id="results" class="results-container">
|
||||
<!-- 结果将通过JS动态加载 -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.getElementById("search-form").addEventListener("submit", function (e) {
|
||||
e.preventDefault();
|
||||
const q = this.q.value;
|
||||
const resultsContainer = document.getElementById("results");
|
||||
|
||||
// 显示加载状态
|
||||
resultsContainer.innerHTML = '<div class="loading">正在搜索,请稍候...</div>';
|
||||
|
||||
fetch(`/search?q=${encodeURIComponent(q)}`)
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
const realData = data.hits?.hits || data;
|
||||
|
||||
if (!Array.isArray(realData) || realData.length === 0) {
|
||||
resultsContainer.innerHTML = '<div class="error">未找到相关结果</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
const html = realData.map((item, index) => {
|
||||
const source = item._source || {};
|
||||
const allFields = Object.entries(source).filter(([key, value]) => key !== 'image' && value);
|
||||
|
||||
// 获取前3个字段作为预览
|
||||
const previewFields = allFields.slice(0, 3);
|
||||
const hasMoreFields = allFields.length > 3;
|
||||
|
||||
// 生成预览字段HTML
|
||||
const previewHtml = previewFields.map(([key, value]) => `
|
||||
<div class="field-item">
|
||||
<span class="field-label">${key}:</span>
|
||||
<span class="field-value">${Array.isArray(value) ? value.join(', ') : value}</span>
|
||||
</div>
|
||||
`).join('');
|
||||
|
||||
// 生成详细字段HTML
|
||||
const detailsHtml = allFields.map(([key, value]) => `
|
||||
<div class="field-item">
|
||||
<span class="field-label">${key}:</span>
|
||||
<span class="field-value">${Array.isArray(value) ? value.join(', ') : value}</span>
|
||||
</div>
|
||||
`).join('');
|
||||
|
||||
// 图片HTML
|
||||
const imageHtml = source.image ? `
|
||||
<div class="image-container">
|
||||
<img src="/image/${source.image}" alt="相关图片" class="result-image" onclick="openImageModal('/image/${source.image}')">
|
||||
</div>
|
||||
` : '';
|
||||
|
||||
return `
|
||||
<div class="result-item" onclick="toggleDetails(${index})" data-index="${index}">
|
||||
<div class="result-preview">
|
||||
${previewHtml}
|
||||
${hasMoreFields ? '<span class="expand-indicator">▼ 点击查看更多</span>' : ''}
|
||||
</div>
|
||||
<div class="result-details" id="details-${index}">
|
||||
${detailsHtml}
|
||||
${imageHtml}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
resultsContainer.innerHTML = html;
|
||||
})
|
||||
.catch(err => {
|
||||
resultsContainer.innerHTML = '<div class="error">搜索过程中发生错误</div>';
|
||||
});
|
||||
});
|
||||
|
||||
function toggleDetails(index) {
|
||||
const resultItem = document.querySelector(`[data-index="${index}"]`);
|
||||
const detailsDiv = document.getElementById(`details-${index}`);
|
||||
|
||||
if (detailsDiv.classList.contains('expanded')) {
|
||||
detailsDiv.classList.remove('expanded');
|
||||
resultItem.classList.remove('expanded');
|
||||
} else {
|
||||
detailsDiv.classList.add('expanded');
|
||||
resultItem.classList.add('expanded');
|
||||
}
|
||||
}
|
||||
|
||||
function openImageModal(imageSrc) {
|
||||
event.stopPropagation(); // 阻止事件冒泡
|
||||
|
||||
// 创建模态框
|
||||
const modal = document.createElement('div');
|
||||
modal.className = 'image-modal';
|
||||
modal.innerHTML = `
|
||||
<span class="close-modal" onclick="closeImageModal()">×</span>
|
||||
<img src="${imageSrc}" alt="图片预览">
|
||||
`;
|
||||
|
||||
document.body.appendChild(modal);
|
||||
modal.style.display = 'block';
|
||||
|
||||
// 点击模态框背景关闭
|
||||
modal.addEventListener('click', function(e) {
|
||||
if (e.target === modal) {
|
||||
closeImageModal();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function closeImageModal() {
|
||||
const modal = document.querySelector('.image-modal');
|
||||
if (modal) {
|
||||
modal.remove();
|
||||
}
|
||||
}
|
||||
|
||||
// ESC键关闭模态框
|
||||
document.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Escape') {
|
||||
closeImageModal();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -1,356 +0,0 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}用户管理{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container">
|
||||
<div class="header-section">
|
||||
<h1>用户管理</h1>
|
||||
<a href="{{ url_for('register') }}" class="btn btn-primary">
|
||||
<i class="fas fa-user-plus"></i> 注册新用户
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="users-table">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>用户ID</th>
|
||||
<th>用户名</th>
|
||||
<th>权限级别</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for user in users %}
|
||||
<tr>
|
||||
<td>{{ user.user_id }}</td>
|
||||
<td>{{ user.username }}</td>
|
||||
<td>
|
||||
<span class="permission-badge {% if user.premission == 0 %}admin{% else %}user{% endif %}">
|
||||
{% if user.premission == 0 %}管理员{% else %}普通用户{% endif %}
|
||||
</span>
|
||||
</td>
|
||||
<td class="actions">
|
||||
{% if user.username != 'admin' %}
|
||||
<!-- 修改密码按钮 -->
|
||||
<button class="btn btn-sm btn-warning" onclick="showPasswordModal('{{ user.username }}')">
|
||||
<i class="fas fa-key"></i> 修改密码
|
||||
</button>
|
||||
|
||||
<!-- 修改权限按钮 -->
|
||||
<button class="btn btn-sm btn-info" onclick="showPermissionModal('{{ user.username }}', {{ user.premission }})">
|
||||
<i class="fas fa-user-cog"></i> 修改权限
|
||||
</button>
|
||||
|
||||
<!-- 删除用户按钮 -->
|
||||
<button class="btn btn-sm btn-danger" onclick="confirmDelete('{{ user.username }}')">
|
||||
<i class="fas fa-trash"></i> 删除
|
||||
</button>
|
||||
{% else %}
|
||||
<span class="text-muted">系统管理员</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 修改密码模态框 -->
|
||||
<div id="passwordModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<span class="close" onclick="closeModal('passwordModal')">×</span>
|
||||
<h2>修改用户密码</h2>
|
||||
<form id="passwordForm" method="POST">
|
||||
<div class="form-group">
|
||||
<label for="new_password">新密码:</label>
|
||||
<input type="password" id="new_password" name="new_password" required minlength="6">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="confirm_password">确认密码:</label>
|
||||
<input type="password" id="confirm_password" name="confirm_password" required minlength="6">
|
||||
</div>
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="btn btn-primary">确认修改</button>
|
||||
<button type="button" class="btn btn-secondary" onclick="closeModal('passwordModal')">取消</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 修改权限模态框 -->
|
||||
<div id="permissionModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<span class="close" onclick="closeModal('permissionModal')">×</span>
|
||||
<h2>修改用户权限</h2>
|
||||
<form id="permissionForm" method="POST">
|
||||
<div class="form-group">
|
||||
<label for="permission">权限级别:</label>
|
||||
<select id="permission" name="permission" required>
|
||||
<option value="0">管理员</option>
|
||||
<option value="1">普通用户</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="btn btn-primary">确认修改</button>
|
||||
<button type="button" class="btn btn-secondary" onclick="closeModal('permissionModal')">取消</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 删除确认模态框 -->
|
||||
<div id="deleteModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<span class="close" onclick="closeModal('deleteModal')">×</span>
|
||||
<h2>确认删除</h2>
|
||||
<p>确定要删除用户 <strong id="deleteUsername"></strong> 吗?此操作不可撤销。</p>
|
||||
<div class="form-actions">
|
||||
<form id="deleteForm" method="POST">
|
||||
<button type="submit" class="btn btn-danger">确认删除</button>
|
||||
<button type="button" class="btn btn-secondary" onclick="closeModal('deleteModal')">取消</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.container {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.header-section {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 30px;
|
||||
padding-bottom: 20px;
|
||||
border-bottom: 2px solid #e0e0e0;
|
||||
}
|
||||
|
||||
.header-section h1 {
|
||||
color: #333;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.users-table {
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
.table th,
|
||||
.table td {
|
||||
padding: 15px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #e0e0e0;
|
||||
}
|
||||
|
||||
.table th {
|
||||
background-color: #f8f9fa;
|
||||
font-weight: 600;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.permission-badge {
|
||||
padding: 4px 12px;
|
||||
border-radius: 20px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.permission-badge.admin {
|
||||
background-color: #dc3545;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.permission-badge.user {
|
||||
background-color: #28a745;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.actions {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 8px 16px;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
margin-right: 5px;
|
||||
font-size: 14px;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background-color: #007bff;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-warning {
|
||||
background-color: #ffc107;
|
||||
color: #212529;
|
||||
}
|
||||
|
||||
.btn-info {
|
||||
background-color: #17a2b8;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background-color: #dc3545;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background-color: #6c757d;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-sm {
|
||||
padding: 6px 12px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.btn:hover {
|
||||
opacity: 0.8;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
/* 模态框样式 */
|
||||
.modal {
|
||||
display: none;
|
||||
position: fixed;
|
||||
z-index: 1000;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0,0,0,0.5);
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
background-color: white;
|
||||
margin: 10% auto;
|
||||
padding: 30px;
|
||||
border-radius: 8px;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.close {
|
||||
position: absolute;
|
||||
right: 15px;
|
||||
top: 15px;
|
||||
font-size: 28px;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
color: #aaa;
|
||||
}
|
||||
|
||||
.close:hover {
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
margin-bottom: 5px;
|
||||
font-weight: 600;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.form-group input,
|
||||
.form-group select {
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
justify-content: flex-end;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.text-muted {
|
||||
color: #6c757d;
|
||||
font-style: italic;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
function showPasswordModal(username) {
|
||||
document.getElementById('passwordForm').action = `/change_password/${username}`;
|
||||
document.getElementById('passwordModal').style.display = 'block';
|
||||
}
|
||||
|
||||
function showPermissionModal(username, currentPermission) {
|
||||
document.getElementById('permissionForm').action = `/change_permission/${username}`;
|
||||
document.getElementById('permission').value = currentPermission;
|
||||
document.getElementById('permissionModal').style.display = 'block';
|
||||
}
|
||||
|
||||
function confirmDelete(username) {
|
||||
document.getElementById('deleteUsername').textContent = username;
|
||||
document.getElementById('deleteForm').action = `/delete_user/${username}`;
|
||||
document.getElementById('deleteModal').style.display = 'block';
|
||||
}
|
||||
|
||||
function closeModal(modalId) {
|
||||
document.getElementById(modalId).style.display = 'none';
|
||||
// 清空表单
|
||||
const forms = document.querySelectorAll(`#${modalId} form`);
|
||||
forms.forEach(form => form.reset());
|
||||
}
|
||||
|
||||
// 点击模态框外部关闭
|
||||
window.onclick = function(event) {
|
||||
const modals = document.querySelectorAll('.modal');
|
||||
modals.forEach(modal => {
|
||||
if (event.target === modal) {
|
||||
modal.style.display = 'none';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 密码确认验证
|
||||
document.getElementById('passwordForm').addEventListener('submit', function(e) {
|
||||
const password = document.getElementById('new_password').value;
|
||||
const confirmPassword = document.getElementById('confirm_password').value;
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
e.preventDefault();
|
||||
alert('两次输入的密码不一致!');
|
||||
return false;
|
||||
}
|
||||
|
||||
if (password.length < 6) {
|
||||
e.preventDefault();
|
||||
alert('密码长度至少6位!');
|
||||
return false;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
Reference in New Issue
Block a user