Reputation: 1
QUESTION
Hello everyone,
I have developed an API that takes two parameters: a URL and a destination path. The purpose of this API is to fetch content from the given URL and save it to the specified path. When testing locally, the API successfully retrieves content from the URL and writes it to my desired location (e.g.,
Users/mustafaorcunucgun/Desktop/new_model
) without any issues.
However, when I run the same process on a Droplet and make requests via Postman, I encounter problems. The API behaves as if it's performing the operation correctly, meaning it does not return any error messages. Yet, I discover that the file has not been saved to the specified path afterward. In other words, even though I provide a path like
Users/user_id/Desktop/new_model
as a parameter, the file isn't being saved to this location upon completing the process.
Here is my code:
from fastapi import Form, HTTPException,APIRouter
from aiofiles import open as async_open
import requests
import os
router=APIRouter(
prefix="/upload_model",
tags=['upload_model']
)
@router.post("/")
async def upload_file(url: str= Form(...),path: str = Form(...)):
try:
response = requests.get(url)
response.raise_for_status()
content = response.content
directory, filename = os.path.split(path) # It divides the path input into two parts: the file name and the location where the file will be downloaded.
if not os.path.exists(directory):
os.makedirs(directory)
_, file_extension = os.path.splitext(filename) # It seperate file extension.
if file_extension not in ['.pth', '.h5']: # Only .pth and .h5 extensions are allowed.
raise HTTPException(status_code=400, detail="Unsupported file extension. Only .pth and .h5 are allowed.")
file_path = os.path.join(directory, filename)
async with async_open(file_path, 'wb') as file:
await file.write(content)
return f"File saved succesfully to this location: {directory}"
except Exception as e:
return HTTPException(status_code=400, detail=f"failure: {str(e)}")
Verified that the API functions as expected locally, saving files to the specified path.
Ensured permissions and paths were correct, and checked the validity of the path on the Droplet.
Experimented with Linux-compatible path formats and checked the API’s working directory.
Upvotes: 0
Views: 35