上传文件至「/」
This commit is contained in:
commit
634bf7a4d5
5 files changed
+383
No files matched your search
@@ -0,0 +1,188 @@
|
|||||||
|
import os
|
||||||
|
import time
|
||||||
|
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify
|
||||||
|
from flask_login import LoginManager, login_user, logout_user, login_required, current_user
|
||||||
|
from werkzeug.security import generate_password_hash, check_password_hash
|
||||||
|
from werkzeug.utils import secure_filename
|
||||||
|
from models import db, User, NavItem, NavStatus, Setting
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.config['SECRET_KEY'] = 'dev-secret-key-998877'
|
||||||
|
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@my-mysql:3306/nav_db'
|
||||||
|
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
||||||
|
|
||||||
|
# 上传配置
|
||||||
|
UPLOAD_FOLDER = 'static/uploads'
|
||||||
|
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp'}
|
||||||
|
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
||||||
|
|
||||||
|
# 确保上传目录存在
|
||||||
|
if not os.path.exists(UPLOAD_FOLDER):
|
||||||
|
os.makedirs(UPLOAD_FOLDER)
|
||||||
|
|
||||||
|
db.init_app(app)
|
||||||
|
|
||||||
|
login_manager = LoginManager()
|
||||||
|
login_manager.init_app(app)
|
||||||
|
login_manager.login_view = 'login'
|
||||||
|
|
||||||
|
@login_manager.user_loader
|
||||||
|
def load_user(user_id):
|
||||||
|
return User.query.get(int(user_id))
|
||||||
|
|
||||||
|
def allowed_file(filename):
|
||||||
|
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
||||||
|
|
||||||
|
def handle_upload(field_name):
|
||||||
|
"""处理文件上传并返回 URL"""
|
||||||
|
if field_name not in request.files:
|
||||||
|
return None
|
||||||
|
file = request.files[field_name]
|
||||||
|
if file and file.filename != '' and allowed_file(file.filename):
|
||||||
|
# 生成安全且唯一的文件名
|
||||||
|
filename_base = secure_filename(file.filename)
|
||||||
|
filename_hashed = f"{int(time.time())}_{filename_base}"
|
||||||
|
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename_hashed)
|
||||||
|
file.save(file_path)
|
||||||
|
# 返回相对于 static 文件夹的 URL
|
||||||
|
return url_for('static', filename=f'uploads/{filename_hashed}')
|
||||||
|
return None
|
||||||
|
|
||||||
|
# 初始化数据库
|
||||||
|
def setup_db():
|
||||||
|
with app.app_context():
|
||||||
|
db.create_all()
|
||||||
|
admin = User.query.filter_by(username='admin').first()
|
||||||
|
if not admin:
|
||||||
|
admin = User(username='admin', password=generate_password_hash('admin123'))
|
||||||
|
db.session.add(admin)
|
||||||
|
print("--- 已创建默认管理员账号: admin / admin123 ---")
|
||||||
|
else:
|
||||||
|
# 强制重置密码,防止哈希版本不一致
|
||||||
|
admin.password = generate_password_hash('admin123')
|
||||||
|
print("--- 已强制重置管理员密码为: admin123 ---")
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
if not Setting.query.filter_by(config_key='popup_config').first():
|
||||||
|
pop = Setting(config_key='popup_config', config_value='欢迎访问现代导航系统!', is_enabled=True)
|
||||||
|
db.session.add(pop)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
setup_db()
|
||||||
|
|
||||||
|
# --- 路由 ---
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index():
|
||||||
|
items = NavItem.query.order_by(NavItem.sort_weight.desc()).all()
|
||||||
|
popup = Setting.query.filter_by(config_key='popup_config').first()
|
||||||
|
return render_template('index.html', items=items, popup=popup)
|
||||||
|
|
||||||
|
@app.route('/login', methods=['GET', 'POST'])
|
||||||
|
def login():
|
||||||
|
if request.method == 'POST':
|
||||||
|
user = User.query.filter_by(username=request.form.get('username')).first()
|
||||||
|
if user and check_password_hash(user.password, request.form.get('password')):
|
||||||
|
login_user(user)
|
||||||
|
return redirect(url_for('admin_dashboard'))
|
||||||
|
flash('用户名或密码错误', 'danger')
|
||||||
|
return render_template('login.html')
|
||||||
|
|
||||||
|
@app.route('/logout')
|
||||||
|
@login_required
|
||||||
|
def logout():
|
||||||
|
logout_user()
|
||||||
|
return redirect(url_for('index'))
|
||||||
|
|
||||||
|
@app.route('/admin')
|
||||||
|
@login_required
|
||||||
|
def admin_dashboard():
|
||||||
|
return render_template('admin/dashboard.html', item_count=NavItem.query.count(), user_count=User.query.count())
|
||||||
|
|
||||||
|
@app.route('/admin/items', methods=['GET', 'POST'])
|
||||||
|
@login_required
|
||||||
|
def admin_items():
|
||||||
|
if request.method == 'POST':
|
||||||
|
# 处理新增条目
|
||||||
|
image_large_url = handle_upload('file_large') or request.form.get('image_large')
|
||||||
|
image_thumb_url = handle_upload('file_thumb') or request.form.get('image_thumb')
|
||||||
|
|
||||||
|
new_item = NavItem(
|
||||||
|
title=request.form.get('title'),
|
||||||
|
url=request.form.get('url') or None,
|
||||||
|
description=request.form.get('description'),
|
||||||
|
image_large=image_large_url,
|
||||||
|
image_thumb=image_thumb_url,
|
||||||
|
status=NavStatus(request.form.get('status')),
|
||||||
|
sort_weight=int(request.form.get('sort_weight', 0))
|
||||||
|
)
|
||||||
|
db.session.add(new_item)
|
||||||
|
db.session.commit()
|
||||||
|
flash('条目添加成功', 'success')
|
||||||
|
return redirect(url_for('admin_items'))
|
||||||
|
|
||||||
|
items = NavItem.query.order_by(NavItem.sort_weight.desc()).all()
|
||||||
|
return render_template('admin/items.html', items=items, status_enum=NavStatus)
|
||||||
|
|
||||||
|
@app.route('/admin/items/edit/<int:id>', methods=['POST'])
|
||||||
|
@login_required
|
||||||
|
def edit_item(id):
|
||||||
|
item = NavItem.query.get_or_404(id)
|
||||||
|
item.title = request.form.get('title')
|
||||||
|
item.url = request.form.get('url') or None
|
||||||
|
item.description = request.form.get('description')
|
||||||
|
item.status = NavStatus(request.form.get('status'))
|
||||||
|
item.sort_weight = int(request.form.get('sort_weight', 0))
|
||||||
|
|
||||||
|
# 处理图片上传或URL更新
|
||||||
|
new_large_url = handle_upload('file_large')
|
||||||
|
if new_large_url: item.image_large = new_large_url
|
||||||
|
elif request.form.get('image_large') is not None: item.image_large = request.form.get('image_large') # Allow clearing URL if input is present
|
||||||
|
|
||||||
|
new_thumb_url = handle_upload('file_thumb')
|
||||||
|
if new_thumb_url: item.image_thumb = new_thumb_url
|
||||||
|
elif request.form.get('image_thumb') is not None: item.image_thumb = request.form.get('image_thumb') # Allow clearing URL if input is present
|
||||||
|
|
||||||
|
db.session.commit()
|
||||||
|
flash('修改成功', 'success')
|
||||||
|
return redirect(url_for('admin_items'))
|
||||||
|
|
||||||
|
@app.route('/admin/items/delete/<int:id>')
|
||||||
|
@login_required
|
||||||
|
def delete_item(id):
|
||||||
|
item = NavItem.query.get_or_404(id)
|
||||||
|
db.session.delete(item)
|
||||||
|
db.session.commit()
|
||||||
|
flash('删除成功', 'success')
|
||||||
|
return redirect(url_for('admin_items'))
|
||||||
|
|
||||||
|
@app.route('/admin/users', methods=['GET', 'POST'])
|
||||||
|
@login_required
|
||||||
|
def admin_users():
|
||||||
|
if request.method == 'POST':
|
||||||
|
username = request.form.get('username')
|
||||||
|
password = request.form.get('password')
|
||||||
|
if User.query.filter_by(username=username).first(): flash('用户名已存在', 'warning')
|
||||||
|
else:
|
||||||
|
new_user = User(username=username, password=generate_password_hash(password))
|
||||||
|
db.session.add(new_user)
|
||||||
|
db.session.commit()
|
||||||
|
flash('用户添加成功', 'success')
|
||||||
|
return render_template('admin/users.html', users=User.query.all())
|
||||||
|
|
||||||
|
@app.route('/admin/settings', methods=['GET', 'POST'])
|
||||||
|
@login_required
|
||||||
|
def admin_settings():
|
||||||
|
setting = Setting.query.filter_by(config_key='popup_config').first()
|
||||||
|
if request.method == 'POST':
|
||||||
|
if not setting:
|
||||||
|
setting = Setting(config_key='popup_config')
|
||||||
|
db.session.add(setting)
|
||||||
|
setting.config_value = request.form.get('config_value')
|
||||||
|
setting.is_enabled = True if request.form.get('is_enabled') else False
|
||||||
|
db.session.commit()
|
||||||
|
flash('配置更新成功', 'success')
|
||||||
|
return render_template('admin/settings.html', setting=setting)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
app.run(host='0.0.0.0', port=5000, debug=True)
|
||||||
+95
@@ -0,0 +1,95 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
||||||
|
<title>Modern Navigator | 现代导航</title>
|
||||||
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css">
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
||||||
|
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<nav class="glass-nav">
|
||||||
|
<div class="logo">NAVIGATOR</div>
|
||||||
|
<div class="nav-links">
|
||||||
|
{% if current_user.is_authenticated %}
|
||||||
|
<a href="{{ url_for('admin_dashboard') }}" class="nav-btn">管理</a>
|
||||||
|
<a href="{{ url_for('logout') }}" class="nav-btn logout">登出</a>
|
||||||
|
{% else %}
|
||||||
|
<a href="{{ url_for('login') }}" class="nav-btn">登录</a>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<main class="hero-section">
|
||||||
|
<div id="hero-bg" class="hero-bg"></div>
|
||||||
|
<div class="hero-content-pure">
|
||||||
|
<h1 id="hero-title">载入中...</h1>
|
||||||
|
<p id="hero-desc">正在为您获取最佳资源...</p>
|
||||||
|
<div class="btn-container">
|
||||||
|
<a id="hero-link" href="#" target="_blank" class="btn-visit">立即访问</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<footer class="bottom-nav-container">
|
||||||
|
<div class="swiper-button-prev custom-arrow"></div>
|
||||||
|
<div class="swiper-button-next custom-arrow"></div>
|
||||||
|
|
||||||
|
<div class="swiper mySwiper">
|
||||||
|
<div class="swiper-wrapper">
|
||||||
|
{% for item in items %}
|
||||||
|
<div class="swiper-slide nav-card {{ 'grayscale' if item.status.value != 'enabled' }}"
|
||||||
|
data-title="{{ item.title }}"
|
||||||
|
data-desc="{{ item.description }}"
|
||||||
|
data-url="{{ item.url or '' }}"
|
||||||
|
data-bg="{{ item.image_large }}"
|
||||||
|
data-status="{{ item.status.value }}">
|
||||||
|
<img src="{{ item.image_thumb }}" alt="{{ item.title }}">
|
||||||
|
<div class="card-info">
|
||||||
|
<h3>{{ item.title }}</h3>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>
|
||||||
|
<script src="{{ url_for('static', filename='js/main.js') }}"></script>
|
||||||
|
<script>
|
||||||
|
window.difyChatbotConfig = {
|
||||||
|
token: 'USxT0fq160sy4KaN',
|
||||||
|
baseUrl: 'https://dify.aibi.chat',
|
||||||
|
inputs: {
|
||||||
|
// You can define the inputs from the Start node here
|
||||||
|
// key is the variable name
|
||||||
|
// e.g.
|
||||||
|
// name: "NAME"
|
||||||
|
},
|
||||||
|
systemVariables: {
|
||||||
|
// user_id: 'YOU CAN DEFINE USER ID HERE',
|
||||||
|
// conversation_id: 'YOU CAN DEFINE CONVERSATION ID HERE, IT MUST BE A VALID UUID',
|
||||||
|
},
|
||||||
|
userVariables: {
|
||||||
|
// avatar_url: 'YOU CAN DEFINE USER AVATAR URL HERE',
|
||||||
|
// name: 'YOU CAN DEFINE USER NAME HERE',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
<script
|
||||||
|
src="https://dify.aibi.chat/embed.min.js"
|
||||||
|
id="USxT0fq160sy4KaN"
|
||||||
|
defer>
|
||||||
|
</script>
|
||||||
|
<style>
|
||||||
|
#dify-chatbot-bubble-button {
|
||||||
|
background-color: #1C64F2 !important;
|
||||||
|
}
|
||||||
|
#dify-chatbot-bubble-window {
|
||||||
|
width: 24rem !important;
|
||||||
|
height: 40rem !important;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
-- 创建数据库
|
||||||
|
CREATE DATABASE IF NOT EXISTS nav_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
USE nav_db;
|
||||||
|
|
||||||
|
-- 1. 用户表
|
||||||
|
CREATE TABLE IF NOT EXISTS `users` (
|
||||||
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
`username` VARCHAR(50) NOT NULL UNIQUE,
|
||||||
|
`password` VARCHAR(255) NOT NULL,
|
||||||
|
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
) ENGINE=InnoDB;
|
||||||
|
|
||||||
|
-- 2. 导航条目表
|
||||||
|
CREATE TABLE IF NOT EXISTS `nav_items` (
|
||||||
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
`title` VARCHAR(100) NOT NULL,
|
||||||
|
`url` VARCHAR(255) DEFAULT NULL,
|
||||||
|
`description` TEXT,
|
||||||
|
`image_large` VARCHAR(255),
|
||||||
|
`image_thumb` VARCHAR(255),
|
||||||
|
`status` ENUM('enabled', 'disabled', 'construction', 'offline') DEFAULT 'enabled',
|
||||||
|
`sort_weight` INT DEFAULT 0,
|
||||||
|
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
) ENGINE=InnoDB;
|
||||||
|
|
||||||
|
-- 3. 全局配置表
|
||||||
|
CREATE TABLE IF NOT EXISTS `settings` (
|
||||||
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
`config_key` VARCHAR(50) NOT NULL UNIQUE,
|
||||||
|
`config_value` TEXT,
|
||||||
|
`is_enabled` TINYINT(1) DEFAULT 0
|
||||||
|
) ENGINE=InnoDB;
|
||||||
|
|
||||||
|
-- 插入默认管理员 (密码: admin123)
|
||||||
|
-- 注意:实际哈希会在 app.py 首次运行时由程序生成以保证兼容性
|
||||||
|
INSERT INTO `users` (`username`, `password`) VALUES
|
||||||
|
('admin', 'pbkdf2:sha256:260000$v9mB5NlD$0c0c0e3a6c1a8e9e7b4b1a2c3d4e5f6g7h8i9j0k');
|
||||||
|
|
||||||
|
INSERT INTO `settings` (`config_key`, `config_value`, `is_enabled`) VALUES
|
||||||
|
('popup_config', '欢迎来到现代导航系统!', 1);
|
||||||
|
|
||||||
|
INSERT INTO `nav_items` (`title`, `url`, `description`, `image_large`, `image_thumb`, `status`, `sort_weight`) VALUES
|
||||||
|
('Google', 'https://www.google.com', '全球领先的搜索引擎。', 'https://images.unsplash.com/photo-1573804633927-bfcbcd909acd?auto=format&fit=crop&q=80&w=1920', 'https://images.unsplash.com/photo-1573804633927-bfcbcd909acd?auto=format&fit=crop&q=80&w=400', 'enabled', 100),
|
||||||
|
('建设中项目', NULL, '这是一个正在建设中的示例条目。', 'https://images.unsplash.com/photo-1503387762-592dea58ef23?auto=format&fit=crop&q=80&w=1920', 'https://images.unsplash.com/photo-1503387762-592dea58ef23?auto=format&fit=crop&q=80&w=400', 'construction', 50),
|
||||||
|
('离线资源', 'https://example.com', '该资源目前已离线。', 'https://images.unsplash.com/photo-1555066931-4365d14bab8c?auto=format&fit=crop&q=80&w=1920', 'https://images.unsplash.com/photo-1555066931-4365d14bab8c?auto=format&fit=crop&q=80&w=400', 'offline', 10);
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
|
from flask_login import UserMixin
|
||||||
|
from datetime import datetime
|
||||||
|
import enum
|
||||||
|
|
||||||
|
db = SQLAlchemy()
|
||||||
|
|
||||||
|
class NavStatus(enum.Enum):
|
||||||
|
enabled = 'enabled'
|
||||||
|
disabled = 'disabled'
|
||||||
|
construction = 'construction'
|
||||||
|
offline = 'offline'
|
||||||
|
|
||||||
|
class User(db.Model, UserMixin):
|
||||||
|
__tablename__ = 'users'
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
username = db.Column(db.String(50), unique=True, nullable=False)
|
||||||
|
password = db.Column(db.String(255), nullable=False)
|
||||||
|
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||||
|
|
||||||
|
class NavItem(db.Model):
|
||||||
|
__tablename__ = 'nav_items'
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
title = db.Column(db.String(100), nullable=False)
|
||||||
|
url = db.Column(db.String(255), nullable=True)
|
||||||
|
description = db.Column(db.Text)
|
||||||
|
image_large = db.Column(db.String(255))
|
||||||
|
image_thumb = db.Column(db.String(255))
|
||||||
|
status = db.Column(db.Enum(NavStatus), default=NavStatus.enabled)
|
||||||
|
sort_weight = db.Column(db.Integer, default=0)
|
||||||
|
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||||
|
|
||||||
|
def to_dict(self):
|
||||||
|
return {
|
||||||
|
"id": self.id,
|
||||||
|
"title": self.title,
|
||||||
|
"url": self.url,
|
||||||
|
"description": self.description,
|
||||||
|
"image_large": self.image_large,
|
||||||
|
"image_thumb": self.image_thumb,
|
||||||
|
"status": self.status.value,
|
||||||
|
"sort_weight": self.sort_weight
|
||||||
|
}
|
||||||
|
|
||||||
|
class Setting(db.Model):
|
||||||
|
__tablename__ = 'settings'
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
config_key = db.Column(db.String(50), unique=True, nullable=False)
|
||||||
|
config_value = db.Column(db.Text)
|
||||||
|
is_enabled = db.Column(db.Boolean, default=False)
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
flask
|
||||||
|
flask-sqlalchemy
|
||||||
|
pymysql
|
||||||
|
flask-login
|
||||||
|
cryptography
|
||||||
Reference in new issue
Block a user