Update app.py
Browse files12342 unmodified lines78910111213141516171819202122232425262728293031323334354 unmodified lines4041424344454647484950515253545556575859601 unmodified line626364656667686970717273747576777879808182838485868788from fastapi import FastAPI, Request, Responsefrom fastapi.responses import HTMLResponsefrom fastapi.templating import Jinja2Templatesfrom pydantic import BaseModel2 unmodified linesimport csvimport ioimport osapp = FastAPI()# --- 1. 載入對照表 ---product_db = {}def load_products():"""從 CSV 讀取商品對照表到記憶體"""global product_db# 檢查檔案是否存在,避免報錯if os.path.exists("products.csv"):with open("products.csv", mode="r", encoding="utf-8") as f:reader = csv.reader(f)next(reader, None) # 跳過標題列for row in reader:if len(row) >= 2:# key: 條碼, value: 名稱product_db[row[0].strip()] = row[1].strip()print(f"已載入 {len(product_db)} 筆商品資料")else:print("警告:找不到 products.csv,將只顯示條碼")# 啟動時先載入一次load_products()scan_records = []4 unmodified lines@app.get("/", response_class=HTMLResponse)async def read_root(request: Request):return templates.TemplateResponse("index.html", {"request": request, "records": scan_records[:15]})@app.post("/api/scan")async def receive_scan(item: ScanItem):# --- 2. 進行比對 ---code = item.qr_content.strip()# 如果字典裡有這個 code 就抓名稱,沒有就顯示 '未知物品'p_name = product_db.get(code, "未知物品")new_record = {"content": code,"name": p_name, # 新增名稱欄位"time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}scan_records.insert(0, new_record)return {"status": "success", "data": new_record}1 unmodified lineasync def download_csv():stream = io.StringIO()writer = csv.writer(stream)# --- 3. 下載時多一欄 '物品名稱' ---writer.writerow(["掃描內容", "物品名稱", "掃描時間"])for record in scan_records:writer.writerow([record["content"], record["name"], record["time"]])csv_content = stream.getvalue()final_content = "\ufeff" + csv_contentreturn Response(content=final_content,media_type="text/csv",headers={"Content-Disposition": "attachment; filename=scan_results.csv"})# 用來重新載入 CSV 的 API (可選,方便更新對照表後不用重啟 Space)@app.get("/reload_db")async def reload_db():load_products()return {"message": f"對照表已更新,目前有 {len(product_db)} 筆資料"}if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=7860)12342 unmodified lines789101112131415161718192021222324252627282930313233343536373839404142434 unmodified lines48495051525354555657585960616263646566676869707172737475767778798081828384858687881 unmodified line90919293949596979899100101from fastapi import FastAPI, Request, Response, UploadFile, Filefrom fastapi.responses import HTMLResponsefrom fastapi.templating import Jinja2Templatesfrom pydantic import BaseModel2 unmodified linesimport csvimport ioimport osimport shutilapp = FastAPI()# 全域變數:商品對照表product_db = {}# --- 核心功能:讀取 CSV 到記憶體 ---def load_products():"""從 CSV 讀取商品對照表到記憶體"""global product_dbproduct_db = {} # 先清空舊資料if os.path.exists("products.csv"):try:# 嘗試用 UTF-8 讀取with open("products.csv", mode="r", encoding="utf-8") as f:reader = csv.reader(f)# 嘗試讀取第一行,如果是標題就跳過header = next(reader, None)for row in reader:if len(row) >= 2:# row[0] 是條碼, row[1] 是名稱product_db[row[0].strip()] = row[1].strip()print(f"✅ 已載入 {len(product_db)} 筆商品資料")except Exception as e:print(f"❌ 讀取 CSV 失敗: {e}")else:print("⚠️ 找不到 products.csv")# 啟動時載入一次load_products()scan_records = []4 unmodified lines@app.get("/", response_class=HTMLResponse)async def read_root(request: Request):# 傳遞目前的對照表數量給前端顯示db_count = len(product_db)return templates.TemplateResponse("index.html", {"request": request,"records": scan_records[:15],"db_count": db_count})# --- 新增:上傳 CSV 的 API ---@app.post("/api/upload_csv")async def upload_csv(file: UploadFile = File(...)):# 1. 將上傳的檔案存為 products.csv (覆蓋舊的)with open("products.csv", "wb") as buffer:shutil.copyfileobj(file.file, buffer)# 2. 立即重新載入記憶體load_products()return {"status": "success","message": f"更新成功!目前資料庫有 {len(product_db)} 筆商品。","count": len(product_db)}@app.post("/api/scan")async def receive_scan(item: ScanItem):code = item.qr_content.strip()# 查表p_name = product_db.get(code, "未知物品")new_record = {"content": code,"name": p_name,"time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}scan_records.insert(0, new_record)return {"status": "success", "data": new_record}1 unmodified lineasync def download_csv():stream = io.StringIO()writer = csv.writer(stream)writer.writerow(["掃描內容", "物品名稱", "掃描時間"])for record in scan_records:writer.writerow([record["content"], record["name"], record["time"]])csv_content = stream.getvalue()final_content = "\ufeff" + csv_contentreturn Response(content=final_content, media_type="text/csv", headers={"Content-Disposition": "attachment; filename=scan_results.csv"})if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=7860)
app.py+47-34