增加資料庫連線到MySQL
This commit is contained in:
@@ -1,12 +1,14 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
簡化版夥伴對齊系統 - 使用 SQLite
|
||||
無需 MySQL,開箱即用
|
||||
夥伴對齊系統 - 使用 MySQL
|
||||
生產環境就緒版本
|
||||
"""
|
||||
|
||||
from flask import Flask, render_template, request, jsonify
|
||||
from flask_cors import CORS
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
from config import Config
|
||||
from datetime import datetime, date
|
||||
import json
|
||||
import os
|
||||
@@ -16,14 +18,13 @@ import io
|
||||
# 創建 Flask 應用程式
|
||||
app = Flask(__name__)
|
||||
|
||||
# 配置
|
||||
app.config['SECRET_KEY'] = 'dev-secret-key-for-testing'
|
||||
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///partner_alignment.db'
|
||||
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
||||
# 從配置類載入設定
|
||||
app.config.from_object(Config)
|
||||
|
||||
# 初始化擴展
|
||||
db = SQLAlchemy(app)
|
||||
CORS(app, origins=['http://localhost:5000', 'http://127.0.0.1:5000'])
|
||||
migrate = Migrate(app, db)
|
||||
CORS(app, origins=Config.CORS_ORIGINS)
|
||||
|
||||
# 數據模型
|
||||
class User(db.Model):
|
||||
@@ -923,16 +924,36 @@ def create_sample_data():
|
||||
|
||||
if __name__ == '__main__':
|
||||
with app.app_context():
|
||||
# 創建所有數據庫表
|
||||
db.create_all()
|
||||
print("數據庫表創建成功!")
|
||||
|
||||
# 創建樣本數據
|
||||
create_sample_data()
|
||||
|
||||
print("=" * 60)
|
||||
print("夥伴對齊系統已啟動!")
|
||||
print("夥伴對齊系統 - MySQL 版本")
|
||||
print("=" * 60)
|
||||
print(f"[DATABASE] 連線至: {Config.DB_HOST}:{Config.DB_PORT}/{Config.DB_NAME}")
|
||||
print(f"[DATABASE] 使用者: {Config.DB_USER}")
|
||||
|
||||
# 使用 Flask-Migrate 管理資料庫
|
||||
# 首次運行前請執行: flask db upgrade
|
||||
try:
|
||||
# 嘗試建立樣本數據(如果表已存在)
|
||||
from sqlalchemy import inspect
|
||||
inspector = inspect(db.engine)
|
||||
existing_tables = inspector.get_table_names()
|
||||
|
||||
if 'user' in existing_tables:
|
||||
print("[DATABASE] 資料表已存在")
|
||||
else:
|
||||
print("[WARNING] 資料表不存在,請先執行: flask db upgrade")
|
||||
|
||||
# 創建樣本數據(如果不存在)
|
||||
create_sample_data()
|
||||
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 資料庫操作錯誤: {e}")
|
||||
print("[INFO] 請確認:")
|
||||
print(" 1. 已執行 flask db upgrade")
|
||||
print(" 2. 資料庫連線資訊正確")
|
||||
print(" 3. MySQL 服務正在運行")
|
||||
|
||||
print()
|
||||
print("[WEB] 訪問地址: http://localhost:5000")
|
||||
print()
|
||||
print("[ACCOUNT] 測試帳號資訊:")
|
||||
|
||||
Reference in New Issue
Block a user