File size: 2,649 Bytes
1bba663
 
 
fe14e96
1bba663
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3dbc374
 
1bba663
 
908064b
1bba663
 
 
 
 
908064b
 
 
 
1bba663
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
from fastapi import FastAPI, Request, Response, Form, Header, HTTPException, BackgroundTasks
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware  # 匯入 FastAPI 的 CORS 中介軟體
from fastapi.staticfiles import StaticFiles

from typing import Annotated # 推薦用於 Pydantic v2+
import pandas as pd
import os

import json
import io
import os
from datetime import datetime
import uvicorn
from dotenv import load_dotenv # 匯入 dotenv 以載入 .env 環境變數檔案

STATIC_DIR = "static"

os.environ["TORCH_HOME"] = "./.cache"
os.environ["HF_HOME"] = "./.cache"
os.environ["TRANSFORMERS_CACHE"] = "./.cache"
os.makedirs("./.cache", exist_ok=True)
os.makedirs(STATIC_DIR, exist_ok=True)

load_dotenv()

# =====================
# 初始化 FastAPI
# =====================
app = FastAPI(title="Crypt Price")

app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
# 設定 CORS (跨來源資源共用)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允許所有來源
    allow_credentials=True,  # 允許憑證
    allow_methods=["*"],  # 允許所有 HTTP 方法
    allow_headers=["*"],  # 允許所有 HTTP 標頭
)

# =====================
# API 路由
# =====================
@app.get("/")
def root():
    return {"message": "Crypt Price API ready!"}

@app.get("/history")
async def cryptohistory():
    try:
        print("### start /cryptohistory !!")

        file_path = os.path.join("static", "eth_history.csv")

        # 讀取 CSV
        df = pd.read_csv(file_path)

        # 標準化欄位名稱
        df.columns = df.columns.str.lower()

        # 轉換日期格式
        #df["date"] = pd.to_datetime(df["date"]).dt.strftime("%Y-%m-%d")
        df["date"] = df["date"].astype(str)

        # 建立回傳資料
        # date,open,high,low,close,volume
        results = []
        for idx, row in df.iterrows():
            results.append({
                "id": idx + 1,
                "date": row["date"],
                "open": float(row["open"]),
                "high": float(row["high"]),
                "low": float(row["low"]),
                "close": float(row["close"]),
                "volume": float(row["volume"])
            })

        return {
            "status": "success",
            "data": results
        }

    except Exception as e:
        return JSONResponse(
            status_code=500,
            content={
                "status": "error",
                "message": str(e)
            }
        )
    

if __name__ == "__main__":
    uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=False)