Update app.py
Browse files
app.py
CHANGED
|
@@ -1,19 +1,16 @@
|
|
| 1 |
from fastapi import FastAPI, File, UploadFile, HTTPException, Response
|
| 2 |
-
from pydantic import BaseModel
|
| 3 |
-
from typing import Optional
|
| 4 |
import uuid
|
| 5 |
-
import
|
| 6 |
-
import schedule
|
| 7 |
import time
|
| 8 |
import threading
|
| 9 |
-
import
|
| 10 |
|
| 11 |
app = FastAPI()
|
| 12 |
|
| 13 |
-
# In-
|
| 14 |
-
#
|
| 15 |
data_storage = {}
|
| 16 |
-
expiration_timeout =
|
| 17 |
|
| 18 |
def clean_expired_data():
|
| 19 |
global data_storage
|
|
@@ -21,8 +18,8 @@ def clean_expired_data():
|
|
| 21 |
data_storage = {key: value for key, value in data_storage.items() if current_time - value['uploaded_at'] < expiration_timeout}
|
| 22 |
print("Data storage cleaned.")
|
| 23 |
|
| 24 |
-
# Schedule data cleaning every
|
| 25 |
-
schedule.every(
|
| 26 |
|
| 27 |
def run_schedule():
|
| 28 |
while True:
|
|
@@ -34,62 +31,63 @@ thread = threading.Thread(target=run_schedule)
|
|
| 34 |
thread.daemon = True # So that it dies when main thread dies
|
| 35 |
thread.start()
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
@app.post("/upload/file")
|
| 42 |
-
async def
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
upload_id = str(uuid.uuid4())
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
-
|
| 57 |
-
async def upload_text(text_upload: TextUpload):
|
| 58 |
global data_storage
|
| 59 |
-
upload_id = str(uuid.uuid4())
|
| 60 |
data_storage[upload_id] = {
|
| 61 |
-
'
|
| 62 |
-
'file_name':
|
| 63 |
-
'file_data':
|
| 64 |
-
'
|
|
|
|
|
|
|
| 65 |
}
|
| 66 |
-
return {"upload_id": upload_id, "message": "Text uploaded successfully"}
|
| 67 |
|
| 68 |
-
|
| 69 |
-
async def download_file(upload_id: str):
|
| 70 |
global data_storage
|
| 71 |
if upload_id not in data_storage:
|
| 72 |
-
raise HTTPException(status_code=404, detail="
|
| 73 |
-
|
| 74 |
-
upload_data = data_storage[upload_id]
|
| 75 |
-
file_name = upload_data['file_name']
|
| 76 |
-
|
| 77 |
-
# Guess the MIME type based on the file extension
|
| 78 |
-
mime_type, _ = mimetypes.guess_type(file_name)
|
| 79 |
-
if mime_type is None: # Default to octet-stream if type is unknown
|
| 80 |
-
mime_type = "application/octet-stream"
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
file_name += '.txt'
|
| 88 |
|
| 89 |
-
return Response(content=
|
| 90 |
headers={"Content-Disposition": f"attachment; filename={file_name}"})
|
| 91 |
|
| 92 |
if __name__ == "__main__":
|
| 93 |
-
scheduled_function()
|
| 94 |
import uvicorn
|
| 95 |
uvicorn.run(app, host="0.0.0.0", port=8083)
|
|
|
|
| 1 |
from fastapi import FastAPI, File, UploadFile, HTTPException, Response
|
|
|
|
|
|
|
| 2 |
import uuid
|
| 3 |
+
import mimetypes
|
|
|
|
| 4 |
import time
|
| 5 |
import threading
|
| 6 |
+
import schedule
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
| 10 |
+
# **In-Memory Storage (FOR DEMO ONLY)**
|
| 11 |
+
# Replace with Redis, NoSQL DB, or Cloud Storage for Production
|
| 12 |
data_storage = {}
|
| 13 |
+
expiration_timeout = 5 * 60 # 5 minutes in seconds
|
| 14 |
|
| 15 |
def clean_expired_data():
|
| 16 |
global data_storage
|
|
|
|
| 18 |
data_storage = {key: value for key, value in data_storage.items() if current_time - value['uploaded_at'] < expiration_timeout}
|
| 19 |
print("Data storage cleaned.")
|
| 20 |
|
| 21 |
+
# Schedule data cleaning every minute
|
| 22 |
+
schedule.every(1).minutes.do(clean_expired_data)
|
| 23 |
|
| 24 |
def run_schedule():
|
| 25 |
while True:
|
|
|
|
| 31 |
thread.daemon = True # So that it dies when main thread dies
|
| 32 |
thread.start()
|
| 33 |
|
| 34 |
+
@app.post("/upload/file/auto-link")
|
| 35 |
+
async def upload_file_auto_link(file: UploadFile = File(...)):
|
| 36 |
+
upload_id = str(uuid.uuid4())
|
| 37 |
+
file_name = file.filename
|
| 38 |
+
mime_type = file.content_type
|
| 39 |
+
await _store_file(upload_id, file_name, await file.read(), mime_type)
|
| 40 |
+
return {"download_link": f"/download/auto/{upload_id}", "message": "File uploaded successfully"}
|
| 41 |
|
| 42 |
+
@app.post("/upload/file/custom-link")
|
| 43 |
+
async def upload_file_custom_link(link: str, file: UploadFile = File(...)):
|
| 44 |
+
# Ensure link doesn't collide and is URL-friendly (simplified for demo)
|
| 45 |
+
if link in [item['custom_link'] for item in data_storage.values() if 'custom_link' in item]:
|
| 46 |
+
link += f"_{str(uuid.uuid4())[:5]}" # Append unique suffix
|
| 47 |
+
print(f"Link collision detected. New link: {link}")
|
| 48 |
+
|
| 49 |
upload_id = str(uuid.uuid4())
|
| 50 |
+
file_name = file.filename
|
| 51 |
+
mime_type = file.content_type
|
| 52 |
+
await _store_file(upload_id, file_name, await file.read(), mime_type, custom_link=link)
|
| 53 |
+
return {"download_link": f"/download/custom/{link}", "message": "File uploaded successfully"}
|
| 54 |
+
|
| 55 |
+
@app.get("/download/auto/{upload_id}")
|
| 56 |
+
async def download_file_auto(upload_id: str):
|
| 57 |
+
return await _handle_download(upload_id)
|
| 58 |
+
|
| 59 |
+
@app.get("/download/custom/{link}")
|
| 60 |
+
async def download_file_custom(link: str):
|
| 61 |
+
for item in data_storage.values():
|
| 62 |
+
if 'custom_link' in item and item['custom_link'] == link:
|
| 63 |
+
return await _handle_download(item['upload_id'], item['file_name'], item['file_data'], item['mime_type'])
|
| 64 |
+
raise HTTPException(status_code=404, detail="File not found")
|
| 65 |
|
| 66 |
+
async def _store_file(upload_id, file_name, file_data, mime_type, custom_link=None):
|
|
|
|
| 67 |
global data_storage
|
|
|
|
| 68 |
data_storage[upload_id] = {
|
| 69 |
+
'upload_id': upload_id,
|
| 70 |
+
'file_name': file_name,
|
| 71 |
+
'file_data': file_data,
|
| 72 |
+
'ime_type': mime_type,
|
| 73 |
+
'uploaded_at': time.time(),
|
| 74 |
+
'custom_link': custom_link # Optional
|
| 75 |
}
|
|
|
|
| 76 |
|
| 77 |
+
async def _handle_download(upload_id, file_name=None, file_data=None, mime_type=None):
|
|
|
|
| 78 |
global data_storage
|
| 79 |
if upload_id not in data_storage:
|
| 80 |
+
raise HTTPException(status_code=404, detail="File not found or has expired")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
+
if not file_name or not file_data or not mime_type:
|
| 83 |
+
upload_data = data_storage[upload_id]
|
| 84 |
+
file_name = upload_data['file_name']
|
| 85 |
+
file_data = upload_data['file_data']
|
| 86 |
+
mime_type = upload_data['mime_type'] or mimetypes.guess_type(file_name)[0] or "application/octet-stream"
|
|
|
|
| 87 |
|
| 88 |
+
return Response(content=file_data, media_type=mime_type,
|
| 89 |
headers={"Content-Disposition": f"attachment; filename={file_name}"})
|
| 90 |
|
| 91 |
if __name__ == "__main__":
|
|
|
|
| 92 |
import uvicorn
|
| 93 |
uvicorn.run(app, host="0.0.0.0", port=8083)
|