|
from fastapi import FastAPI, HTTPException |
|
from pydantic import BaseModel, EmailStr |
|
import random |
|
import string |
|
from datetime import datetime |
|
import json |
|
from pathlib import Path |
|
|
|
|
|
app = FastAPI() |
|
|
|
|
|
DB_FILE = Path("database.json") |
|
|
|
|
|
if not DB_FILE.exists(): |
|
DB_FILE.write_text(json.dumps([])) |
|
|
|
|
|
class Data(BaseModel): |
|
number: int |
|
email: EmailStr |
|
|
|
|
|
def generate_id(): |
|
return ''.join(random.choices(string.ascii_letters + string.digits, k=8)) |
|
|
|
|
|
def read_database(): |
|
with DB_FILE.open("r") as f: |
|
return json.load(f) |
|
|
|
|
|
def write_database(data): |
|
with DB_FILE.open("w") as f: |
|
json.dump(data, f, indent=4) |
|
|
|
|
|
@app.post("/add") |
|
def add_data(data: Data): |
|
database = read_database() |
|
new_entry = { |
|
"id": generate_id(), |
|
"date": datetime.utcnow().isoformat(), |
|
"number": data.number, |
|
"email": data.email, |
|
} |
|
database.append(new_entry) |
|
write_database(database) |
|
return new_entry |
|
|
|
|
|
@app.get("/data") |
|
def get_data(): |
|
return read_database() |
|
|
|
@app.get("/data/{item_id}") |
|
def get_data_by_id(item_id: str): |
|
database = read_database() |
|
for entry in database: |
|
if entry["id"] == item_id: |
|
return entry |
|
raise HTTPException(status_code=404, detail="Item not found") |
|
|