Spaces:
paola1
/
Sleeping

api / app.py
paola1's picture
Update app.py
85fe8e5 verified
raw
history blame
3.2 kB
from fastapi import FastAPI, File, UploadFile, HTTPException, Response
from pydantic import BaseModel
from typing import Optional
import uuid
import os
import schedule
import time
import threading
import mimetypes
app = FastAPI()
# In-memory storage (NOT SUITABLE FOR PRODUCTION)
# Consider Redis or an embedded NoSQL DB for production
data_storage = {}
expiration_timeout = 15 * 60 # 15 minutes in seconds
def clean_expired_data():
global data_storage
current_time = time.time()
data_storage = {key: value for key, value in data_storage.items() if current_time - value['uploaded_at'] < expiration_timeout}
print("Data storage cleaned.")
# Schedule data cleaning every 15 minutes
schedule.every(15).minutes.do(clean_expired_data)
def run_schedule():
while True:
schedule.run_pending()
time.sleep(1)
# Start the scheduler in a separate thread
thread = threading.Thread(target=run_schedule)
thread.daemon = True # So that it dies when main thread dies
thread.start()
class TextUpload(BaseModel):
text: str
file_name: Optional[str] = "uploaded_text.txt"
@app.post("/upload/file")
async def upload_file(file: UploadFile = File(...)):
global data_storage
upload_id = str(uuid.uuid4())
data_storage[upload_id] = {
'data_type': "file",
'file_name': file.filename,
'file_data': await file.read(),
'uploaded_at': time.time()
}
# Optionally save file to filesystem (commented out for brevity)
# with open(f"uploads/{file.filename}", "wb") as f:
# f.write(await file.read())
return {"upload_id": upload_id, "message": "File uploaded successfully"}
@app.post("/upload/text")
async def upload_text(text_upload: TextUpload):
global data_storage
upload_id = str(uuid.uuid4())
data_storage[upload_id] = {
'data_type': "text",
'file_name': text_upload.file_name,
'file_data': text_upload.text.encode('utf-8'),
'uploaded_at': time.time()
}
return {"upload_id": upload_id, "message": "Text uploaded successfully"}
@app.get("/download/{upload_id}")
async def download_file(upload_id: str):
global data_storage
if upload_id not in data_storage:
raise HTTPException(status_code=404, detail="Upload not found or has expired")
upload_data = data_storage[upload_id]
file_name = upload_data['file_name']
# Guess the MIME type based on the file extension
mime_type, _ = mimetypes.guess_type(file_name)
if mime_type is None: # Default to octet-stream if type is unknown
mime_type = "application/octet-stream"
# For text uploads, ensure the MIME type is set correctly
if upload_data['data_type'] == "text":
mime_type = "text/plain"
# Optionally, force a `.txt` extension for text files if no extension is provided
if '.' not in file_name:
file_name += '.txt'
return Response(content=upload_data['file_data'], media_type=mime_type,
headers={"Content-Disposition": f"attachment; filename={file_name}"})
if __name__ == "__main__":
scheduled_function()
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8083)