3DGen-Arena / serve /log_server.py
ZhangYuhan's picture
update serve
716a927
raw
history blame
2.5 kB
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}")
@router.get(f"/test")
async def test():
return "Successfully"
@router.post(f"/{APPEND_JSON}")
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"}
@router.post(f"/{SAVE_IMAGE}")
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}"}
@router.post(f"/{SAVE_LOG}")
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)