async def read_output(job_id: int): query = jobs.select(jobs.c.id == job_id) job = await database.fetch_one(query) path = f'output_zips/{job_id}.zip' if job is None or not os.path.exists(path): return None return FileResponse(path, filename=f'{job_id}.zip')
def download_shared_file( link: str, form: schemas.File_download, db: Session = Depends(get_db), ): file_path = crud.download_shared_file(db, link, form) if not file_path: raise HTTPException(status_code=400, detail="Such file doesn't exist") return FileResponse(file_path)
def download_notes(id: str): # Query `notes` and `dates` from `processed` table from notes # Create md file for file response # note, date are from the sql database md_file = tempfile.NamedTemporaryFile(delete=False, suffix='.md') fname = f'{date.date()}-notes.md' md_file.write(bytes(notes, encoding='utf-8')) return FileResponse(md_file.name, media_type="markdown", filename=fname)
def render_public(key: str): r = db.get(key) if r == None: return "404 not found" if "public" in r: if not r["public"]: return "404 not found" else: return FileResponse("./static/public.html") return "404 not found"
def text_to_tacotron_audio_file(data: TTSModel, model=Header(None)): try: text = data.text if len(text) > MAX_CHARACTERS: raise NotVIPplsPAYError("Too many chararacters.") wav_audio_file_path = controller.text_to_tacotron_audio_file( data.text, model) return FileResponse(str(wav_audio_file_path)) except Exception as e: raise HTTPException(status_code=500, detail=str(e))
def reload_qr(): # if the client id exists and not none and it's not loggedIn then reload qr if ( client_id in drivers and drivers[client_id] and drivers[client_id] != WhatsAPIDriverStatus.LoggedIn ): set_qr_code(drivers[client_id]) img_path = get_qr_image_path(client_id, with_border=True) return FileResponse(img_path, media_type="image/png") return {'error':'error reloading qr code'}
async def get_png(user_agent: Optional[str] = Header(None), os: str = ""): from_string(await get_html(user_agent, os), config.out_file) return FileResponse( config.out_file, headers={ "cache-control": "no-cache,max-age=0,no-store,s-maxage=0,proxy-revalidate", "expires": datetime.now().strftime("%a, %d %b %Y %H:%M:%S GMT"), }, )
def serve_pdf_document( document_request_key: str, output_dir: str = settings.output_dir() ) -> FileResponse: """Serve the requested PDF document.""" path = "{}.pdf".format(os.path.join(output_dir, document_request_key)) return FileResponse( path=path, filename=pathlib.Path(path).name, headers={"Content-Disposition": "attachment"}, )
async def image_endpoint(images: imageRequest): # Returns a cv2 image array from the document vector # img = Image.open('./'+images.name+"/image.B2.jpeg") folder = 'shots/' if images.folder == 'empty' else 'shots/' + images.folder path = [ n for n in os.listdir(folder + images.name + "/") if images.band in n and images.type in n ] print(path[0]) return FileResponse(folder + images.name + "/" + path[0])
def send_static_client(file_path: str): """ Serves all files from ./client/ to ``/client/{path}``. Used primarily for development. NGINX handles production. Args: file_path: Name of file in the client directory """ f = str(pf.DIST / file_path) print("Finding file: ", f) return FileResponse(f)
async def stream_video(videoId: str, resolution: str = '360p'): video: YoutubeVideoStream = await load_video(videoId, res=resolution) if video.is_stream: return StreamingResponse(video(), media_type=video.media_type, headers=video.headers) return FileResponse(video.filepath, media_type=video.media_type, filename=video.filename, background=delete_video(video.filepath))
async def gera_curriculo( request: Request, pessoa_id: int, db=Depends(get_db), current_pessoa=Depends(get_current_active_pessoa), ): pessoa = get_pessoa_by_id(db, pessoa_id) return FileResponse(createPDFcurriculo(db, pessoa))
async def get_score_img(match_url: str, count_warmup: int = 2, scoring_list: List[int] = (10, 6, 3, 1)): match = matchanalysis.Match(match_url, count_warmup) sdf = match.scored_match_df(scoring_list) img_out = img.gen_img(sdf, size=128) cv2.imwrite('result.jpg', img_out) sdf.to_csv(PATH_CSV_SAVE) return FileResponse('result.jpg')
def download(downlad_request: LsDataRequestBody, user_id: int = Depends(get_user_id)): """ task_id_list为空列表时,默认下载全部任务的打标数据 """ label_sys_id = downlad_request.label_sys_id task_id_list = downlad_request.task_id_list file_name = label_sys_op.label_sys_tagged_data_download( label_sys_id, task_id_list) return FileResponse('download_datasets/%s.csv' % file_name, filename='%s.csv' % file_name)
async def create_upload_file(file: UploadFile = File(...)): # 받은 파일을 새이름의 파일로 저장 filename = shortuuid.uuid() + ".png" saveFile = open('./api/' + filename, 'wb+') shutil.copyfileobj(file.file, saveFile) saveFile.close() cliHandlerApi() os.remove('./api/' + filename) return FileResponse('./api/blur/' + filename)
async def read_file_block(file_path: str): try: filename = get_filename(file_path) logger.info('%s: readblock from server %d', file_path, settings.server_id) file_path = os.path.join(settings.data_dir, filename) # buffer = await read_file_block_from_fs(file_path) # stream = io.BytesIO(buffer) return FileResponse(file_path, media_type='application/octet-stream') except Exception as e: logger.exception(e) raise HTTPException(400, str(e))
async def convert_to_dwg(request: Request, file_uuid: str, token: Optional[str] = Header(None)): file_record = await file_request_handler(file_uuid, request) dwg_response = await to_cad(file_record) if not dwg_response: raise_422_exception() file_name = f"{os.path.splitext(file_record.file_name)[0]}.dxf" return FileResponse(dwg_response, media_type='application/dxf', filename=file_name)
def download_pickle_file(modelID: int): path = get_pickle_file_path(modelID, Project21Database) #Have to put modelID here if (os.path.exists(path + '.pkl')): print("Path: ", path) return FileResponse( path + '.pkl', media_type="application/octet-stream", filename="model.pkl" ) #for this we need aiofiles to be installed. Use pip install aiofiles return {"Error": "File not found at path"}
def redirect(short: str, db: Session = Depends(get_db)): hsh = short.replace("-", "") url = crud.get_raw(db=db, hsh=hsh) if url is None: return FileResponse("public/404.html", status_code=404) if url.raw.startswith(("http://", "https://")): return RedirectResponse(url=f"{url.raw}") else: return RedirectResponse(url=f"http://{url.raw}")
async def read_item2(item_id: str, img: bool = None): if img: # print(item_id) res = os.path.exists("img.jpg") # 判断img.jpg是否在当前目录下,也就是运行文件的目录下 if not res: return JSONResponse(status_code=400, content={"message": "Item_id not found"}) print("hhhh") # 返回当前目录下的文件:img.jpg 文件 文件的类型可以为:image或png类型 return FileResponse("zero.png", media_type="image/png") else: return {"id": item_id, "value": "there goes my hero"}
async def download_model( background_tasks: BackgroundTasks, current_user: User = Depends(auth.get_current_user), ): """ Downloads latest trained model file """ try: model_path = AgentProcessor.get_latest_model(current_user.get_bot()) response = FileResponse( model_path, filename=os.path.basename(model_path), background=background_tasks, ) response.headers[ "Content-Disposition"] = "attachment; filename=" + os.path.basename( model_path) return response except Exception as e: raise AppException(str(e))
async def thumbnail(request: Request): try: document = get_request_document(request) params = await get_preview_generator_params(request, document) return FileResponse(document.get_jpeg_preview(params)) except DocumentTooBig: raise HTTPException(status_code=509, detail="Document too big") except DocumentNotPreviewable: raise HTTPException(status_code=403, detail="Document not previewable") except DocumentUnauthorized: raise HTTPException(status_code=401)
def response_image_file(filename:str, image_type:str): validPath = { 'original': os.environ.get('IMAGE_ORIGINAL_LOCAL_PATH'), 'thumbnail': os.environ.get('IMAGE_THUMBNAIL_LOCAL_PATH'), 'qrImage': os.environ.get('QR_IMAGE_LOCAL_PATH'), } if not Path(validPath[image_type] + filename).is_file(): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='File not found please recheck name') return FileResponse(validPath[image_type] + filename)
def send_static_client(file_path: str): """ Serves (makes accessible) all files from ``/client/dist/{path}``. Used primarily for development. NGINX handles production. NOTE: Not needed for Vue CLI Args: path: Name of file in the client directory """ f = str(pf.DIST / file_path) print("Finding file: ", f) return FileResponse(f)
def return_image(brcode): img = qrcode.make(brcode) with tempfile.NamedTemporaryFile(mode="w", suffix=".png", delete=False) as FOUT: img.save(FOUT.name) return FileResponse( FOUT.name, media_type="image/png", headers={ 'brcode': brcode } )
async def convert_to_geojson(request: Request, file_uuid: str, token: Optional[str] = Header(None)): file_record = await file_request_handler(file_uuid, request) geojson_response = await to_geojson(file_record, stream=False) if not geojson_response: raise_422_exception() file_name = f"{os.path.splitext(file_record.file_name)[0]}.json" return FileResponse(geojson_response, media_type='application/json', filename=file_name)
async def get_scan_result(scan_id: uuid.UUID, request: Request): scan = request.app.state.SCANS.get(scan_id) if not scan.stats.done: return JSONResponse({"error": "scan has not finished"}, status_code=status.HTTP_400_BAD_REQUEST) loop = asyncio.get_running_loop() zip_file = await loop.run_in_executor( None, functools.partial(zip_scan_folder, scan.report_folder)) return FileResponse(zip_file, media_type="application/zip")
async def designer(request: Request): vm = DesignViewModel(request) await vm.load() save_img = save_upload_file_tmp(vm.final_image) wb_text = vm.final_text artwork = create_artwork(wb_text, save_img) output_img = f"{IMG_OUTPUT_FLDR}/tmp_joined.png" return FileResponse(output_img)
def get_app_file(path: str) -> Response: path = safe_join(str(self.apps_dir), path) if os.path.exists(path): return FileResponse(path) return JSONResponse( status_code=404, content={ "success": False, "detail": f"File not found: {path}" }, )
async def get_result_csv(topic_name: TypeEnum): """ Exports the current results into a CSV file.""" field_names = list(results[topic_name.value][0].keys()) with open("results.csv", 'w', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=field_names) writer.writeheader() for data in results[topic_name.value]: writer.writerow(data) return FileResponse(path="results.csv", filename=f"{topic_name.value}.csv")