Python sanic.response.file_stream() Examples

The following are 8 code examples of sanic.response.file_stream(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sanic.response , or try the search function .
Example #1
Source File: test_agent.py    From rasa_core with Apache License 2.0 6 votes vote down vote up
def model_server_app(model_path: Text, model_hash: Text = "somehash"):
    app = Sanic(__name__)
    app.number_of_model_requests = 0

    @app.route("/model", methods=['GET'])
    async def model(request):
        """Simple HTTP model server responding with a trained model."""

        if model_hash == request.headers.get("If-None-Match"):
            return response.text("", 204)

        app.number_of_model_requests += 1

        return await response.file_stream(
            location=model_path,
            headers={'ETag': model_hash,
                     'filename': model_path},
            mime_type='application/zip')

    return app 
Example #2
Source File: test_agent.py    From rasa-for-botfront with Apache License 2.0 6 votes vote down vote up
def model_server_app(model_path: Text, model_hash: Text = "somehash") -> Sanic:
    app = Sanic(__name__)
    app.number_of_model_requests = 0

    @app.route("/model", methods=["GET"])
    async def model(request: Request) -> StreamingHTTPResponse:
        """Simple HTTP model server responding with a trained model."""

        if model_hash == request.headers.get("If-None-Match"):
            return response.text("", 204)

        app.number_of_model_requests += 1

        return await response.file_stream(
            location=model_path,
            headers={"ETag": model_hash, "filename": model_path},
            mime_type="application/gzip",
        )

    return app 
Example #3
Source File: run_asgi.py    From sanic with MIT License 5 votes vote down vote up
def handler_file_stream(request):
    return await response.file_stream(
        Path("../") / "setup.py", chunk_size=1024
    ) 
Example #4
Source File: try_everything.py    From sanic with MIT License 5 votes vote down vote up
def test_file_stream(request):
    return await response.file_stream(os.path.abspath("setup.py"),
                                      chunk_size=1024)

# ----------------------------------------------- #
# Exceptions
# ----------------------------------------------- # 
Example #5
Source File: static.py    From project-black with GNU General Public License v2.0 5 votes vote down vote up
def cb_index_handler(request, project_uuid=None, host=None):
        return await response.file_stream(os.path.abspath('./public/index.html')) 
Example #6
Source File: static.py    From project-black with GNU General Public License v2.0 5 votes vote down vote up
def cb_bundle_handler(request):
        return await response.file_stream(os.path.abspath('./public/bundle.js')) 
Example #7
Source File: static.py    From project-black with GNU General Public License v2.0 5 votes vote down vote up
def cb_serve_media_file(request, filename=""):
        return await response.file_stream(os.path.join('./public', os.path.basename(request.path))) 
Example #8
Source File: sanic.py    From idom with MIT License 4 votes vote down vote up
def _setup_blueprint_routes(self, blueprint: Blueprint, config: Config) -> None:
        """Add routes to the application blueprint"""

        @blueprint.websocket("/stream")  # type: ignore
        async def model_stream(
            request: request.Request, socket: WebSocketCommonProtocol
        ) -> None:
            async def sock_recv() -> LayoutEvent:
                message = json.loads(await socket.recv())
                event = message["body"]["event"]
                return LayoutEvent(event["target"], event["data"])

            async def sock_send(data: Dict[str, Any]) -> None:
                message = {"header": {}, "body": {"render": data}}
                await socket.send(json.dumps(message, separators=(",", ":")))

            param_dict = {k: request.args.get(k) for k in request.args}
            await self._run_renderer(sock_send, sock_recv, param_dict)

        def handler_name(function: Any) -> str:
            return f"{blueprint.name}.{function.__name__}"

        if config["server_static_files"]:

            @blueprint.route("/client/<path:path>")  # type: ignore
            async def client_files(
                request: request.Request, path: str
            ) -> response.HTTPResponse:
                file_extensions = [".html", ".js", ".json"]
                abs_path = find_path(path)
                return (
                    (await response.file_stream(str(abs_path)))
                    if abs_path is not None and abs_path.suffix in file_extensions
                    else response.text(f"Could not find: {path!r}", status=404)
                )

        if config["redirect_root_to_index"]:

            @blueprint.route("/")  # type: ignore
            def redirect_to_index(request: request.Request) -> response.HTTPResponse:
                return response.redirect(
                    request.app.url_for(handler_name(client_files), path="index.html")
                )