當前位置: 首頁>>代碼示例>>Python>>正文


Python responses.FileResponse方法代碼示例

本文整理匯總了Python中starlette.responses.FileResponse方法的典型用法代碼示例。如果您正苦於以下問題:Python responses.FileResponse方法的具體用法?Python responses.FileResponse怎麽用?Python responses.FileResponse使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在starlette.responses的用法示例。


在下文中一共展示了responses.FileResponse方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: predict_image

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import FileResponse [as 別名]
def predict_image(model_name: str, input_data: UploadFile = File(...)):
	"""
	Draws bounding box(es) on image and returns it.
	:param model_name: Model name
	:param input_data: Image file
	:return: Image file
	"""
	try:
		output = await dl_service.run_model(model_name, input_data, draw=True, predict_batch=False)
		error_logging.info('request successful;' + str(output))
		return FileResponse("/main/result.jpg", media_type="image/jpg")
	except ApplicationError as e:
		error_logging.warning(model_name + ';' + str(e))
		return ApiResponse(success=False, error=e)
	except Exception as e:
		error_logging.error(model_name + ' ' + str(e))
		return ApiResponse(success=False, error='unexpected server error') 
開發者ID:BMW-InnovationLab,項目名稱:BMW-TensorFlow-Inference-API-CPU,代碼行數:19,代碼來源:start.py

示例2: run_model

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import FileResponse [as 別名]
def run_model(model_name: str, input_data: UploadFile = File(...)):
	"""
	Draws bounding box(es) on image and returns it.
	:param model_name: Model name
	:param input_data: Image file
	:return: Image file
	"""
	draw_boxes = True
	predict_batch = False
	try:
		output = await dl_service.run_model(model_name, input_data, draw_boxes, predict_batch)
		error_logging.info('request successful;' + str(output))
		return FileResponse("/main/result.jpg", media_type="image/jpg")
	except ApplicationError as e:
		error_logging.warning(model_name+';'+str(e))
		return ApiResponse(success=False, error=e)
	except Exception as e:
		error_logging.error(model_name+' '+str(e))
		return ApiResponse(success=False, error='unexpected server error') 
開發者ID:BMW-InnovationLab,項目名稱:BMW-TensorFlow-Training-GUI,代碼行數:21,代碼來源:start.py

示例3: get_validation

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import FileResponse [as 別名]
def get_validation():
    """Returns prediction on image with the latest saved weights \n
       Left image is the one predicted by the model and Right image is the ground truth"""
    if Path(prediction_image_path).exists():
        list_im: list = [prediction_image_path, ground_truth_image_path]
        imgs: list = [Image.open(str(i)) for i in list_im]

        min_shape: list = sorted([(np.sum(i.size), i.size) for i in imgs])[0][1]
        imgs_comb: np = np.hstack(list((np.asarray(i.resize(min_shape)) for i in imgs)))

        imgs_comb: Image = Image.fromarray(imgs_comb)
        collage_path: Path = working_dir / "collage.jpg"
        imgs_comb.save(collage_path)

        return FileResponse(collage_path, media_type="image/jpg")

    else:
        if ground_truth_image_path.exists():
            message: str = "No predictions yet"
        else:
            message: str = "No testing set was provided"

        result: dict = {"success": True, "start_time": get_time(), "message": message}
        return result 
開發者ID:BMW-InnovationLab,項目名稱:BMW-YOLOv3-Training-Automation,代碼行數:26,代碼來源:api.py

示例4: download_artifact

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import FileResponse [as 別名]
def download_artifact(request):
    run_uuid = request.path_params["run_uuid"]
    filepath = request.query_params.get("path", "")
    stream = to_bool(request.query_params.get("stream"), handle_none=True)
    force = to_bool(request.query_params.get("force"), handle_none=True)
    if not filepath:
        return Response(
            content="A `path` query param is required to stream a file content",
            status_code=status.HTTP_400_BAD_REQUEST,
        )
    subpath = "{}/{}".format(run_uuid, filepath).rstrip("/")
    archived_path = await download_file(subpath=subpath, check_cache=not force)
    if not archived_path:
        return Response(
            content="Artifact not found: filepath={}".format(archived_path),
            status_code=status.HTTP_404_NOT_FOUND,
        )
    if stream:
        return FileResponse(archived_path)
    return redirect(archived_path) 
開發者ID:polyaxon,項目名稱:polyaxon,代碼行數:22,代碼來源:endpoints.py

示例5: download

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import FileResponse [as 別名]
def download(job_id: str, ordinal: int, file_path: str) -> FileResponse:
    """
    Sends a file from given `file_path`. This path should come from
    results of one of the previous searches.

    This endpoint needs `job_id` that found the specified file, and `ordinal`
    (index of the file in that job), to ensure that user can't download
    arbitrary files (for example "/etc/passwd").
    """
    if not db.job_contains(JobId(job_id), ordinal, file_path):
        raise NotFound("No such file in result set.")

    attach_name, ext = os.path.splitext(os.path.basename(file_path))
    return FileResponse(file_path, filename=attach_name + ext + "_") 
開發者ID:CERT-Polska,項目名稱:mquery,代碼行數:16,代碼來源:app.py

示例6: serve_index

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import FileResponse [as 別名]
def serve_index(path: str) -> FileResponse:
    return FileResponse("mqueryfront/build/index.html") 
開發者ID:CERT-Polska,項目名稱:mquery,代碼行數:4,代碼來源:app.py

示例7: serve_index_sub

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import FileResponse [as 別名]
def serve_index_sub() -> FileResponse:
    return FileResponse("mqueryfront/build/index.html") 
開發者ID:CERT-Polska,項目名稱:mquery,代碼行數:4,代碼來源:app.py

示例8: ui

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import FileResponse [as 別名]
def ui(*args, **kwargs):
    return FileResponse('static/index.html') 
開發者ID:webrecorder,項目名稱:browsertrix,代碼行數:4,代碼來源:api.py

示例9: get_prediction

# 需要導入模塊: from starlette import responses [as 別名]
# 或者: from starlette.responses import FileResponse [as 別名]
def get_prediction(
    image: bytes = File(..., description="Image to perform inference on")
):
    """Runs the last saved weights to infer on the given image"""

    prediction_path: Path = working_dir / "predictions"
    training_path: Path = trainn_dir
    weights_path: Path = training_path / "weights"
    last_weights: list = list(weights_path.glob("*_last.weights"))

    if not last_weights:
        result: dict = {
            "success": True,
            "start_time": get_time(),
            "message": "No predictions yet",
        }
        return result

    if not prediction_path.exists():
        # Create folder in working directory symlinked to darknet/data/labels because it is needed by darknet to label the bounding boxes
        Path.mkdir(prediction_path)
        os.chdir(prediction_path)
        os.mkdir(Path("data"))
        os.symlink(
            working_dir / "darknet/data/labels", working_dir / "predictions/data/labels"
        )
    try:
        img: Image = Image.open(BytesIO(image)).convert("RGB")
        img.save("image.jpg")
        config_file_path: Path = training_path / "config"
        data_path: str = str(list(config_file_path.glob("*.data"))[0])
        cfg_path: str = str(list(config_file_path.glob("*.cfg"))[0])
        last_weights: str = str(last_weights[0])
        darknet_exec_path: Path = working_dir / "darknet/darknet"
        command: list = [
            darknet_exec_path,
            "detector",
            "test",
            data_path,
            cfg_path,
            last_weights,
            "-dont_show",
        ]
        command.append(str(working_dir / "predictions/image.jpg"))

        with open(os.devnull, "w") as DEVNULL:
            subprocess.call(command, stdout=DEVNULL, stderr=DEVNULL)

    except Exception as ex:
        raise HTTPException(
            422,
            detail="Error while reading request image. Please make sure it is a valid image {}".format(
                str(ex)
            ),
        )

    return FileResponse("predictions.jpg", media_type="image/jpg") 
開發者ID:BMW-InnovationLab,項目名稱:BMW-YOLOv3-Training-Automation,代碼行數:59,代碼來源:api.py


注:本文中的starlette.responses.FileResponse方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。