Spaces:
Running
Running
from fastapi import FastAPI, File, UploadFile, Form, APIRouter | |
from typing import Optional | |
import json | |
import os | |
import aiofiles | |
import sys | |
sys.path.append('..') | |
from log_utils import build_logger | |
from constants import LOG_SERVER_SUBDOAMIN, APPEND_JSON, SAVE_IMAGE, SAVE_LOG | |
logger = build_logger("log_server", "log_server.log", add_remote_handler=False) | |
app = FastAPI() | |
router = APIRouter(prefix=f"/{LOG_SERVER_SUBDOAMIN}") | |
async def test(): | |
return "Successfully" | |
async def append_json(json_str: str = Form(...), file_name: str = Form(...)): | |
""" | |
Appends a JSON string to a specified file. | |
""" | |
# Convert the string back to a JSON object (dict) | |
data = json.loads(json_str) | |
# Append the data to the specified file | |
os.makedirs(os.path.dirname(file_name), exist_ok=True) | |
async with aiofiles.open(file_name, mode='a') as f: | |
await f.write(json.dumps(data) + "\n") | |
logger.info(f"Appended 1 JSON object to {file_name}") | |
return {"message": "JSON data appended successfully"} | |
async def save_image(image: UploadFile = File(...), image_path: str = Form(...)): | |
""" | |
Saves an uploaded image to the specified path. | |
""" | |
# Note: 'image_path' should include the file name and extension for the image to be saved. | |
os.makedirs(os.path.dirname(image_path), exist_ok=True) | |
async with aiofiles.open(image_path, mode='wb') as f: | |
content = await image.read() # Read the content of the uploaded image | |
await f.write(content) # Write the image content to a file | |
logger.info(f"Image saved successfully at {image_path}") | |
return {"message": f"Image saved successfully at {image_path}"} | |
async def save_log(message: str = Form(...), log_path: str = Form(...)): | |
""" | |
Save a log message to a specified log file on the server. | |
""" | |
# Ensure the directory for the log file exists | |
if os.path.dirname(log_path): | |
os.makedirs(os.path.dirname(log_path), exist_ok=True) | |
# Append the log message to the specified log file | |
async with aiofiles.open(log_path, mode='a') as f: | |
await f.write(f"{message}\n") | |
logger.info(f"Romote log message saved to {log_path}") | |
return {"message": f"Log message saved successfully to {log_path}"} | |
app.include_router(router) | |
if __name__ == "__main__": | |
import uvicorn | |
uvicorn.run(app, host="127.0.0.1", port=8000) |