Update app.py
Browse files5 unmodified lines678910111213141516171 unmodified line1920212223242526272829303132333435363738394041424344454647484950515253545556575859606162635 unmodified linesimport uvicornimport csvimport ioapp = FastAPI()# 模擬資料庫 (Space 重啟後會清空)scan_records = []templates = Jinja2Templates(directory="templates")class ScanItem(BaseModel):1 unmodified line@app.get("/", response_class=HTMLResponse)async def read_root(request: Request):# 這裡我們只顯示最新的 10 筆在網頁上,以免頁面太長return templates.TemplateResponse("index.html", {"request": request, "records": scan_records[:10]})@app.post("/api/scan")async def receive_scan(item: ScanItem):new_record = {"content": item.qr_content,"time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}# 新資料插在最前面scan_records.insert(0, new_record)return {"status": "success", "data": new_record}# --- 新增:下載 CSV 的功能 ---@app.get("/download")async def download_csv():# 使用 StringIO 在記憶體中建立 CSVstream = io.StringIO()writer = csv.writer(stream)# 寫入表頭writer.writerow(["掃描內容", "掃描時間"])# 寫入所有資料for record in scan_records:writer.writerow([record["content"], record["time"]])# 取得 CSV 字串內容csv_content = stream.getvalue()# 加入 BOM (\ufeff) 讓 Excel 開啟時中文不亂碼final_content = "\ufeff" + csv_content# 回傳檔案return Response(content=final_content,media_type="text/csv",headers={"Content-Disposition": "attachment; filename=scan_records.csv"})if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=7860)5 unmodified lines678910111213141516171819202122232425262728293031323334353637381 unmodified line404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687885 unmodified linesimport uvicornimport 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 = []templates = Jinja2Templates(directory="templates")class ScanItem(BaseModel):1 unmodified line@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}@app.get("/download")async 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)
app.py+42-17