lazerkat's picture
Update app.py
f874e7c verified
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
import json
import os
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
app = FastAPI()
# Enable CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Use /tmp directory which has write permissions
DB_FILE = "/tmp/content_db.json"
# Content model
class ContentItem(BaseModel):
title: str
type: str # "movie" or "series"
description: str
thumbnail: str
video_url: str
# Initialize database if it doesn't exist
if not os.path.exists(DB_FILE):
try:
with open(DB_FILE, "w") as f:
json.dump([], f)
except Exception as e:
print(f"Couldn't initialize database: {e}")
# Fallback to in-memory storage
in_memory_db = []
# Helper function to read content
def read_content():
try:
with open(DB_FILE, "r") as f:
return json.load(f)
except:
# Fallback to in-memory storage if file reading fails
return in_memory_db if 'in_memory_db' in globals() else []
# Helper function to write content
def write_content(content):
try:
with open(DB_FILE, "w") as f:
json.dump(content, f)
except:
# Fallback to in-memory storage if file writing fails
if 'in_memory_db' in globals():
global in_memory_db
in_memory_db = content
@app.get("/")
async def read_root():
return {"message": "Streaming Service API is running"}
@app.get("/get_content")
async def get_content():
return JSONResponse(content=read_content())
@app.post("/add_content")
async def add_content(item: ContentItem):
try:
content = read_content()
content.append(item.dict())
write_content(content)
return {"message": "Content added successfully"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# For Hugging Face Spaces
def get_app():
return app