Compare commits
46 Commits
main-v2
...
a896613726
| Author | SHA1 | Date | |
|---|---|---|---|
| a896613726 | |||
| 04b1df2130 | |||
| 0e23fe8266 | |||
| 37f8c442b2 | |||
| 9342f37b45 | |||
| 0f1cfdd803 | |||
| 4efaf7ac55 | |||
| 0564593a84 | |||
| fc34c37763 | |||
| 64219a9a24 | |||
| 31d5ca5a01 | |||
| fb5e8a6588 | |||
| 1e041cad3b | |||
| 046b649aec | |||
| e1152bdc86 | |||
| ca9da9f7aa | |||
| 62ee8399e8 | |||
| 40317b47ec | |||
| 31c0371da3 | |||
| 98056b2515 | |||
| 9dcd353815 | |||
| 42758deeae | |||
| ee46e4cebb | |||
| e2c93d6933 | |||
| 3f673f2f69 | |||
| 83a9dd04ba | |||
| 0e1d3e54d1 | |||
| 2c31e1571f | |||
| 127f5c5926 | |||
| cf57f981c0 | |||
| 30999e1de4 | |||
| be054e70ea | |||
| d37d60b896 | |||
| 1bbd777565 | |||
| f3aec9a18d | |||
| 61b1d93718 | |||
| aba94c074a | |||
| e650a087ca | |||
| 48bb1b3c12 | |||
| 8a752b2b92 | |||
| a678adf646 | |||
| 08994d732d | |||
| 0926ab2535 | |||
| e887494796 | |||
| 7e44ccdb31 | |||
| 5575370621 |
15
.dockerignore
Normal file
15
.dockerignore
Normal file
@@ -0,0 +1,15 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.pyd
|
||||
*.log
|
||||
.DS_Store
|
||||
.env
|
||||
.venv/
|
||||
venv/
|
||||
node_modules/
|
||||
.git/
|
||||
.gitignore
|
||||
db.sqlite3
|
||||
media/
|
||||
staticfiles/
|
||||
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()
|
||||
166
Achievement_Inputing/settings.py
Normal file
166
Achievement_Inputing/settings.py
Normal file
@@ -0,0 +1,166 @@
|
||||
"""
|
||||
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 = os.environ.get('DJANGO_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 = os.environ.get('DJANGO_DEBUG', 'True').lower() == 'true'
|
||||
|
||||
ALLOWED_HOSTS = os.environ.get('DJANGO_ALLOWED_HOSTS', '127.0.0.1,localhost').split(',')
|
||||
|
||||
|
||||
# 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',
|
||||
'whitenoise.middleware.WhiteNoiseMiddleware',
|
||||
'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/'
|
||||
STATIC_ROOT = BASE_DIR / 'staticfiles'
|
||||
|
||||
# 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'
|
||||
|
||||
CSRF_TRUSTED_ORIGINS = os.environ.get('DJANGO_CSRF_TRUSTED_ORIGINS', '').split(',') if os.environ.get('DJANGO_CSRF_TRUSTED_ORIGINS') else []
|
||||
|
||||
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
|
||||
_ES_URL = os.environ.get('ELASTICSEARCH_URL', 'http://localhost:9200')
|
||||
if not (_ES_URL.startswith('http://') or _ES_URL.startswith('https://')):
|
||||
_ES_URL = 'http://' + _ES_URL
|
||||
ELASTICSEARCH_DSL = {
|
||||
'default': {
|
||||
'hosts': _ES_URL
|
||||
},
|
||||
}
|
||||
|
||||
# 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()
|
||||
23
Dockerfile
Normal file
23
Dockerfile
Normal file
@@ -0,0 +1,23 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
build-essential \
|
||||
libjpeg62-turbo-dev \
|
||||
zlib1g-dev \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY requirements.txt /app/
|
||||
RUN pip install --no-cache-dir -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple \
|
||||
&& apt-get purge -y --auto-remove build-essential \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY . /app
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["sh","-c","python manage.py migrate && python manage.py collectstatic --noinput && gunicorn Achievement_Inputing.wsgi:application --bind 0.0.0.0:8000 --workers 3"]
|
||||
223
ESConnect.py
223
ESConnect.py
@@ -1,223 +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"])
|
||||
|
||||
# 定义索引名称和类型名称
|
||||
index_name = "wordsearch2666"
|
||||
|
||||
def create_index_with_mapping():
|
||||
"""修正后的索引映射配置"""
|
||||
# 修正映射结构(移除keyword字段的非法参数)
|
||||
mapping = {
|
||||
"mappings": {
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "text", # 存储转换后的字符串,支持分词搜索
|
||||
"analyzer": "ik_max_word",
|
||||
"search_analyzer": "ik_smart"
|
||||
},
|
||||
"image": {"type": "keyword"}, # 存储图片路径或标识
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# 检查索引是否存在,不存在则创建
|
||||
if not es.indices.exists(index=index_name):
|
||||
es.indices.create(index=index_name, body=mapping)
|
||||
print(f"创建索引 {index_name} 并设置映射")
|
||||
else:
|
||||
print(f"索引 {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=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=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=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=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=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_mapping()
|
||||
response = requests.post(
|
||||
f"{ES_URL}/{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}/{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
|
||||
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"),
|
||||
]
|
||||
146
accounts/views.py
Normal file
146
accounts/views.py
Normal file
@@ -0,0 +1,146 @@
|
||||
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, ensure_csrf_cookie
|
||||
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"])
|
||||
@ensure_csrf_cookie
|
||||
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
|
||||
428
app.py
428
app.py
@@ -1,428 +0,0 @@
|
||||
import base64
|
||||
from flask import Flask, request, render_template, redirect, url_for, jsonify
|
||||
import os
|
||||
import uuid
|
||||
from PIL import Image
|
||||
import re
|
||||
import json
|
||||
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)
|
||||
|
||||
# OCR和信息提取函数,使用大模型API处理图片并提取结构化信息
|
||||
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('/')
|
||||
def index():
|
||||
"""
|
||||
渲染首页模板
|
||||
|
||||
返回:
|
||||
str: 渲染后的HTML页面
|
||||
"""
|
||||
return render_template('index.html')
|
||||
|
||||
# 图片上传路由
|
||||
@app.route('/upload', methods=['POST'])
|
||||
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:
|
||||
# 使用json_converter将JSON数据转换为字符串
|
||||
data_string = json_to_string(original_data)
|
||||
print(f"转换后的数据字符串: {data_string}")
|
||||
|
||||
# 构造新的数据结构,只包含data和image字段
|
||||
processed_data = {
|
||||
"data": data_string,
|
||||
"image": filename # 存储图片文件名
|
||||
}
|
||||
print(f"准备存储的数据: {processed_data}")
|
||||
|
||||
insert_data(processed_data) # 存入ES
|
||||
print("✓ 数据成功存储到Elasticsearch")
|
||||
return jsonify({"message": "成功录入", "data": original_data, "processed": processed_data})
|
||||
else:
|
||||
print("✗ 无法识别图片内容")
|
||||
return jsonify({"error": "无法识别图片内容"}), 400
|
||||
except Exception as e:
|
||||
print(f"✗ 处理过程中发生错误: {str(e)}")
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
# 搜索路由
|
||||
@app.route('/search')
|
||||
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')
|
||||
def results_page():
|
||||
"""
|
||||
渲染搜索结果页面
|
||||
|
||||
返回:
|
||||
str: 渲染后的HTML页面
|
||||
"""
|
||||
return render_template('results.html')
|
||||
|
||||
# 显示所有数据路由
|
||||
@app.route('/all')
|
||||
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('/edit/<doc_id>')
|
||||
def edit_entry(doc_id):
|
||||
"""
|
||||
渲染编辑页面
|
||||
|
||||
参数:
|
||||
doc_id (str): 要编辑的文档ID
|
||||
|
||||
返回:
|
||||
str: 渲染后的编辑页面或错误信息
|
||||
"""
|
||||
# 获取要编辑的文档数据
|
||||
document = get_by_id(doc_id)
|
||||
if not document:
|
||||
return "文档不存在", 404
|
||||
|
||||
# 保持原始数据格式,不进行JSON转换
|
||||
# 直接传递包含data字段的原始文档
|
||||
return render_template('edited.html', document=document)
|
||||
|
||||
# 更新数据路由
|
||||
@app.route('/update/<doc_id>', methods=['POST'])
|
||||
def update_entry(doc_id):
|
||||
"""
|
||||
处理数据更新请求
|
||||
|
||||
参数:
|
||||
doc_id (str): 要更新的文档ID
|
||||
|
||||
返回:
|
||||
重定向到所有数据页面或错误信息
|
||||
"""
|
||||
# 获取原文档的图片信息
|
||||
original_doc = get_by_id(doc_id)
|
||||
if not original_doc:
|
||||
return "文档不存在", 404
|
||||
|
||||
# 从表单中获取所有字段数据
|
||||
data_parts = []
|
||||
i = 1
|
||||
while True:
|
||||
key_name = request.form.get(f'key_{i}')
|
||||
field_value = request.form.get(f'field_{i}')
|
||||
|
||||
if not key_name or not field_value:
|
||||
break
|
||||
|
||||
# 处理字段值(如果是列表格式,用|##|分隔)
|
||||
if ',' in field_value:
|
||||
# 如果是逗号分隔的值,转换为列表格式
|
||||
items = [item.strip() for item in field_value.split(',') if item.strip()]
|
||||
if len(items) > 1:
|
||||
field_value = f"[{'|##|'.join(items)}]"
|
||||
|
||||
data_parts.append(f"{key_name}:{field_value}")
|
||||
i += 1
|
||||
|
||||
# 验证是否有数据
|
||||
if not data_parts:
|
||||
return "没有可更新的数据", 400
|
||||
|
||||
# 构建新的数据字符串
|
||||
data_value = "|###|".join(data_parts)
|
||||
|
||||
# 构造更新数据
|
||||
updated_data = {
|
||||
'data': data_value,
|
||||
'image': original_doc.get('image', '') # 保持原图片
|
||||
}
|
||||
|
||||
# 更新文档
|
||||
if update_by_id(doc_id, updated_data):
|
||||
return redirect(url_for('show_all'))
|
||||
else:
|
||||
return "更新失败", 500
|
||||
|
||||
# 删除数据路由
|
||||
@app.route('/delete/<doc_id>', methods=['POST'])
|
||||
def delete_entry(doc_id):
|
||||
"""
|
||||
根据文档ID删除数据
|
||||
|
||||
参数:
|
||||
doc_id (str): 要删除的文档ID
|
||||
|
||||
返回:
|
||||
重定向到所有数据页面或错误信息
|
||||
"""
|
||||
if delete_by_id(doc_id):
|
||||
return redirect(url_for('show_all'))
|
||||
else:
|
||||
return "删除失败", 500
|
||||
|
||||
# 批量删除数据路由
|
||||
@app.route('/batch_delete', methods=['POST'])
|
||||
def batch_delete():
|
||||
"""
|
||||
批量删除数据
|
||||
|
||||
返回:
|
||||
重定向到所有数据页面或错误信息
|
||||
"""
|
||||
doc_ids = request.form.getlist('doc_ids')
|
||||
if not doc_ids:
|
||||
return "没有选择要删除的文档", 400
|
||||
|
||||
success_count = 0
|
||||
for doc_id in doc_ids:
|
||||
if delete_by_id(doc_id):
|
||||
success_count += 1
|
||||
|
||||
if success_count == len(doc_ids):
|
||||
return redirect(url_for('show_all'))
|
||||
else:
|
||||
return f"成功删除 {success_count} 条记录,失败 {len(doc_ids) - success_count} 条", 500
|
||||
|
||||
|
||||
|
||||
# 提供图片访问的路由
|
||||
@app.route('/image/<filename>')
|
||||
def serve_image(filename):
|
||||
"""
|
||||
提供image目录下图片的访问服务
|
||||
|
||||
参数:
|
||||
filename (str): 图片文件名
|
||||
|
||||
返回:
|
||||
图片文件或404错误
|
||||
"""
|
||||
import os
|
||||
from flask import send_from_directory
|
||||
|
||||
# 确保文件存在
|
||||
image_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'image')
|
||||
if not os.path.exists(os.path.join(image_dir, filename)):
|
||||
return "图片不存在", 404
|
||||
|
||||
# 发送图片文件
|
||||
return send_from_directory(image_dir, filename)
|
||||
|
||||
# 主程序入口
|
||||
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.
|
||||
25
elastic/apps.py
Normal file
25
elastic/apps.py
Normal file
@@ -0,0 +1,25 @@
|
||||
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, start_daily_analytics_scheduler
|
||||
try:
|
||||
create_index_with_mapping()
|
||||
start_daily_analytics_scheduler()
|
||||
except Exception as e:
|
||||
print(f"❌ ES 初始化失败: {e}")
|
||||
50
elastic/documents.py
Normal file
50
elastic/documents.py
Normal file
@@ -0,0 +1,50 @@
|
||||
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)
|
||||
GLOBAL_INDEX = Index(GLOBAL_INDEX_NAME)
|
||||
GLOBAL_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'}})
|
||||
time = fields.DateField()
|
||||
|
||||
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列表应该只包含需要特殊处理的字段,或者可以完全省略
|
||||
# 因为我们已经显式定义了所有字段
|
||||
|
||||
@GLOBAL_INDEX.doc_type
|
||||
class GlobalDocument(Document):
|
||||
type_list = fields.KeywordField()
|
||||
|
||||
class Django:
|
||||
model = ElasticNews
|
||||
591
elastic/es_connect.py
Normal file
591
elastic/es_connect.py
Normal file
@@ -0,0 +1,591 @@
|
||||
"""
|
||||
Django版本的ES连接和操作模块
|
||||
迁移自Flask项目的ESConnect.py
|
||||
"""
|
||||
from elasticsearch import Elasticsearch
|
||||
from elasticsearch_dsl import connections
|
||||
import os
|
||||
import json
|
||||
import re
|
||||
from .documents import AchievementDocument, UserDocument, GlobalDocument
|
||||
from .indexes import ACHIEVEMENT_INDEX_NAME, USER_INDEX_NAME, GLOBAL_INDEX_NAME
|
||||
import hashlib
|
||||
import time
|
||||
from datetime import datetime, timezone, timedelta
|
||||
import threading
|
||||
|
||||
# 使用环境变量配置ES连接,默认为本机
|
||||
_ES_URL = os.environ.get('ELASTICSEARCH_URL', 'http://localhost:9200')
|
||||
if not (_ES_URL.startswith('http://') or _ES_URL.startswith('https://')):
|
||||
_ES_URL = 'http://' + _ES_URL
|
||||
connections.create_connection(hosts=[_ES_URL])
|
||||
|
||||
# 获取默认的ES客户端
|
||||
es = connections.get_connection()
|
||||
|
||||
DATA_INDEX_NAME = ACHIEVEMENT_INDEX_NAME
|
||||
USERS_INDEX_NAME = USER_INDEX_NAME
|
||||
GLOBAL_TYPES_INDEX_NAME = GLOBAL_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. 处理全局类型索引 ---
|
||||
if not es.indices.exists(index=GLOBAL_TYPES_INDEX_NAME):
|
||||
GlobalDocument.init()
|
||||
default_types = ['软著', '专利', '奖状']
|
||||
doc = GlobalDocument(type_list=default_types)
|
||||
doc.meta.id = 'types'
|
||||
doc.save()
|
||||
print(f"✅ 创建索引 {GLOBAL_TYPES_INDEX_NAME} 并写入默认类型")
|
||||
else:
|
||||
try:
|
||||
GlobalDocument.get(id='types')
|
||||
except Exception:
|
||||
default_types = ['软著', '专利', '奖状']
|
||||
doc = GlobalDocument(type_list=default_types)
|
||||
doc.meta.id = 'types'
|
||||
doc.save()
|
||||
print("ℹ️ 全局类型文档缺失,已补充默认类型")
|
||||
|
||||
# --- 4. 创建默认管理员用户(可选:也可检查用户是否已存在)---
|
||||
# 这里简单处理:每次初始化都写入(可能重复),建议加唯一性判断
|
||||
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_type_list():
|
||||
try:
|
||||
doc = GlobalDocument.get(id='types')
|
||||
lst = [str(t).strip().strip(';') for t in (doc.type_list or [])]
|
||||
return lst
|
||||
except Exception:
|
||||
return ['软著', '专利', '奖状']
|
||||
|
||||
def ensure_type_in_list(type_name: str):
|
||||
if not type_name:
|
||||
return False
|
||||
norm = str(type_name).strip().strip(';')
|
||||
try:
|
||||
try:
|
||||
doc = GlobalDocument.get(id='types')
|
||||
cur = list(doc.type_list or [])
|
||||
except Exception:
|
||||
cur = ['软著', '专利', '奖状']
|
||||
doc = GlobalDocument(type_list=cur)
|
||||
doc.meta.id = 'types'
|
||||
cur_sanitized = {str(t).strip().strip(';') for t in cur}
|
||||
if norm not in cur_sanitized:
|
||||
cur.append(norm)
|
||||
doc.type_list = cur
|
||||
doc.save()
|
||||
return True
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
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:
|
||||
achievement = AchievementDocument(
|
||||
writer_id=data.get('writer_id', ''),
|
||||
data=data.get('data', ''),
|
||||
image=data.get('image', ''),
|
||||
time=datetime.now(timezone.utc).isoformat()
|
||||
)
|
||||
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)
|
||||
print(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 []
|
||||
|
||||
ANALYTICS_CACHE = {"data": None, "ts": 0}
|
||||
|
||||
def _compute_hist(range_gte: str, interval: str, fmt: str):
|
||||
from elasticsearch_dsl import Search
|
||||
s = AchievementDocument.search()
|
||||
s = s.filter('range', time={'gte': range_gte, 'lte': 'now'})
|
||||
s = s.extra(size=0)
|
||||
s.aggs.bucket('b', 'date_histogram', field='time', calendar_interval=interval, format=fmt, min_doc_count=0)
|
||||
resp = s.execute()
|
||||
buckets = getattr(resp.aggs, 'b').buckets
|
||||
return [{"label": b.key_as_string, "count": b.doc_count} for b in buckets]
|
||||
|
||||
def _parse_type_from_data(data_str: str):
|
||||
try:
|
||||
obj = json.loads(data_str)
|
||||
if isinstance(obj, dict):
|
||||
for k in ("数据类型", "类型", "type"):
|
||||
if k in obj and obj.get(k):
|
||||
return str(obj.get(k)).strip().strip(';')
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
m = re.search(r'"数据类型"\s*:\s*"(.*?)"', data_str)
|
||||
if m:
|
||||
return str(m.group(1)).strip().strip(';')
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
def _compute_type_counts_dynamic(range_gte: str):
|
||||
s = AchievementDocument.search()
|
||||
s = s.filter('range', time={'gte': range_gte, 'lte': 'now'})
|
||||
s = s.query('match_all')
|
||||
counts_map = {}
|
||||
for hit in s.scan():
|
||||
t = _parse_type_from_data(getattr(hit, 'data', '') or '')
|
||||
if not t:
|
||||
continue
|
||||
counts_map[t] = counts_map.get(t, 0) + 1
|
||||
try:
|
||||
ensure_type_in_list(t)
|
||||
except Exception:
|
||||
pass
|
||||
return [{"type": k, "count": int(v)} for k, v in counts_map.items()]
|
||||
|
||||
def compute_analytics():
|
||||
days = _compute_hist('now-10d/d', 'day', 'yyyy-MM-dd')
|
||||
weeks = _compute_hist('now-10w/w', 'week', 'yyyy-ww')
|
||||
months = _compute_hist('now-10M/M', 'month', 'yyyy-MM')
|
||||
pie_1m = _compute_type_counts_dynamic('now-1M/M')
|
||||
pie_12m = _compute_type_counts_dynamic('now-12M/M')
|
||||
return {
|
||||
"last_10_days": days[-10:],
|
||||
"last_10_weeks": weeks[-10:],
|
||||
"last_10_months": months[-10:],
|
||||
"type_pie_1m": pie_1m,
|
||||
"type_pie_12m": pie_12m,
|
||||
}
|
||||
|
||||
def get_analytics_overview(force: bool = False):
|
||||
now_ts = time.time()
|
||||
if force or ANALYTICS_CACHE["data"] is None or (now_ts - ANALYTICS_CACHE["ts"]) > 3600:
|
||||
ANALYTICS_CACHE["data"] = compute_analytics()
|
||||
ANALYTICS_CACHE["ts"] = now_ts
|
||||
return ANALYTICS_CACHE["data"]
|
||||
|
||||
def _seconds_until_hour(h: int):
|
||||
now = datetime.now()
|
||||
tgt = now.replace(hour=h, minute=0, second=0, microsecond=0)
|
||||
if tgt <= now:
|
||||
tgt = tgt + timedelta(days=1)
|
||||
return max(0, int((tgt - now).total_seconds()))
|
||||
|
||||
def start_daily_analytics_scheduler():
|
||||
def _run_and_reschedule():
|
||||
try:
|
||||
get_analytics_overview(force=True)
|
||||
except Exception as e:
|
||||
print(f"分析任务失败: {e}")
|
||||
finally:
|
||||
threading.Timer(24 * 3600, _run_and_reschedule).start()
|
||||
delay = _seconds_until_hour(3)
|
||||
threading.Timer(delay, _run_and_reschedule).start()
|
||||
|
||||
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_id(user_id):
|
||||
try:
|
||||
search = UserDocument.search()
|
||||
search = search.query("term", user_id=user_id)
|
||||
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_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 get_user_by_id(user_id):
|
||||
try:
|
||||
search = UserDocument.search()
|
||||
search = search.query("term", user_id=int(user_id))
|
||||
response = search.execute()
|
||||
if response.hits:
|
||||
hit = response.hits[0]
|
||||
return {
|
||||
"user_id": hit.user_id,
|
||||
"username": hit.username,
|
||||
"permission": hit.permission,
|
||||
}
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"获取用户数据失败: {str(e)}")
|
||||
return None
|
||||
|
||||
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
|
||||
|
||||
def delete_user_by_id(user_id):
|
||||
try:
|
||||
search = UserDocument.search()
|
||||
search = search.query("term", user_id=int(user_id))
|
||||
response = search.execute()
|
||||
if response.hits:
|
||||
user = response.hits[0]
|
||||
user.delete()
|
||||
return True
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"删除用户失败: {str(e)}")
|
||||
return False
|
||||
|
||||
def update_user_by_id(user_id, username=None, permission=None, password=None):
|
||||
try:
|
||||
search = UserDocument.search()
|
||||
search = search.query("term", user_id=int(user_id))
|
||||
response = search.execute()
|
||||
if response.hits:
|
||||
user = response.hits[0]
|
||||
if username is not None:
|
||||
user.username = username
|
||||
if permission is not None:
|
||||
user.permission = int(permission)
|
||||
if password is not None:
|
||||
user.password = password
|
||||
user.save()
|
||||
return True
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"更新用户失败: {str(e)}")
|
||||
return False
|
||||
5
elastic/indexes.py
Normal file
5
elastic/indexes.py
Normal file
@@ -0,0 +1,5 @@
|
||||
INDEX_NAME = "wordsearch266666"
|
||||
USER_NAME = "users11111"
|
||||
ACHIEVEMENT_INDEX_NAME = INDEX_NAME
|
||||
USER_INDEX_NAME = USER_NAME
|
||||
GLOBAL_INDEX_NAME = "global11111"
|
||||
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
|
||||
727
elastic/templates/elastic/manage.html
Normal file
727
elastic/templates/elastic/manage.html
Normal file
@@ -0,0 +1,727 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>数据管理</title>
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
|
||||
background: #fafafa;
|
||||
}
|
||||
|
||||
/* 导航栏样式 */
|
||||
.sidebar {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 180px;
|
||||
height: 100vh;
|
||||
background: #1e1e2e;
|
||||
color: white;
|
||||
padding: 20px;
|
||||
box-shadow: 2px 0 5px rgba(0,0,0,0.1);
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.user-id {
|
||||
text-align: center;
|
||||
margin-bottom: auto;
|
||||
}
|
||||
|
||||
.sidebar h3 {
|
||||
margin-top: 0;
|
||||
font-size: 18px;
|
||||
color: #ff79c6;
|
||||
text-align: center;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.navigation-links {
|
||||
width: 100%;
|
||||
margin-top: 60px;
|
||||
}
|
||||
|
||||
.sidebar a,
|
||||
.sidebar button {
|
||||
display: block;
|
||||
color: #8be9fd;
|
||||
text-decoration: none;
|
||||
margin: 10px 0;
|
||||
font-size: 16px;
|
||||
padding: 15px;
|
||||
border-radius: 4px;
|
||||
background: transparent;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
width: calc(100% - 40px);
|
||||
text-align: left;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.sidebar a:hover,
|
||||
.sidebar button:hover {
|
||||
color: #ff79c6;
|
||||
background-color: rgba(139, 233, 253, 0.2);
|
||||
}
|
||||
|
||||
/* 主内容区 */
|
||||
.main-content {
|
||||
margin-left: 200px;
|
||||
padding: 20px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
/* 原有样式保持不变 */
|
||||
.container {
|
||||
max-width: 1200px;
|
||||
margin: 0 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;
|
||||
margin-top: 20px;
|
||||
}
|
||||
th, td {
|
||||
border-bottom: 1px solid #eee;
|
||||
padding: 12px 8px;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
th {
|
||||
background-color: #f8f9fa;
|
||||
font-weight: 600;
|
||||
}
|
||||
img {
|
||||
max-width: 120px;
|
||||
border: 1px solid #eee;
|
||||
border-radius: 6px;
|
||||
}
|
||||
.btn {
|
||||
padding: 6px 10px;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
margin: 2px;
|
||||
}
|
||||
.btn-primary {
|
||||
background: #1677ff;
|
||||
color: #fff;
|
||||
}
|
||||
.btn-danger {
|
||||
background: #ff4d4f;
|
||||
color: #fff;
|
||||
}
|
||||
.btn-secondary {
|
||||
background: #f0f0f0;
|
||||
color: #333;
|
||||
}
|
||||
.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;
|
||||
z-index: 1000;
|
||||
}
|
||||
.modal .dialog {
|
||||
width: 720px;
|
||||
max-width: 92vw;
|
||||
background: #fff;
|
||||
border-radius: 10px;
|
||||
padding: 20px;
|
||||
max-height: 80vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
textarea {
|
||||
width: 100%;
|
||||
min-height: 240px;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 14px;
|
||||
padding: 10px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
resize: vertical;
|
||||
}
|
||||
#kvForm {
|
||||
border: 1px solid #eee;
|
||||
border-radius: 6px;
|
||||
padding: 8px;
|
||||
max-height: 300px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
/* 搜索区域样式 */
|
||||
.search-container {
|
||||
background: #f8f9fa;
|
||||
padding: 15px;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.search-controls {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.search-input {
|
||||
flex: 1;
|
||||
min-width: 200px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
}
|
||||
.search-result {
|
||||
margin-top: 10px;
|
||||
padding: 10px;
|
||||
background: #e8f4ff;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
}
|
||||
.search-result.empty {
|
||||
background: #fff8e8;
|
||||
}
|
||||
.search-result.error {
|
||||
background: #ffe8e8;
|
||||
}
|
||||
|
||||
/* 加载动画 */
|
||||
.loading {
|
||||
display: inline-block;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border: 3px solid #f3f3f3;
|
||||
border-top: 3px solid #1677ff;
|
||||
border-radius: 50%;
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* 响应式调整 */
|
||||
@media (max-width: 768px) {
|
||||
.search-controls {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
.search-input {
|
||||
min-width: auto;
|
||||
}
|
||||
.btn {
|
||||
width: 100%;
|
||||
margin: 2px 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!-- 左侧固定栏目 -->
|
||||
<div class="sidebar">
|
||||
<div class="user-id">
|
||||
<h3>用户ID:{{ user_id }}</h3>
|
||||
</div>
|
||||
<div class="navigation-links">
|
||||
<a href="{% url 'main:home' %}">主页</a>
|
||||
<button id="logoutBtn">退出登录</button>
|
||||
<div id="logoutMsg"></div>
|
||||
{% csrf_token %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 主内容区域 -->
|
||||
<div class="main-content">
|
||||
<div class="container">
|
||||
<h2>数据管理</h2>
|
||||
<p class="muted">仅管理员可见。可查看、编辑、删除所有记录。</p>
|
||||
|
||||
<!-- 搜索功能区域 -->
|
||||
<div class="search-container">
|
||||
<div class="search-controls">
|
||||
<input type="text" id="searchQuery" class="search-input" placeholder="请输入搜索关键词...">
|
||||
<button class="btn btn-primary" onclick="performSearch('exact')">关键词搜索</button>
|
||||
<button class="btn btn-secondary" onclick="performSearch('fuzzy')">模糊搜索</button>
|
||||
<button class="btn" onclick="loadAllData()">显示全部</button>
|
||||
<button class="btn" onclick="clearSearch()">清空结果</button>
|
||||
</div>
|
||||
|
||||
<div id="searchResult" class="search-result" style="display: none;">
|
||||
<div id="searchStatus">正在搜索...</div>
|
||||
<div id="searchCount" style="margin-top: 5px; font-weight: bold;"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 数据表格 -->
|
||||
<table id="dataTable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>图片</th>
|
||||
<th>数据</th>
|
||||
<th>作者</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="tableBody">
|
||||
<!-- 数据将通过JavaScript动态加载 -->
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<!-- 编辑模态框 -->
|
||||
<div id="editModal" 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>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// 获取CSRF token的函数
|
||||
function getCookie(name) {
|
||||
const value = `; ${document.cookie}`;
|
||||
const parts = value.split(`; ${name}=`);
|
||||
if (parts.length === 2) return parts.pop().split(';').shift();
|
||||
}
|
||||
|
||||
// DOM元素引用
|
||||
const searchQueryInput = document.getElementById('searchQuery');
|
||||
const searchResultDiv = document.getElementById('searchResult');
|
||||
const searchStatus = document.getElementById('searchStatus');
|
||||
const searchCount = document.getElementById('searchCount');
|
||||
const tableBody = document.getElementById('tableBody');
|
||||
const editModal = document.getElementById('editModal');
|
||||
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 = '';
|
||||
let allDataCache = []; // 缓存所有数据,避免重复请求
|
||||
|
||||
// 搜索功能
|
||||
async function performSearch(type) {
|
||||
const query = searchQueryInput.value.trim();
|
||||
if (!query) {
|
||||
showSearchMessage('请输入搜索关键词', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
showSearchLoading();
|
||||
|
||||
try {
|
||||
let url;
|
||||
if (type === 'exact') {
|
||||
url = `/elastic/search/?q=${encodeURIComponent(query)}`;
|
||||
} else if (type === 'fuzzy') {
|
||||
url = `/elastic/fuzzy-search/?keyword=${encodeURIComponent(query)}`;
|
||||
}
|
||||
|
||||
const response = await fetch(url);
|
||||
const data = await response.json();
|
||||
|
||||
if (data.status === 'success') {
|
||||
displaySearchResults(data.data || []);
|
||||
} else {
|
||||
showSearchMessage(`搜索失败: ${data.message || '未知错误'}`, 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('搜索请求失败:', error);
|
||||
showSearchMessage('搜索请求失败,请检查网络连接', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// 显示加载状态
|
||||
function showSearchLoading() {
|
||||
searchResultDiv.style.display = 'block';
|
||||
searchResultDiv.className = 'search-result';
|
||||
searchStatus.innerHTML = '<span class="loading"></span> 正在搜索...';
|
||||
searchCount.textContent = '';
|
||||
}
|
||||
|
||||
// 显示搜索结果
|
||||
function displaySearchResults(results) {
|
||||
if (results.length === 0) {
|
||||
showSearchMessage('未找到匹配的结果', 'empty');
|
||||
renderTable([]);
|
||||
return;
|
||||
}
|
||||
|
||||
searchResultDiv.style.display = 'block';
|
||||
searchResultDiv.className = 'search-result';
|
||||
searchStatus.textContent = `找到 ${results.length} 条匹配结果`;
|
||||
searchCount.textContent = `显示 ${results.length} 条记录`;
|
||||
|
||||
renderTable(results);
|
||||
}
|
||||
|
||||
// 显示搜索消息
|
||||
function showSearchMessage(message, type = '') {
|
||||
searchResultDiv.style.display = 'block';
|
||||
searchResultDiv.className = `search-result ${type}`;
|
||||
searchStatus.textContent = message;
|
||||
searchCount.textContent = '';
|
||||
}
|
||||
|
||||
// 加载所有数据
|
||||
async function loadAllData() {
|
||||
showSearchLoading();
|
||||
|
||||
try {
|
||||
// 如果已有缓存,直接使用
|
||||
if (allDataCache.length > 0) {
|
||||
displayAllData(allDataCache);
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await fetch('/elastic/all-data/');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.status === 'success') {
|
||||
allDataCache = data.data || [];
|
||||
displayAllData(allDataCache);
|
||||
} else {
|
||||
showSearchMessage(`加载数据失败: ${data.message || '未知错误'}`, 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载数据失败:', error);
|
||||
showSearchMessage('加载数据失败,请检查网络连接', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// 显示所有数据
|
||||
function displayAllData(data) {
|
||||
searchResultDiv.style.display = 'block';
|
||||
searchResultDiv.className = 'search-result';
|
||||
searchStatus.textContent = '显示全部数据';
|
||||
searchCount.textContent = `共 ${data.length} 条记录`;
|
||||
|
||||
renderTable(data);
|
||||
}
|
||||
|
||||
// 清空搜索结果
|
||||
function clearSearch() {
|
||||
searchQueryInput.value = '';
|
||||
searchResultDiv.style.display = 'none';
|
||||
|
||||
// 如果有缓存数据,显示全部
|
||||
if (allDataCache.length > 0) {
|
||||
renderTable(allDataCache);
|
||||
} else {
|
||||
// 否则重新加载
|
||||
loadAllData();
|
||||
}
|
||||
}
|
||||
|
||||
// 渲染表格
|
||||
function renderTable(data) {
|
||||
tableBody.innerHTML = '';
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = '<td colspan="5" style="text-align: center; color: #999;">暂无数据</td>';
|
||||
tableBody.appendChild(row);
|
||||
return;
|
||||
}
|
||||
|
||||
data.forEach(item => {
|
||||
const row = document.createElement('tr');
|
||||
row.setAttribute('data-id', item._id || item.id);
|
||||
row.setAttribute('data-writer', item.writer_id);
|
||||
row.setAttribute('data-image', item.image);
|
||||
|
||||
// 解析data字段,如果是JSON字符串则格式化显示
|
||||
let displayData = item.data || '';
|
||||
try {
|
||||
const parsed = JSON.parse(item.data);
|
||||
displayData = JSON.stringify(parsed, null, 2);
|
||||
} catch (e) {
|
||||
// 如果不是JSON,直接显示原字符串
|
||||
}
|
||||
|
||||
row.innerHTML = `
|
||||
<td style="max-width:140px; word-break:break-all; font-size: 12px;">${item._id || item.id || ''}</td>
|
||||
<td>
|
||||
${item.image ? `<img src="/media/${item.image}" onerror="this.src=''; this.alt='图片加载失败'" />` : '无图片'}
|
||||
</td>
|
||||
<td>
|
||||
<pre style="white-space:pre-wrap; word-wrap:break-word; max-height: 100px; overflow-y: auto; font-size: 12px; margin: 0;">${escapeHtml(displayData)}</pre>
|
||||
</td>
|
||||
<td style="font-size: 12px;">${item.writer_id || ''}</td>
|
||||
<td>
|
||||
<button class="btn btn-primary" onclick="openEdit('${item._id || item.id}')">编辑</button>
|
||||
<button class="btn btn-danger" onclick="doDelete('${item._id || item.id}')">删除</button>
|
||||
</td>
|
||||
`;
|
||||
tableBody.appendChild(row);
|
||||
});
|
||||
}
|
||||
|
||||
// 转义HTML以防止XSS
|
||||
function escapeHtml(unsafe) {
|
||||
return unsafe
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
// 编辑功能相关
|
||||
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=()=>{
|
||||
if (kvForm.children.length > 1) { // 至少保留一行
|
||||
kvForm.removeChild(row);
|
||||
syncTextarea();
|
||||
} else {
|
||||
kI.value = '';
|
||||
vI.value = '';
|
||||
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(){
|
||||
try {
|
||||
resultBox.value = JSON.stringify(formToObject(), null, 2);
|
||||
} catch (e) {
|
||||
resultBox.value = '{}';
|
||||
}
|
||||
}
|
||||
|
||||
// 事件绑定
|
||||
addFieldBtn.onclick = ()=>{
|
||||
kvForm.appendChild(createRow());
|
||||
syncTextarea();
|
||||
};
|
||||
|
||||
syncFromTextBtn.onclick = ()=>{
|
||||
try{
|
||||
const obj = JSON.parse(resultBox.value||'{}');
|
||||
renderForm(obj);
|
||||
editMsg.textContent = '已从文本区刷新表单';
|
||||
setTimeout(() => editMsg.textContent = '', 2000);
|
||||
}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(d.message || '获取失败');
|
||||
const rec=d.data||{};
|
||||
const dataStr = rec.data || '{}';
|
||||
let obj={};
|
||||
try{
|
||||
obj = typeof dataStr==='string'? JSON.parse(dataStr): (dataStr||{});
|
||||
}catch(_){
|
||||
obj={};
|
||||
}
|
||||
renderForm(obj);
|
||||
editModal.style.display='flex';
|
||||
}).catch(e=>{
|
||||
alert(e.message||'获取数据失败');
|
||||
});
|
||||
}
|
||||
|
||||
function closeModal(){
|
||||
editModal.style.display='none';
|
||||
currentId='';
|
||||
}
|
||||
|
||||
async function saveEdit(){
|
||||
const body = {
|
||||
writer_id: currentWriter,
|
||||
data: resultBox.value, // 直接使用textarea中的值
|
||||
image: currentImage,
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch(`/elastic/data/${currentId}/update/`, {
|
||||
method:'PUT',
|
||||
credentials:'same-origin',
|
||||
headers:{
|
||||
'Content-Type':'application/json',
|
||||
'X-CSRFToken': getCookie('csrftoken')||''
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if(data.status!=='success') throw new Error(data.message || '保存失败');
|
||||
|
||||
alert('保存成功');
|
||||
closeModal();
|
||||
// 重新加载数据以显示更新
|
||||
if (searchResultDiv.style.display !== 'none') {
|
||||
// 如果当前显示的是搜索结果,重新执行搜索
|
||||
const query = searchQueryInput.value.trim();
|
||||
if (query) {
|
||||
const isFuzzy = document.querySelector('.search-result').textContent.includes('模糊');
|
||||
performSearch(isFuzzy ? 'fuzzy' : 'exact');
|
||||
} else {
|
||||
loadAllData();
|
||||
}
|
||||
} else {
|
||||
loadAllData();
|
||||
}
|
||||
} catch (e) {
|
||||
editMsg.textContent = e.message||'保存失败';
|
||||
}
|
||||
}
|
||||
|
||||
async function doDelete(id){
|
||||
if(!confirm('确认删除该记录?此操作不可撤销')) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/elastic/data/${id}/delete/`, {
|
||||
method:'DELETE',
|
||||
credentials:'same-origin',
|
||||
headers:{ 'X-CSRFToken': getCookie('csrftoken')||'' }
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if(data.status!=='success') throw new Error(data.message || '删除失败');
|
||||
|
||||
alert('删除成功');
|
||||
// 重新加载数据
|
||||
if (searchResultDiv.style.display !== 'none') {
|
||||
const query = searchQueryInput.value.trim();
|
||||
if (query) {
|
||||
const isFuzzy = document.querySelector('.search-result').textContent.includes('模糊');
|
||||
performSearch(isFuzzy ? 'fuzzy' : 'exact');
|
||||
} else {
|
||||
loadAllData();
|
||||
}
|
||||
} else {
|
||||
loadAllData();
|
||||
}
|
||||
} catch (e) {
|
||||
alert(e.message||'删除失败');
|
||||
}
|
||||
}
|
||||
|
||||
// 页面加载时自动加载所有数据
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
loadAllData();
|
||||
});
|
||||
|
||||
// 退出登录处理
|
||||
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>
|
||||
</body>
|
||||
</html>
|
||||
359
elastic/templates/elastic/upload.html
Normal file
359
elastic/templates/elastic/upload.html
Normal file
@@ -0,0 +1,359 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>图片上传与识别</title>
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
|
||||
background: #fafafa;
|
||||
}
|
||||
|
||||
/* 导航栏样式 */
|
||||
.sidebar {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 180px;
|
||||
height: 100vh;
|
||||
background: #1e1e2e;
|
||||
color: white;
|
||||
padding: 20px;
|
||||
box-shadow: 2px 0 5px rgba(0,0,0,0.1);
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.user-id {
|
||||
text-align: center;
|
||||
margin-bottom: auto;
|
||||
}
|
||||
|
||||
.sidebar h3 {
|
||||
margin-top: 0;
|
||||
font-size: 18px;
|
||||
color: #ff79c6;
|
||||
text-align: center;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.navigation-links {
|
||||
width: 100%;
|
||||
margin-top: 60px;
|
||||
}
|
||||
|
||||
.sidebar a,
|
||||
.sidebar button {
|
||||
display: block;
|
||||
color: #8be9fd;
|
||||
text-decoration: none;
|
||||
margin: 10px 0;
|
||||
font-size: 16px;
|
||||
padding: 15px;
|
||||
border-radius: 4px;
|
||||
background: transparent;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
width: calc(100% - 40px);
|
||||
text-align: left;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.sidebar a:hover,
|
||||
.sidebar button:hover {
|
||||
color: #ff79c6;
|
||||
background-color: rgba(139, 233, 253, 0.2);
|
||||
}
|
||||
|
||||
/* 主内容区 */
|
||||
.main-content {
|
||||
margin-left: 200px;
|
||||
padding: 20px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
/* 原有样式保持不变 */
|
||||
.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="sidebar">
|
||||
<div class="user-id">
|
||||
<h3>用户ID:{{ user_id }}</h3>
|
||||
</div>
|
||||
<div class="navigation-links">
|
||||
<a href="{% url 'main:home' %}">主页</a>
|
||||
<button id="logoutBtn">退出登录</button>
|
||||
<div id="logoutMsg"></div>
|
||||
{% csrf_token %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 主内容区域 -->
|
||||
<div class="main-content">
|
||||
<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>
|
||||
</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;
|
||||
});
|
||||
|
||||
// 退出登录处理
|
||||
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>
|
||||
</body>
|
||||
</html>
|
||||
644
elastic/templates/elastic/users.html
Normal file
644
elastic/templates/elastic/users.html
Normal file
@@ -0,0 +1,644 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>用户管理</title>
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
|
||||
background: #fafafa;
|
||||
}
|
||||
|
||||
/* 导航栏样式 */
|
||||
.sidebar {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 180px;
|
||||
height: 100vh;
|
||||
background: #1e1e2e;
|
||||
color: white;
|
||||
padding: 20px;
|
||||
box-shadow: 2px 0 5px rgba(0,0,0,0.1);
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.user-id {
|
||||
text-align: center;
|
||||
margin-bottom: auto;
|
||||
}
|
||||
|
||||
.sidebar h3 {
|
||||
margin-top: 0;
|
||||
font-size: 18px;
|
||||
color: #ff79c6;
|
||||
text-align: center;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.navigation-links {
|
||||
width: 100%;
|
||||
margin-top: 60px;
|
||||
}
|
||||
|
||||
.sidebar a,
|
||||
.sidebar button {
|
||||
display: block;
|
||||
color: #8be9fd;
|
||||
text-decoration: none;
|
||||
margin: 10px 0;
|
||||
font-size: 16px;
|
||||
padding: 15px;
|
||||
border-radius: 4px;
|
||||
background: transparent;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
width: calc(100% - 40px);
|
||||
text-align: left;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.sidebar a:hover,
|
||||
.sidebar button:hover {
|
||||
color: #ff79c6;
|
||||
background-color: rgba(139, 233, 253, 0.2);
|
||||
}
|
||||
|
||||
/* 主内容区 */
|
||||
.main-content {
|
||||
margin-left: 200px;
|
||||
padding: 20px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: #fff;
|
||||
border-radius: 14px;
|
||||
box-shadow: 0 10px 24px rgba(31,35,40,0.08);
|
||||
padding: 20px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 8px 12px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
margin: 0 4px;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: #4f46e5;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background: #ef4444;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.btn-success {
|
||||
background: #22c55e;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.table-container {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
th, td {
|
||||
padding: 12px 15px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
th {
|
||||
background-color: #f9fafb;
|
||||
font-weight: bold;
|
||||
color: #374151;
|
||||
}
|
||||
|
||||
tr:hover {
|
||||
background-color: #f3f4f6;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
margin-bottom: 5px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.form-group input, .form-group select {
|
||||
width: 100%;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #d1d5db;
|
||||
border-radius: 6px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.form-row {
|
||||
display: flex;
|
||||
gap: 15px;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.form-row .form-group {
|
||||
flex: 1;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.action-buttons {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.search-container {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.search-container input {
|
||||
flex: 1;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #d1d5db;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.search-container button {
|
||||
padding: 8px 15px;
|
||||
background: #4f46e5;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.modal {
|
||||
display: none;
|
||||
position: fixed;
|
||||
z-index: 2000;
|
||||
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: 20px;
|
||||
border-radius: 8px;
|
||||
width: 80%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.close {
|
||||
color: #aaa;
|
||||
float: right;
|
||||
font-size: 28px;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.close:hover {
|
||||
color: black;
|
||||
}
|
||||
|
||||
.notification {
|
||||
padding: 10px;
|
||||
margin-bottom: 15px;
|
||||
border-radius: 4px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.notification.success {
|
||||
background-color: #d4edda;
|
||||
color: #155724;
|
||||
border: 1px solid #c3e6cb;
|
||||
}
|
||||
|
||||
.notification.error {
|
||||
background-color: #f8d7da;
|
||||
color: #721c24;
|
||||
border: 1px solid #f5c6cb;
|
||||
}
|
||||
|
||||
.nav-error {
|
||||
color: #ef4444;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!-- 左侧固定栏目 -->
|
||||
<div class="sidebar">
|
||||
<div class="user-id">
|
||||
<h3>用户ID:{{ user_id }}</h3>
|
||||
</div>
|
||||
<div class="navigation-links">
|
||||
<a href="{% url 'main:home' %}" onclick="return handleNavClick(this, '/');">主页</a>
|
||||
<button id="logoutBtn">退出登录</button>
|
||||
<div id="logoutMsg"></div>
|
||||
{% csrf_token %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 主内容区域 -->
|
||||
<div class="main-content">
|
||||
<div class="card">
|
||||
<div class="header">
|
||||
<h2>用户管理</h2>
|
||||
<button id="addUserBtn" class="btn btn-primary">添加用户</button>
|
||||
</div>
|
||||
|
||||
<div class="notification success" id="successNotification">
|
||||
操作成功!
|
||||
</div>
|
||||
<div class="notification error" id="errorNotification">
|
||||
操作失败!
|
||||
</div>
|
||||
|
||||
<div class="search-container">
|
||||
<input type="text" id="searchInput" placeholder="搜索用户名...">
|
||||
<button id="searchBtn">搜索</button>
|
||||
<button id="resetBtn">重置</button>
|
||||
</div>
|
||||
|
||||
<div class="table-container">
|
||||
<table id="usersTable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>用户ID</th>
|
||||
<th>用户名</th>
|
||||
<th>权限</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="usersTableBody">
|
||||
<!-- 用户数据将通过JavaScript加载 -->
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 添加/编辑用户模态框 -->
|
||||
<div id="userModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<span class="close">×</span>
|
||||
<h2 id="modalTitle">添加用户</h2>
|
||||
<form id="userForm">
|
||||
<input type="hidden" id="userId" name="user_id">
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label for="username">用户名</label>
|
||||
<input type="text" id="username" name="username" required>
|
||||
</div>
|
||||
<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>
|
||||
<div class="form-group">
|
||||
<label for="password">密码</label>
|
||||
<input type="password" id="password" name="password" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="confirmPassword">确认密码</label>
|
||||
<input type="password" id="confirmPassword" name="confirmPassword" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">保存</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 确认删除模态框 -->
|
||||
<div id="deleteModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<span class="close">×</span>
|
||||
<h2>确认删除</h2>
|
||||
<p>确定要删除用户 <strong id="deleteUserName"></strong> 吗?此操作不可撤销。</p>
|
||||
<input type="hidden" id="deleteUserId">
|
||||
<button id="confirmDeleteBtn" class="btn btn-danger">确认删除</button>
|
||||
<button class="btn">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// 获取CSRF令牌的函数
|
||||
function getCookie(name) {
|
||||
const value = `; ${document.cookie}`;
|
||||
const parts = value.split(`; ${name}=`);
|
||||
if (parts.length === 2) return parts.pop().split(';').shift();
|
||||
}
|
||||
|
||||
// 导航点击处理函数,提供备用URL
|
||||
function handleNavClick(element, fallbackUrl) {
|
||||
// 尝试使用Django模板生成的URL,如果失败则使用备用URL
|
||||
try {
|
||||
// 如果模板渲染正常,直接返回true让默认行为处理
|
||||
return true;
|
||||
} catch (e) {
|
||||
// 如果模板渲染有问题,使用备用URL
|
||||
window.location.href = fallbackUrl;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 显示通知
|
||||
function showNotification(message, isSuccess = true) {
|
||||
const notification = isSuccess ?
|
||||
document.getElementById('successNotification') :
|
||||
document.getElementById('errorNotification');
|
||||
|
||||
notification.textContent = message;
|
||||
notification.style.display = 'block';
|
||||
|
||||
setTimeout(() => {
|
||||
notification.style.display = 'none';
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// 获取所有用户
|
||||
async function loadUsers(searchTerm = '') {
|
||||
try {
|
||||
const url = searchTerm ?
|
||||
`/elastic/users/?search=${encodeURIComponent(searchTerm)}` :
|
||||
'/elastic/users/';
|
||||
|
||||
const response = await fetch(url);
|
||||
const result = await response.json();
|
||||
|
||||
if (result.status === 'success') {
|
||||
const tbody = document.getElementById('usersTableBody');
|
||||
tbody.innerHTML = '';
|
||||
|
||||
// 处理不同格式的API响应
|
||||
const users = result.data || result.users || [];
|
||||
|
||||
users.forEach(user => {
|
||||
const row = document.createElement('tr');
|
||||
|
||||
// 根据权限值显示权限名称
|
||||
const permissionText = user.permission === 0 ? '管理员' : '普通用户';
|
||||
|
||||
row.innerHTML = `
|
||||
<td>${user.user_id}</td>
|
||||
<td>${user.username}</td>
|
||||
<td>${permissionText}</td>
|
||||
<td class="action-buttons">
|
||||
<button class="btn btn-success edit-btn" data-user='${JSON.stringify(user)}'>编辑</button>
|
||||
<button class="btn btn-danger delete-btn" data-username="${user.username}" data-userid="${user.user_id}">删除</button>
|
||||
</td>
|
||||
`;
|
||||
|
||||
tbody.appendChild(row);
|
||||
});
|
||||
} else {
|
||||
showNotification('获取用户列表失败', false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载用户列表失败:', error);
|
||||
showNotification('获取用户列表失败', false);
|
||||
}
|
||||
}
|
||||
|
||||
// 打开添加用户模态框
|
||||
function openAddModal() {
|
||||
document.getElementById('modalTitle').textContent = '添加用户';
|
||||
document.getElementById('userForm').reset();
|
||||
document.getElementById('userId').value = '';
|
||||
document.getElementById('password').required = true;
|
||||
document.getElementById('confirmPassword').required = true;
|
||||
document.getElementById('userModal').style.display = 'block';
|
||||
}
|
||||
|
||||
// 打开编辑用户模态框
|
||||
function openEditModal(user) {
|
||||
document.getElementById('modalTitle').textContent = '编辑用户';
|
||||
document.getElementById('username').value = user.username;
|
||||
document.getElementById('userId').value = user.user_id;
|
||||
document.getElementById('permission').value = user.permission;
|
||||
document.getElementById('password').required = false;
|
||||
document.getElementById('confirmPassword').required = false;
|
||||
document.getElementById('userModal').style.display = 'block';
|
||||
}
|
||||
|
||||
// 打开删除确认模态框
|
||||
function openDeleteModal(username, userId) {
|
||||
document.getElementById('deleteUserName').textContent = username;
|
||||
document.getElementById('deleteUserId').value = userId;
|
||||
document.getElementById('deleteModal').style.display = 'block';
|
||||
}
|
||||
|
||||
// 保存用户(添加或编辑)
|
||||
async function saveUser(event) {
|
||||
event.preventDefault();
|
||||
|
||||
const formData = new FormData(event.target);
|
||||
const userId = formData.get('user_id');
|
||||
const username = formData.get('username');
|
||||
const permission = formData.get('permission');
|
||||
const password = formData.get('password');
|
||||
const confirmPassword = formData.get('confirmPassword');
|
||||
|
||||
// 验证密码
|
||||
if (password !== confirmPassword) {
|
||||
showNotification('密码和确认密码不匹配', false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 验证密码长度(如果提供了密码)
|
||||
if (password && password.length < 6) {
|
||||
showNotification('密码长度至少为6位', false);
|
||||
return;
|
||||
}
|
||||
|
||||
const data = {
|
||||
username: username,
|
||||
permission: parseInt(permission)
|
||||
};
|
||||
|
||||
if (password) {
|
||||
data.password = password;
|
||||
}
|
||||
|
||||
try {
|
||||
const csrftoken = getCookie('csrftoken');
|
||||
let response;
|
||||
|
||||
if (userId) {
|
||||
// 更新用户
|
||||
response = await fetch(`/elastic/users/${userId}/update/`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRFToken': csrftoken
|
||||
},
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
} else {
|
||||
// 添加用户
|
||||
response = await fetch('/elastic/users/add/', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRFToken': csrftoken
|
||||
},
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.status === 'success') {
|
||||
showNotification(userId ? '用户更新成功' : '用户添加成功');
|
||||
document.getElementById('userModal').style.display = 'none';
|
||||
loadUsers();
|
||||
} else {
|
||||
showNotification(result.message || '操作失败', false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('保存用户失败:', error);
|
||||
showNotification('保存用户失败', false);
|
||||
}
|
||||
}
|
||||
|
||||
// 删除用户
|
||||
async function deleteUser() {
|
||||
const userId = document.getElementById('deleteUserId').value;
|
||||
|
||||
try {
|
||||
const csrftoken = getCookie('csrftoken');
|
||||
const response = await fetch(`/elastic/users/${userId}/delete/`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRFToken': csrftoken
|
||||
}
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.status === 'success') {
|
||||
showNotification('用户删除成功');
|
||||
document.getElementById('deleteModal').style.display = 'none';
|
||||
loadUsers();
|
||||
} else {
|
||||
showNotification(result.message || '删除失败', false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('删除用户失败:', error);
|
||||
showNotification('删除用户失败', false);
|
||||
}
|
||||
}
|
||||
|
||||
// 事件监听器
|
||||
document.getElementById('addUserBtn').addEventListener('click', openAddModal);
|
||||
|
||||
document.getElementById('userForm').addEventListener('submit', saveUser);
|
||||
|
||||
document.getElementById('confirmDeleteBtn').addEventListener('click', deleteUser);
|
||||
|
||||
document.querySelectorAll('.close').forEach(closeBtn => {
|
||||
closeBtn.addEventListener('click', function() {
|
||||
this.parentElement.parentElement.style.display = 'none';
|
||||
});
|
||||
});
|
||||
|
||||
document.getElementById('searchBtn').addEventListener('click', function() {
|
||||
const searchTerm = document.getElementById('searchInput').value;
|
||||
loadUsers(searchTerm);
|
||||
});
|
||||
|
||||
document.getElementById('resetBtn').addEventListener('click', function() {
|
||||
document.getElementById('searchInput').value = '';
|
||||
loadUsers();
|
||||
});
|
||||
|
||||
// 点击模态框外部关闭模态框
|
||||
window.addEventListener('click', function(event) {
|
||||
const modals = document.querySelectorAll('.modal');
|
||||
modals.forEach(modal => {
|
||||
if (event.target === modal) {
|
||||
modal.style.display = 'none';
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 登出功能
|
||||
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 || '发生错误';
|
||||
}
|
||||
});
|
||||
|
||||
// 页面加载时获取用户列表
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
loadUsers();
|
||||
});
|
||||
|
||||
// 为表格中的编辑和删除按钮添加事件监听器
|
||||
document.addEventListener('click', function(e) {
|
||||
if (e.target.classList.contains('edit-btn')) {
|
||||
const user = JSON.parse(e.target.getAttribute('data-user'));
|
||||
openEditModal(user);
|
||||
}
|
||||
|
||||
if (e.target.classList.contains('delete-btn')) {
|
||||
const username = e.target.getAttribute('data-username');
|
||||
const userId = e.target.getAttribute('data-userid');
|
||||
openDeleteModal(username, userId);
|
||||
}
|
||||
});
|
||||
</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.
|
||||
38
elastic/urls.py
Normal file
38
elastic/urls.py
Normal file
@@ -0,0 +1,38 @@
|
||||
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('analytics/overview/', views.analytics_overview, name='analytics_overview'),
|
||||
|
||||
# 用户管理
|
||||
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('users/<int:user_id>/delete/', views.delete_user_by_id_view, name='delete_user_by_id'),
|
||||
path('users/<int:user_id>/update/', views.update_user_by_id_view, name='update_user_by_id'),
|
||||
|
||||
# 图片上传与确认
|
||||
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'),
|
||||
path('user_manage/', views.user_manage, name='user_manage'),
|
||||
]
|
||||
552
elastic/views.py
Normal file
552
elastic/views.py
Normal file
@@ -0,0 +1,552 @@
|
||||
"""
|
||||
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, csrf_protect
|
||||
from .es_connect import *
|
||||
from openai import OpenAI
|
||||
from PIL import Image
|
||||
|
||||
|
||||
@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(["GET"])
|
||||
def analytics_overview(request):
|
||||
try:
|
||||
force = request.GET.get("force") == "1"
|
||||
data = get_analytics_overview(force=force)
|
||||
return JsonResponse({"status": "success", "data": data})
|
||||
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):
|
||||
"""删除数据(需登录;管理员或作者本人)"""
|
||||
request_user=request.session.get("user_id")
|
||||
# request_admin=request.session.get("permisssion")
|
||||
if request_user is None:
|
||||
return JsonResponse({"status": "error", "message": "未登录"}, status=401)
|
||||
|
||||
|
||||
try:
|
||||
existing = get_by_id(doc_id)
|
||||
user_existing=get_user_by_id(request_user)
|
||||
|
||||
if not existing:
|
||||
return JsonResponse({"status": "error", "message": "数据不存在"}, status=404)
|
||||
|
||||
is_admin = (user_existing.get('permission') ) == 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):
|
||||
"""更新数据(需登录;管理员或作者本人)"""
|
||||
request_user = request.session.get("user_id")
|
||||
if request_user is None:
|
||||
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)
|
||||
user_existing = get_user_by_id(request_user)
|
||||
|
||||
if not existing:
|
||||
return JsonResponse({"status": "error", "message": "数据不存在"}, status=404)
|
||||
|
||||
is_admin = (user_existing.get('permission')) == 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_protect
|
||||
def add_user(request):
|
||||
if request.session.get("user_id") is None:
|
||||
return JsonResponse({"status": "error", "message": "未登录"}, status=401)
|
||||
if request.session.get("permission", 1) != 0:
|
||||
return JsonResponse({"status": "error", "message": "无权限"}, status=403)
|
||||
try:
|
||||
payload = json.loads(request.body.decode("utf-8"))
|
||||
except Exception:
|
||||
return JsonResponse({"status": "error", "message": "JSON无效"}, status=400)
|
||||
username = (payload.get("username") or "").strip()
|
||||
password = (payload.get("password") or "").strip()
|
||||
try:
|
||||
permission = int(payload.get("permission", 1))
|
||||
except Exception:
|
||||
permission = 1
|
||||
if not username:
|
||||
return JsonResponse({"status": "error", "message": "用户名不能为空"}, status=400)
|
||||
if password and len(password) < 6:
|
||||
return JsonResponse({"status": "error", "message": "密码长度至少为6位"}, status=400)
|
||||
existing = get_user_by_username(username)
|
||||
if existing:
|
||||
return JsonResponse({"status": "error", "message": "用户名已存在"}, status=409)
|
||||
users = get_all_users()
|
||||
next_id = (max([int(u.get("user_id", 0)) for u in users]) + 1) if users else 1
|
||||
ok = write_user_data({
|
||||
"user_id": next_id,
|
||||
"username": username,
|
||||
"password": password,
|
||||
"permission": permission,
|
||||
})
|
||||
if not ok:
|
||||
return JsonResponse({"status": "error", "message": "用户添加失败"}, status=500)
|
||||
return JsonResponse({"status": "success", "message": "用户添加成功"})
|
||||
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
def get_users(request):
|
||||
if request.session.get("user_id") is None:
|
||||
return JsonResponse({"status": "error", "message": "未登录"}, status=401)
|
||||
if request.session.get("permission", 1) != 0:
|
||||
return JsonResponse({"status": "error", "message": "无权限"}, status=403)
|
||||
try:
|
||||
q = (request.GET.get("search") or "").strip()
|
||||
users = get_all_users()
|
||||
if q:
|
||||
users = [u for u in users if q in str(u.get("username", ""))]
|
||||
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 = int(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)
|
||||
|
||||
@require_http_methods(["POST"])
|
||||
@csrf_protect
|
||||
def update_user_by_id_view(request, user_id):
|
||||
if request.session.get("user_id") is None:
|
||||
return JsonResponse({"status": "error", "message": "未登录"}, status=401)
|
||||
if request.session.get("permission", 1) != 0:
|
||||
return JsonResponse({"status": "error", "message": "无权限"}, status=403)
|
||||
try:
|
||||
payload = json.loads(request.body.decode("utf-8"))
|
||||
except Exception:
|
||||
return JsonResponse({"status": "error", "message": "JSON无效"}, status=400)
|
||||
new_username = (payload.get("username") or "").strip()
|
||||
new_permission = payload.get("permission")
|
||||
new_password = (payload.get("password") or "").strip()
|
||||
if new_username:
|
||||
other = get_user_by_username(new_username)
|
||||
if other and int(other.get("user_id", -1)) != int(user_id):
|
||||
return JsonResponse({"status": "error", "message": "用户名已存在"}, status=409)
|
||||
if new_password and len(new_password) < 6:
|
||||
return JsonResponse({"status": "error", "message": "密码长度至少为6位"}, status=400)
|
||||
ok = update_user_by_id(
|
||||
user_id,
|
||||
username=new_username if new_username else None,
|
||||
permission=int(new_permission) if new_permission is not None else None,
|
||||
password=new_password if new_password else None,
|
||||
)
|
||||
if not ok:
|
||||
return JsonResponse({"status": "error", "message": "用户更新失败"}, status=500)
|
||||
return JsonResponse({"status": "success", "message": "用户更新成功"})
|
||||
|
||||
@require_http_methods(["POST"])
|
||||
@csrf_protect
|
||||
def delete_user_by_id_view(request, user_id):
|
||||
if request.session.get("user_id") is None:
|
||||
return JsonResponse({"status": "error", "message": "未登录"}, status=401)
|
||||
if request.session.get("permission", 1) != 0:
|
||||
return JsonResponse({"status": "error", "message": "无权限"}, status=403)
|
||||
ok = delete_user_by_id(user_id)
|
||||
if not ok:
|
||||
return JsonResponse({"status": "error", "message": "用户删除失败"}, status=500)
|
||||
return JsonResponse({"status": "success", "message": "用户删除成功"})
|
||||
|
||||
|
||||
# 辅助: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", "188f57db3766e02ed2c7e18373996d84f4112272")
|
||||
# base_url = getattr(settings, "OPENAI_BASE_URL", "https://aistudio.baidu.com/llm/lmapi/v3")
|
||||
# if not api_key:
|
||||
# raise RuntimeError("缺少 AISTUDIO_API_KEY,请在环境变量或 settings 中配置")
|
||||
|
||||
|
||||
api_key = getattr(settings, "AISTUDIO_API_KEY", "")
|
||||
base_url = getattr(settings, "OPENAI_BASE_URL", "")
|
||||
if not api_key or not base_url:
|
||||
raise RuntimeError("缺少模型服务配置,请设置 AISTUDIO_API_KEY 与 OPENAI_BASE_URL")
|
||||
client = OpenAI(api_key=api_key, base_url=base_url)
|
||||
|
||||
types = get_type_list()
|
||||
chat_completion = client.chat.completions.create(
|
||||
messages=[
|
||||
{"role": "system", "content": "你是一个能理解图片和文本的助手,请根据用户提供的信息进行回答。"},
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": f"请识别这张图片中的信息,将你认为重要的数据转换为不包含嵌套的json,不要显示其它信息以便于解析,直接输出json结果即可。使用“数据类型”字段表示这个东西的大致类型,除此之外你可以自行决定使用哪些json字段。“数据类型”的内容有严格规定,请查看{json.dumps(types, ensure_ascii=False)}中是否包含你所需要的类型,确定不包含后你才可以填入你觉得合适的大致分类。"},
|
||||
{"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 request.session.get("user_id") is None:
|
||||
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 request.session.get("user_id") is None:
|
||||
# 允许从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)
|
||||
|
||||
ensure_type_in_list(edited.get("数据类型"))
|
||||
final_image_rel = image_rel
|
||||
try:
|
||||
if image_rel:
|
||||
images_dir = os.path.join(settings.MEDIA_ROOT, "images")
|
||||
os.makedirs(images_dir, exist_ok=True)
|
||||
src_abs = os.path.join(settings.MEDIA_ROOT, image_rel)
|
||||
base = os.path.splitext(os.path.basename(image_rel))[0]
|
||||
webp_name = base + ".webp"
|
||||
webp_abs = os.path.join(images_dir, webp_name)
|
||||
with Image.open(src_abs) as im:
|
||||
if im.mode in ("RGBA", "LA", "P"):
|
||||
im = im.convert("RGBA")
|
||||
else:
|
||||
im = im.convert("RGB")
|
||||
im.save(webp_abs, format="WEBP", quality=80)
|
||||
final_image_rel = f"images/{webp_name}"
|
||||
except Exception:
|
||||
final_image_rel = image_rel
|
||||
|
||||
to_store = {
|
||||
"writer_id": str(request.session.get("user_id")),
|
||||
"data": json_to_string(edited),
|
||||
"image": final_image_rel,
|
||||
}
|
||||
|
||||
ok = insert_data(to_store)
|
||||
if not ok:
|
||||
return JsonResponse({"status": "error", "message": "写入ES失败"}, status=500)
|
||||
|
||||
try:
|
||||
if image_rel and final_image_rel != image_rel:
|
||||
orig_abs = os.path.join(settings.MEDIA_ROOT, image_rel)
|
||||
if os.path.isfile(orig_abs):
|
||||
os.remove(orig_abs)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
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)
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
@ensure_csrf_cookie
|
||||
def user_manage(request):
|
||||
session_user_id = request.session.get("user_id")
|
||||
if session_user_id is None:
|
||||
from django.shortcuts import redirect
|
||||
return redirect("/accounts/login/")
|
||||
if request.session.get("permission", 1) != 0:
|
||||
from django.shortcuts import redirect
|
||||
return redirect("/main/home/")
|
||||
user_id_qs = request.GET.get("user_id")
|
||||
context = {"user_id": user_id_qs or session_user_id}
|
||||
return render(request, "elastic/users.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'
|
||||
343
main/templates/main/home.html
Normal file
343
main/templates/main/home.html
Normal file
@@ -0,0 +1,343 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>数据管理系统</title>
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
|
||||
background: #fafafa;
|
||||
}
|
||||
|
||||
/* 导航栏样式 */
|
||||
.sidebar {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 180px;
|
||||
height: 100vh;
|
||||
background: #1e1e2e;
|
||||
color: white;
|
||||
padding: 20px;
|
||||
box-shadow: 2px 0 5px rgba(0,0,0,0.1);
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.user-id {
|
||||
text-align: center;
|
||||
margin-bottom: auto;
|
||||
}
|
||||
|
||||
.sidebar h3 {
|
||||
margin-top: 0;
|
||||
font-size: 18px;
|
||||
color: #ff79c6;
|
||||
text-align: center;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.navigation-links {
|
||||
width: 100%;
|
||||
margin-top: 60px;
|
||||
}
|
||||
|
||||
.sidebar a,
|
||||
.sidebar button {
|
||||
display: block;
|
||||
color: #8be9fd;
|
||||
text-decoration: none;
|
||||
margin: 10px 0;
|
||||
font-size: 16px;
|
||||
padding: 15px;
|
||||
border-radius: 4px;
|
||||
background: transparent;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
width: calc(100% - 40px);
|
||||
text-align: left;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.sidebar a:hover,
|
||||
.sidebar button:hover {
|
||||
color: #ff79c6;
|
||||
background-color: rgba(139, 233, 253, 0.2);
|
||||
}
|
||||
|
||||
/* 主内容区 */
|
||||
.main-content {
|
||||
margin-left: 200px;
|
||||
padding: 20px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: #fff;
|
||||
border-radius: 14px;
|
||||
box-shadow: 0 10px 24px rgba(31,35,40,0.08);
|
||||
padding: 20px;
|
||||
}
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 16px;
|
||||
}
|
||||
.grid-3 {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 16px;
|
||||
}
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.badge {
|
||||
background: #eef2ff;
|
||||
color: #3730a3;
|
||||
border-radius: 999px;
|
||||
padding: 4px 10px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.legend {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
}
|
||||
.legend .dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
display: inline-block;
|
||||
}
|
||||
.muted {
|
||||
color: #6b7280;
|
||||
font-size: 12px;
|
||||
}
|
||||
.btn {
|
||||
padding: 8px 12px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn-primary {
|
||||
background: #4f46e5;
|
||||
color: #fff;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!-- 左侧固定栏目 -->
|
||||
<div class="sidebar">
|
||||
<div class="user-id">
|
||||
<h3>用户ID:{{ user_id }}</h3>
|
||||
</div>
|
||||
<div class="navigation-links">
|
||||
<a href="{% url 'main:home' %}" onclick="return handleNavClick(this, '/');">主页</a>
|
||||
<a href="{% url 'elastic:upload_page' %}" onclick="return handleNavClick(this, '/elastic/upload/');">图片上传与识别</a>
|
||||
<a href="{% url 'elastic:manage_page' %}" onclick="return handleNavClick(this, '/elastic/manage/');">数据管理</a>
|
||||
{% if is_admin %}
|
||||
<a href="{% url 'elastic:user_manage' %}" onclick="return handleNavClick(this, '/elastic/user_manage/');">用户管理</a>
|
||||
{% endif %}
|
||||
<button id="logoutBtn">退出登录</button>
|
||||
<div id="logoutMsg"></div>
|
||||
{% csrf_token %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 主内容区域 -->
|
||||
<div class="main-content">
|
||||
<div class="card">
|
||||
<div class="header">
|
||||
<h2>数据概览</h2>
|
||||
<div style="display:flex; gap:8px; align-items:center;">
|
||||
<span class="badge">用户:{{ user_id }}</span>
|
||||
{% if is_admin %}
|
||||
<button id="triggerAnalyze" class="btn btn-primary">手动开始分析</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid-3">
|
||||
<div>
|
||||
<div class="legend"><span class="dot" style="background:#4f46e5;"></span><span class="muted">最近十天录入</span></div>
|
||||
<canvas id="chartDays" height="140"></canvas>
|
||||
</div>
|
||||
<div>
|
||||
<div class="legend"><span class="dot" style="background:#16a34a;"></span><span class="muted">最近十周录入</span></div>
|
||||
<canvas id="chartWeeks" height="140"></canvas>
|
||||
</div>
|
||||
<div>
|
||||
<div class="legend"><span class="dot" style="background:#ea580c;"></span><span class="muted">最近十个月录入</span></div>
|
||||
<canvas id="chartMonths" height="140"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid" style="margin-top:16px;">
|
||||
<div class="card">
|
||||
<div class="header"><h2>近1个月成果类型</h2></div>
|
||||
<canvas id="pie1m" height="200"></canvas>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="header"><h2>近12个月成果类型</h2></div>
|
||||
<canvas id="pie12m" height="200"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
|
||||
<script>
|
||||
// 获取CSRF令牌的函数
|
||||
function getCookie(name) {
|
||||
const value = `; ${document.cookie}`;
|
||||
const parts = value.split(`; ${name}=`);
|
||||
if (parts.length === 2) return parts.pop().split(';').shift();
|
||||
}
|
||||
|
||||
// 导航点击处理函数,提供备用URL
|
||||
function handleNavClick(element, fallbackUrl) {
|
||||
// 尝试使用Django模板生成的URL,如果失败则使用备用URL
|
||||
try {
|
||||
// 如果模板渲染正常,直接返回true让默认行为处理
|
||||
return true;
|
||||
} catch (e) {
|
||||
// 如果模板渲染有问题,使用备用URL
|
||||
window.location.href = fallbackUrl;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 修复用户管理链接跳转问题
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// 为用户管理链接添加事件监听器,确保正确跳转
|
||||
const userManagementLink = document.querySelector('a[href*="get_users"]');
|
||||
if (userManagementLink) {
|
||||
userManagementLink.addEventListener('click', function(e) {
|
||||
// 阻止默认行为
|
||||
e.preventDefault();
|
||||
|
||||
// 获取备用URL
|
||||
const fallbackUrl = this.getAttribute('onclick').match(/'([^']+)'/g)[1].replace(/'/g, '');
|
||||
|
||||
// 直接跳转到用户管理页面
|
||||
window.location.href = fallbackUrl;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// 登出功能
|
||||
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 || '发生错误';
|
||||
}
|
||||
});
|
||||
|
||||
async function loadAnalytics() {
|
||||
const resp = await fetch('/elastic/analytics/overview/');
|
||||
const d = await resp.json();
|
||||
if (!resp.ok || d.status !== 'success') return;
|
||||
const data = d.data || {};
|
||||
renderLine('chartDays', data.last_10_days || [], '#4f46e5');
|
||||
renderLine('chartWeeks', data.last_10_weeks || [], '#16a34a');
|
||||
renderLine('chartMonths', data.last_10_months || [], '#ea580c');
|
||||
renderPie('pie1m', data.type_pie_1m || []);
|
||||
renderPie('pie12m', data.type_pie_12m || []);
|
||||
}
|
||||
|
||||
const btn = document.getElementById('triggerAnalyze');
|
||||
if (btn) {
|
||||
btn.addEventListener('click', async () => {
|
||||
btn.disabled = true;
|
||||
btn.textContent = '分析中…';
|
||||
try {
|
||||
const resp = await fetch('/elastic/analytics/overview/?force=1');
|
||||
const d = await resp.json();
|
||||
if (!resp.ok || d.status !== 'success') throw new Error('分析失败');
|
||||
window.location.reload();
|
||||
} catch (e) {
|
||||
btn.textContent = '重试';
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function hexWithAlpha(hex, alphaHex) {
|
||||
if (!hex || !hex.startsWith('#')) return hex;
|
||||
if (hex.length === 7) return hex + alphaHex;
|
||||
return hex;
|
||||
}
|
||||
function renderLine(id, items, color) {
|
||||
const ctx = document.getElementById(id);
|
||||
const labels = items.map(x => x.label);
|
||||
const values = items.map(x => x.count);
|
||||
new Chart(ctx, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels,
|
||||
datasets: [{
|
||||
data: values,
|
||||
borderColor: color,
|
||||
backgroundColor: hexWithAlpha(color, '26'),
|
||||
tension: 0.25,
|
||||
fill: true,
|
||||
pointRadius: 3,
|
||||
}]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
plugins: { legend: { display: false } },
|
||||
animation: { duration: 800, easing: 'easeOutQuart' },
|
||||
scales: {
|
||||
x: { grid: { display: false } },
|
||||
y: { grid: { color: 'rgba(31,35,40,0.06)' }, beginAtZero: true }
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
function renderPie(id, items) {
|
||||
const ctx = document.getElementById(id);
|
||||
const labels = items.map(x => x.type);
|
||||
const values = items.map(x => x.count);
|
||||
const colors = ['#2563eb','#22c55e','#f59e0b','#ef4444','#a855f7','#06b6d4','#84cc16','#ec4899','#475569','#d946ef'];
|
||||
new Chart(ctx, {
|
||||
type: 'doughnut',
|
||||
data: {
|
||||
labels,
|
||||
datasets: [{ data: values, backgroundColor: colors.slice(0, labels.length) }]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
animation: { duration: 900, easing: 'easeOutQuart' },
|
||||
plugins: { legend: { position: 'bottom' } }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
loadAnalytics();
|
||||
</script>
|
||||
</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"),
|
||||
]
|
||||
25
main/views.py
Normal file
25
main/views.py
Normal file
@@ -0,0 +1,25 @@
|
||||
from django.shortcuts import render, redirect
|
||||
from django.views.decorators.http import require_http_methods
|
||||
from elastic.es_connect import get_user_by_id
|
||||
|
||||
|
||||
@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")
|
||||
uid = user_id_qs or session_user_id
|
||||
perm = request.session.get("permission")
|
||||
if perm is None and uid is not None:
|
||||
u = get_user_by_id(uid)
|
||||
perm = (u or {}).get("permission", 1)
|
||||
request.session["permission"] = perm
|
||||
context = {
|
||||
"user_id": uid,
|
||||
"is_admin": (perm == 0),
|
||||
}
|
||||
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,11 @@
|
||||
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==7.17.9
|
||||
django-elasticsearch-dsl==7.4.0
|
||||
django-elasticsearch-dsl-drf==0.22
|
||||
elasticsearch-dsl==7.4.1
|
||||
requests==2.32.3
|
||||
openai==1.52.2
|
||||
httpx==0.27.2
|
||||
Pillow==10.4.0
|
||||
gunicorn==21.2.0
|
||||
whitenoise==6.6.0
|
||||
|
||||
@@ -1,353 +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>
|
||||
</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();
|
||||
}
|
||||
|
||||
// 页面加载时初始化
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
updateSelectedCount();
|
||||
});
|
||||
</script>
|
||||
|
||||
{% endblock %}
|
||||
@@ -1,177 +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;
|
||||
}
|
||||
|
||||
.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);
|
||||
}
|
||||
|
||||
.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>
|
||||
|
||||
<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('show_all') }}" {% if request.endpoint == 'show_all' %}class="active"{% endif %}>
|
||||
<i>📁</i> 数据操作
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
{% 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,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,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 %}
|
||||
Reference in New Issue
Block a user