-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
47 lines (36 loc) · 1.17 KB
/
main.py
File metadata and controls
47 lines (36 loc) · 1.17 KB
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
import os
import pandas as pd
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
# Define a Pydantic model for request validation
class Item(BaseModel):
name: str
message: str
# Use /tmp/ for storage since Render restricts writing to the root directory
CSV_FILE = "/tmp/data.csv"
# Initialize CSV file if it does not exist
if not os.path.exists(CSV_FILE):
df = pd.DataFrame(columns=["name", "message"])
df.to_csv(CSV_FILE, index=False)
# Root endpoint to check if API is running
@app.get("/")
def root():
return {"message": "FastAPI is running!"}
# POST request to receive data
@app.post("/data")
def receive_data(item: Item):
# Read the existing CSV file
df = pd.read_csv(CSV_FILE)
# Append the new data
new_data = pd.DataFrame([{"name": item.name, "message": item.message}])
df = pd.concat([df, new_data], ignore_index=True)
# Save back to CSV
df.to_csv(CSV_FILE, index=False)
return {"message": "Data saved successfully", "data": item}
# GET request to retrieve all data
@app.get("/data")
def get_data():
# Read the existing CSV file
df = pd.read_csv(CSV_FILE)
return df.to_dict(orient="records")