当前位置: 首页>>代码示例>>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;未经允许,请勿转载。