Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,4 @@
|
|
| 1 |
import sys
|
| 2 |
-
import os
|
| 3 |
-
|
| 4 |
-
# 【關鍵修正 1】關閉 Gradio 嚴格的 CSRF 防護,避免在 HF Spaces 加上 FastAPI 後按鈕被阻擋
|
| 5 |
-
os.environ["GRADIO_CSRF_TRUST_ORIGINS"] = "*"
|
| 6 |
|
| 7 |
try:
|
| 8 |
import gradio as gr
|
|
@@ -10,7 +6,6 @@ try:
|
|
| 10 |
from datetime import datetime
|
| 11 |
import subprocess
|
| 12 |
from fastapi import FastAPI, Request, HTTPException
|
| 13 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 14 |
from linebot import LineBotApi, WebhookHandler
|
| 15 |
from linebot.exceptions import InvalidSignatureError
|
| 16 |
from linebot.models import MessageEvent, TextMessage, TextSendMessage
|
|
@@ -39,15 +34,6 @@ except Exception as e:
|
|
| 39 |
|
| 40 |
custom_api = FastAPI()
|
| 41 |
|
| 42 |
-
# 【關鍵修正 2】加入跨域資源共用 (CORS) 中介軟體,確保按鈕送出的 API 請求不會被瀏覽器攔截
|
| 43 |
-
custom_api.add_middleware(
|
| 44 |
-
CORSMiddleware,
|
| 45 |
-
allow_origins=["*"],
|
| 46 |
-
allow_credentials=True,
|
| 47 |
-
allow_methods=["*"],
|
| 48 |
-
allow_headers=["*"],
|
| 49 |
-
)
|
| 50 |
-
|
| 51 |
# ----------------------------
|
| 52 |
# 🛒 系統資料與設定
|
| 53 |
# ----------------------------
|
|
@@ -114,12 +100,12 @@ def handle_message(event):
|
|
| 114 |
print(f"回覆失敗: {e}")
|
| 115 |
|
| 116 |
# ----------------------------
|
| 117 |
-
# 💻 網頁後台邏輯
|
| 118 |
# ----------------------------
|
| 119 |
def get_orders_data():
|
| 120 |
-
"""【關鍵修
|
| 121 |
if not orders_db:
|
| 122 |
-
return []
|
| 123 |
return [[o["時間"], o["顧客姓名"], o["商品"], o["單價"], o["數量"], o["總價"], o["備註"]] for o in orders_db]
|
| 124 |
|
| 125 |
def get_revenue():
|
|
@@ -131,11 +117,11 @@ def refresh_data():
|
|
| 131 |
|
| 132 |
def add_order(c_name, q0, q1, q2, q3, q4, nts):
|
| 133 |
try:
|
| 134 |
-
c_name = str(c_name) if c_name else ""
|
| 135 |
-
nts = str(nts) if nts else ""
|
| 136 |
quantities = [q0, q1, q2, q3, q4]
|
| 137 |
|
| 138 |
-
if not c_name
|
| 139 |
return "❌ 錯誤:請輸入顧客姓名", get_orders_data(), get_revenue()
|
| 140 |
|
| 141 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
@@ -156,15 +142,15 @@ def add_order(c_name, q0, q1, q2, q3, q4, nts):
|
|
| 156 |
total_price = price * qty
|
| 157 |
total_order_price += total_price
|
| 158 |
orders_db.append({
|
| 159 |
-
"時間": timestamp, "顧客姓名": c_name
|
| 160 |
-
"單價": price, "數量": qty, "總價": total_price, "備註": nts
|
| 161 |
})
|
| 162 |
items_desc.append(f"{item}x{qty}")
|
| 163 |
|
| 164 |
if not has_ordered_items:
|
| 165 |
return "❌ 錯誤:請至少設定一項商品的數量(大於 0)", get_orders_data(), get_revenue()
|
| 166 |
|
| 167 |
-
msg = f"✅ 成功新增訂單:{c_name
|
| 168 |
return msg, get_orders_data(), get_revenue()
|
| 169 |
|
| 170 |
except Exception as e:
|
|
@@ -191,7 +177,6 @@ def run_git_cmd(command):
|
|
| 191 |
def backup_and_push_to_github():
|
| 192 |
log_messages = ["🚀 開始備份...\n" + "-"*40]
|
| 193 |
|
| 194 |
-
# 只有這裡保留 pandas 供寫出 CSV 檔案使用
|
| 195 |
if not orders_db:
|
| 196 |
df = pd.DataFrame(columns=["時間", "顧客姓名", "商品", "單價", "數量", "總價", "備註"])
|
| 197 |
else:
|
|
@@ -282,8 +267,8 @@ with gr.Blocks(theme=gr.themes.Soft(), title="簡易訂單管理系統", css=cus
|
|
| 282 |
# ----------------------------
|
| 283 |
# 🚀 啟動伺服器
|
| 284 |
# ----------------------------
|
| 285 |
-
# 【關鍵修
|
| 286 |
-
app = gr.mount_gradio_app(custom_api, demo_ui, path="/")
|
| 287 |
|
| 288 |
if __name__ == "__main__":
|
| 289 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
import sys
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
try:
|
| 4 |
import gradio as gr
|
|
|
|
| 6 |
from datetime import datetime
|
| 7 |
import subprocess
|
| 8 |
from fastapi import FastAPI, Request, HTTPException
|
|
|
|
| 9 |
from linebot import LineBotApi, WebhookHandler
|
| 10 |
from linebot.exceptions import InvalidSignatureError
|
| 11 |
from linebot.models import MessageEvent, TextMessage, TextSendMessage
|
|
|
|
| 34 |
|
| 35 |
custom_api = FastAPI()
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
# ----------------------------
|
| 38 |
# 🛒 系統資料與設定
|
| 39 |
# ----------------------------
|
|
|
|
| 100 |
print(f"回覆失敗: {e}")
|
| 101 |
|
| 102 |
# ----------------------------
|
| 103 |
+
# 💻 網頁後台邏輯
|
| 104 |
# ----------------------------
|
| 105 |
def get_orders_data():
|
| 106 |
+
"""【關鍵修復 1】如果資料庫是空的,必須塞入一排空白資料,否則表格會直接讓網頁卡死!"""
|
| 107 |
if not orders_db:
|
| 108 |
+
return [["", "", "", "", "", "", ""]]
|
| 109 |
return [[o["時間"], o["顧客姓名"], o["商品"], o["單價"], o["數量"], o["總價"], o["備註"]] for o in orders_db]
|
| 110 |
|
| 111 |
def get_revenue():
|
|
|
|
| 117 |
|
| 118 |
def add_order(c_name, q0, q1, q2, q3, q4, nts):
|
| 119 |
try:
|
| 120 |
+
c_name = str(c_name).strip() if c_name else ""
|
| 121 |
+
nts = str(nts).strip() if nts else ""
|
| 122 |
quantities = [q0, q1, q2, q3, q4]
|
| 123 |
|
| 124 |
+
if not c_name:
|
| 125 |
return "❌ 錯誤:請輸入顧客姓名", get_orders_data(), get_revenue()
|
| 126 |
|
| 127 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
| 142 |
total_price = price * qty
|
| 143 |
total_order_price += total_price
|
| 144 |
orders_db.append({
|
| 145 |
+
"時間": timestamp, "顧客姓名": c_name, "商品": item,
|
| 146 |
+
"單價": price, "數量": qty, "總價": total_price, "備註": nts
|
| 147 |
})
|
| 148 |
items_desc.append(f"{item}x{qty}")
|
| 149 |
|
| 150 |
if not has_ordered_items:
|
| 151 |
return "❌ 錯誤:請至少設定一項商品的數量(大於 0)", get_orders_data(), get_revenue()
|
| 152 |
|
| 153 |
+
msg = f"✅ 成功新增訂單:{c_name} 訂購了 {', '.join(items_desc)},總計 {total_order_price} 元。"
|
| 154 |
return msg, get_orders_data(), get_revenue()
|
| 155 |
|
| 156 |
except Exception as e:
|
|
|
|
| 177 |
def backup_and_push_to_github():
|
| 178 |
log_messages = ["🚀 開始備份...\n" + "-"*40]
|
| 179 |
|
|
|
|
| 180 |
if not orders_db:
|
| 181 |
df = pd.DataFrame(columns=["時間", "顧客姓名", "商品", "單價", "數量", "總價", "備註"])
|
| 182 |
else:
|
|
|
|
| 267 |
# ----------------------------
|
| 268 |
# 🚀 啟動伺服器
|
| 269 |
# ----------------------------
|
| 270 |
+
# 【關鍵修復 2】這裡絕對必須要加上 .queue(),才能支援 Gradio 4.x 的按鈕互動機制
|
| 271 |
+
app = gr.mount_gradio_app(custom_api, demo_ui.queue(), path="/")
|
| 272 |
|
| 273 |
if __name__ == "__main__":
|
| 274 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|