async def download_file(request: Request, file_uuid: str, token: Optional[str] = Header(None)): file_record = await file_request_handler(file_uuid, request) return FileResponse(file_record.path, media_type=SupportedFormat.get_mime_type( file_record.type), filename=file_record.file_name)
async def get_attachment(workspace_name: str, document_name: str, attachment_name: str): """ TODO function docstring """ path = get_attachment_path(workspace_name, document_name, attachment_name) return FileResponse(path)
async def root(request: Request) -> FileResponse: persist = PERSIST[request.demand.cache_format.value](Path( request.directory)) df = persist.supply(request.demand, include_start=request.demand.start is None) path = persist.dump_path(request) persist.dump(path, df) return FileResponse(str(path))
def download(file_id: str, background_tasks: BackgroundTasks): cache_obj = Cache.objects.get(id=file_id) extension = cache_obj.mime_type new_file_to_download = str(uuid.uuid4()) + "." + extension with open(new_file_to_download, 'wb') as f: f.write(cache_obj.file.read()) background_tasks.add_task(remove_file, new_file_to_download) return FileResponse(new_file_to_download)
def download_clean_data(dataID: int): path = get_clean_data_path(dataID, Project21Database) #Have to put dataID here if (os.path.exists(path)): return FileResponse( path, media_type="text/csv", filename="clean_data.csv" ) #for this we need aiofiles to be installed. Use pip install aiofiles return {"Error": "Clean Data File not found at path"}
async def get_image(iid: str, response: Response): with open(os.path.join('database', 'images', 'registry.json'), 'r') as f: r = json.load(f) if iid in r.keys(): return FileResponse(r[iid]['path']) else: response.status_code = status.HTTP_404_NOT_FOUND return {'result': f'Image with IID {iid} does not exist.'}
async def trainModel(save: bool = False): MF.genDataSet() MF.getModel() if save: return FileResponse(path="./temp/model.joblib", filename="model.joblib") else: return TrainResponse(message="Training Success")
def send_file( fp: Union[str, io.BufferedIOBase], **kwargs ) -> Union[FileResponse, StreamingResponse]: kwargs.setdefault("headers", {}) kwargs["headers"]["Cache-Control"] = "no-cache" if isinstance(fp, str): return FileResponse(fp, **kwargs) return StreamingResponse(fp, **kwargs)
def get_theme(resource: str): final_path = os.path.join(frontend_dir, resource) logger.info(f"Getting file from {frontend_dir}") logger.info(final_path) if os.path.exists(final_path): return FileResponse(path=final_path) else: raise HTTPException(status_code=404)
async def download_file(file_name: str): path = os.path.join(MEDIA_DIR, file_name) if not os.path.isfile(path): raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="File not found.") return FileResponse(path)
async def get_job(job_uiid: UUID, db: Database = Depends(get_db)): try: path = get_job_csv(str(job_uiid), CSV_FOLDER) except FileNotFoundError: raise HTTPException(status_code=404, detail="Job CSV not found") return FileResponse(path, media_type="octet/stream", filename=DOWNLOAD_CSV_NAME)
async def get_audio(song_id: str): path = Filemanager.get_song_path(song_id) if Filemanager.file_exists(path): file = FileResponse(path) return file else: raise HTTPException(status_code=404, detail='Audio not found')
async def get_media(path: str): path = pathlib.Path(path) storage = ImageStorage.from_path(path) try: return FileResponse(str(storage.get_file(path.name))) except FileNotFoundError: raise HTTPException(status.HTTP_404_NOT_FOUND, f'File {path!r} does not exits')
async def read_tweeturl(q: Optional[str] = None): url_ = urllib.parse.unquote(q) file_name = "tweet" tweetimg.get_tweet(url_, file_name) await tweetimg.asyc_screenshot(file_name) path = tweetimg.autocrop(file_name) # return { "q": q, "tweet_url_path": path} return FileResponse(path)
async def download_battle_files(background_tasks: BackgroundTasks): export_dir = os.path.join(settings.TEMP_DIR, f'export_{secrets.token_urlsafe(16)}') zip_export_path = await db_export_csv(export_dir) background_tasks.add_task(rmdir, export_dir, settings.EXPORT_FILES_RM_DELAY) return FileResponse(path=zip_export_path, filename=Path(zip_export_path).name)
async def create_stretched_audio(rate: int, file: UploadFile = File(...)): y, sr = librosa.core.load(file, sr=None, mono=False) y_stretched0 = librosa.effects.pitch_shift(y[0], rate) y_stretched1 = librosa.effects.pitch_shift(y[1], rate) y_shift = np.array([y_stretched0, y_stretched1]) path = "~/new.wav" soundfile.write(path, y_shift, sr) return FileResponse(path)
async def _export_logs( workspace_id: uuid.UUID, log_id: uuid.UUID ): filepath = get_workspace_path(workspace_id, log_id, 'logging.log') if not Path(filepath).is_file(): raise HTTPException(status_code=404, detail=f'log file {log_id} not found in workspace {workspace_id}') else: return FileResponse(filepath)
def get_area_daily_data(area_id: str, date: date = Query(date.today().isoformat())): """ Returns a csv file containing the data detected by the area <area_id> for the date <date> """ validate_area_existence(area_id) dir_path = os.path.join(os.getenv("AreaLogDirectory"), area_id, "occupancy_log") if not os.path.exists(os.path.join(dir_path, f"{date}.csv")): raise HTTPException(status_code=404, detail=f"There is no data for the selected date.") return FileResponse(f"{dir_path}/{date}.csv", media_type="text/csv", filename=f"{date}_daily_data.csv")
async def download_image(): ''' async streams a file as a response ''' im = get_path('mangaimage', plate=8485, ifu=1901, drpver='v2_4_3', dir3d='stack') imname = get_path('mangaimage', full=im, ptype='name') return FileResponse(im, filename=imname, media_type='image/png')
def download_label(label: str, tag: str): instance: MONAILabelApp = app_instance() label = instance.datastore().get_label_uri(label, tag) if not os.path.isfile(label): raise HTTPException(status_code=404, detail="Label NOT Found") return FileResponse(label, media_type=get_mime_type(label), filename=os.path.basename(label))
def download_image(image: str): instance: MONAILabelApp = app_instance() image = instance.datastore().get_image_uri(image) if not os.path.isfile(image): raise HTTPException(status_code=404, detail="Image NOT Found") return FileResponse(image, media_type=get_mime_type(image), filename=os.path.basename(image))
def direct_address_request(address_request: AddressRequest): print("Received direct address request") address = address_request.address try: image_path = address_to_birds_eye(address) response = FileResponse(image_path) return response except Exception as e: return str(e)
async def downlaod_file(token: int, db: Session = Depends(get_db)): print(token) info = clishare_db.get_file_bytoken(db, token) if info is None: return "Invalid Token" else: return FileResponse(info.file_path + info.new_file_name, media_type='application/octet-stream', filename=info.file_name)
async def get_favicon() -> FileResponse: """Gets the favicon.ico and adds to the API endpoint. Returns: FileResponse: Uses FileResponse to send the favicon.ico to support the robinhood script's robinhood.html. """ if os.path.isfile('favicon.ico'): return FileResponse(filename='favicon.ico', path=os.getcwd(), status_code=HTTPStatus.OK.real)
async def start(): try: # detect_curling( # "./yolo/data/1.mp4", "./yolo/data/coordinates.txt" # ) draw() except: return JSONResponse(False, headers=headers) return FileResponse("./cutshow/3.jpeg", headers=headers)
def files(filename): filepath = f'root/{filename}' supported_extensions = ('png', 'txt', 'js', 'ico', 'html', 'css', 'webmanifest') if filename.split('.')[-1] in supported_extensions and isfile(filepath): return FileResponse(filepath) raise HTTPException( status_code=404, detail=f"Requested file('/{filename}') does not exist." )
async def get_upload_file(request: Request, filename: str, username: str = Depends(authen)): '''Dùng đẻ tải file tài liệu vào trang *get_quick_report*''' full_path = os.path.join(tai_lieu_folder, filename) if not full_path.lower().endswith('mp4'): return FileResponse(full_path) else: return MyResponse(full_path, request)
def download_file(file_hash: str): """Отправляет файл по хешу""" file_path = f'store/{file_hash[:2]}/{file_hash}' if os.path.exists(file_path): mimetype = magic.from_file(file_path, mime=True) return FileResponse(file_path, media_type=mimetype) else: return HTTPException(status_code=404, detail="Item not found")
async def get_file(suffix: str): """Returns a new file Returns: Returns a new file """ return FileResponse(suffix + '.csv')