Spaces:
Sleeping
Sleeping
| from flask import Flask, render_template, redirect, url_for, flash, request | |
| from flask_sqlalchemy import SQLAlchemy | |
| from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user | |
| from flask_admin import Admin | |
| from flask_admin.contrib.sqla import ModelView | |
| from werkzeug.security import generate_password_hash, check_password_hash | |
| import os | |
| app = Flask(__name__) | |
| app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'your-secret-key') | |
| app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///admin.db' | |
| app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False | |
| db = SQLAlchemy(app) | |
| login_manager = LoginManager(app) | |
| login_manager.login_view = 'login' | |
| # 用户模型 | |
| class User(UserMixin, db.Model): | |
| id = db.Column(db.Integer, primary_key=True) | |
| username = db.Column(db.String(80), unique=True, nullable=False) | |
| password_hash = db.Column(db.String(120), nullable=False) | |
| is_admin = db.Column(db.Boolean, default=False) | |
| def set_password(self, password): | |
| self.password_hash = generate_password_hash(password) | |
| def check_password(self, password): | |
| return check_password_hash(self.password_hash, password) | |
| # 管理员视图 | |
| class AdminModelView(ModelView): | |
| def is_accessible(self): | |
| return current_user.is_authenticated and current_user.is_admin | |
| def load_user(user_id): | |
| return User.query.get(int(user_id)) | |
| # 初始化管理员界面 | |
| admin = Admin(app, name='后台管理系统', template_mode='bootstrap3') | |
| admin.add_view(AdminModelView(User, db.session)) | |
| def index(): | |
| return render_template('index.html') | |
| def login(): | |
| if request.method == 'POST': | |
| username = request.form.get('username') | |
| password = request.form.get('password') | |
| user = User.query.filter_by(username=username).first() | |
| if user and user.check_password(password): | |
| login_user(user) | |
| return redirect(url_for('admin.index')) | |
| flash('Invalid username or password') | |
| return render_template('login.html') | |
| def logout(): | |
| logout_user() | |
| return redirect(url_for('index')) | |
| def init_db(): | |
| with app.app_context(): | |
| db.create_all() | |
| # 创建默认管理员账户 | |
| if not User.query.filter_by(username='admin').first(): | |
| admin_user = User(username='admin', is_admin=True) | |
| admin_user.set_password('admin123') | |
| db.session.add(admin_user) | |
| db.session.commit() | |
| # 初始化数据库 | |
| with app.app_context(): | |
| init_db() | |
| # 为 Hugging Face Spaces 配置 | |
| app.config['TEMPLATES_AUTO_RELOAD'] = True | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0', port=7860) | |
| else: | |
| # 这是为了让 Gunicorn 能够找到应用 | |
| application = app |