34 lines
1023 B
Python
34 lines
1023 B
Python
from typing import Annotated
|
|
import csv
|
|
import uvicorn
|
|
import datetime
|
|
from fastapi import FastAPI, Form
|
|
|
|
from .core.config import settings
|
|
from pydantic import BaseModel
|
|
|
|
app = FastAPI()
|
|
|
|
|
|
class Reading(BaseModel):
|
|
temperature: float
|
|
humidity: float
|
|
age: int
|
|
|
|
@app.post("/upload", response_model=Reading)
|
|
def add_reading(temp: Annotated[float, Form()], humidity: Annotated[float, Form()], age: Annotated[int, Form()], device: Annotated[str, Form()]):
|
|
current_datetime = datetime.datetime.now()
|
|
deducted_datetime = current_datetime - datetime.timedelta(milliseconds=age)
|
|
append_to_csv(settings.FILE_PATH, temp, humidity, deducted_datetime)
|
|
return Reading(temperature=temp,humidity=humidity,age=age)
|
|
|
|
|
|
def append_to_csv(filename, temperature, humidity, datetime_var):
|
|
with open(filename, 'a', newline='') as csvfile:
|
|
writer = csv.writer(csvfile)
|
|
writer.writerow([temperature, humidity, datetime_var])
|
|
|
|
|
|
def init():
|
|
uvicorn.run(app, host=settings.HOST, port=settings.PORT)
|