Python starlette.responses.HTMLResponse() Examples

The following are 11 code examples of starlette.responses.HTMLResponse(). 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 starlette.responses , or try the search function .
Example #1
Source File: starlette_plugin.py    From spectree with Apache License 2.0 6 votes vote down vote up
def register_route(self, app):
        self.app = app
        from starlette.responses import JSONResponse, HTMLResponse

        self.app.add_route(
            self.config.spec_url,
            lambda request: JSONResponse(self.spectree.spec),
        )

        for ui in PAGES:
            self.app.add_route(
                f'/{self.config.PATH}/{ui}',
                lambda request, ui=ui: HTMLResponse(
                    PAGES[ui].format(self.config.spec_url)
                ),
            ) 
Example #2
Source File: ftfy_app.py    From ftfy-web with Apache License 2.0 6 votes vote down vote up
def homepage(request):
    s = request.query_params.getlist("s")
    if s:
        s = s[0].strip()
        fixed, steps = fix_encoding_and_explain(s)
        return HTMLResponse(
            INDEX.format(
                output="<textarea>{}</textarea>".format(escape(fixed)),
                steps=escape(steps_to_python(s, steps)),
                s=escape(s),
                examples="\n".join(examples),
            )
        )
    else:
        return HTMLResponse(
            INDEX.format(output="", s="", steps="", examples="\n".join(examples),)
        ) 
Example #3
Source File: docs.py    From fastapi with MIT License 5 votes vote down vote up
def get_redoc_html(
    *,
    openapi_url: str,
    title: str,
    redoc_js_url: str = "https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js",
    redoc_favicon_url: str = "https://fastapi.tiangolo.com/img/favicon.png",
    with_google_fonts: bool = True,
) -> HTMLResponse:
    html = f"""
    <!DOCTYPE html>
    <html>
    <head>
    <title>{title}</title>
    <!-- needed for adaptive design -->
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    """
    if with_google_fonts:
        html += """
    <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
    """
    html += f"""
    <link rel="shortcut icon" href="{redoc_favicon_url}">
    <!--
    ReDoc doesn't change outer page styles
    -->
    <style>
      body {{
        margin: 0;
        padding: 0;
      }}
    </style>
    </head>
    <body>
    <redoc spec-url="{openapi_url}"></redoc>
    <script src="{redoc_js_url}"> </script>
    </body>
    </html>
    """
    return HTMLResponse(html) 
Example #4
Source File: asgi.py    From ariadne with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render_playground(  # pylint: disable=unused-argument
        self, request: Request
    ) -> Response:
        return HTMLResponse(PLAYGROUND_HTML) 
Example #5
Source File: core.py    From swagger-ui-py with Apache License 2.0 5 votes vote down vote up
def _starlette_handler(self):
        from starlette.responses import HTMLResponse, JSONResponse
        from starlette.staticfiles import StaticFiles

        async def swagger_doc_handler(request):
            return HTMLResponse(content=self.doc_html, media_type='text/html')

        async def swagger_editor_handler(request):
            return JSONResponse(content=self.editor_html, media_type='text/html')

        async def swagger_config_handler(request):
            host = '{}:{}'.format(request.url.hostname, request.url.port)
            return JSONResponse(self.get_config(host))

        self._app.router.add_route(self._uri(''), swagger_doc_handler, ['get'], 'swagger-ui')
        self._app.router.add_route(self._uri('/'), swagger_doc_handler, ['get'], 'swagger-ui')

        if self._editor:
            self._app.router.add_route(
                self._uri('/editor'), swagger_editor_handler, ['get'], 'swagger-editor')

        self._app.router.add_route(self._uri('/swagger.json'),
                                   swagger_config_handler, ['get'], 'swagger-config')
        self._app.router.mount(self._uri('/'),
                               app=StaticFiles(directory='{}/'.format(self.static_dir)),
                               name='swagger-static-files') 
Example #6
Source File: server.py    From google-app-engine with MIT License 5 votes vote down vote up
def index(request):
    html = path/'view'/'index.html'
    return HTMLResponse(html.open().read()) 
Example #7
Source File: _endpoints.py    From tartiflette-asgi with MIT License 5 votes vote down vote up
def get(self, request: Request) -> Response:
        config = get_graphql_config(request)
        graphql_endpoint = request["root_path"] + config.path
        subscriptions_endpoint = None
        if config.subscriptions:
            subscriptions_endpoint = request["root_path"] + config.subscriptions.path
        graphiql = config.graphiql
        assert graphiql is not None
        html = graphiql.render_template(
            graphql_endpoint=graphql_endpoint,
            subscriptions_endpoint=subscriptions_endpoint,
        )
        return HTMLResponse(html) 
Example #8
Source File: server.py    From Malaria-Detection-using-Keras with MIT License 5 votes vote down vote up
def index(request):
    html = path/'view'/'index.html'
    return HTMLResponse(html.open().read()) 
Example #9
Source File: view.py    From pygraphy with MIT License 5 votes vote down vote up
def get(self, request):
        html = get_playground_html(request.url.path, self.PLAYGROUND_SETTINGS)
        return HTMLResponse(html) 
Example #10
Source File: applications.py    From fastapi with MIT License 4 votes vote down vote up
def setup(self) -> None:
        if self.openapi_url:

            async def openapi(req: Request) -> JSONResponse:
                root_path = req.scope.get("root_path", "").rstrip("/")
                return JSONResponse(self.openapi(root_path))

            self.add_route(self.openapi_url, openapi, include_in_schema=False)
        if self.openapi_url and self.docs_url:

            async def swagger_ui_html(req: Request) -> HTMLResponse:
                root_path = req.scope.get("root_path", "").rstrip("/")
                openapi_url = root_path + self.openapi_url
                oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url
                if oauth2_redirect_url:
                    oauth2_redirect_url = root_path + oauth2_redirect_url
                return get_swagger_ui_html(
                    openapi_url=openapi_url,
                    title=self.title + " - Swagger UI",
                    oauth2_redirect_url=oauth2_redirect_url,
                    init_oauth=self.swagger_ui_init_oauth,
                )

            self.add_route(self.docs_url, swagger_ui_html, include_in_schema=False)

            if self.swagger_ui_oauth2_redirect_url:

                async def swagger_ui_redirect(req: Request) -> HTMLResponse:
                    return get_swagger_ui_oauth2_redirect_html()

                self.add_route(
                    self.swagger_ui_oauth2_redirect_url,
                    swagger_ui_redirect,
                    include_in_schema=False,
                )
        if self.openapi_url and self.redoc_url:

            async def redoc_html(req: Request) -> HTMLResponse:
                root_path = req.scope.get("root_path", "").rstrip("/")
                openapi_url = root_path + self.openapi_url
                return get_redoc_html(
                    openapi_url=openapi_url, title=self.title + " - ReDoc"
                )

            self.add_route(self.redoc_url, redoc_html, include_in_schema=False)
        self.add_exception_handler(HTTPException, http_exception_handler)
        self.add_exception_handler(
            RequestValidationError, request_validation_exception_handler
        ) 
Example #11
Source File: docs.py    From fastapi with MIT License 4 votes vote down vote up
def get_swagger_ui_html(
    *,
    openapi_url: str,
    title: str,
    swagger_js_url: str = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@3/swagger-ui-bundle.js",
    swagger_css_url: str = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@3/swagger-ui.css",
    swagger_favicon_url: str = "https://fastapi.tiangolo.com/img/favicon.png",
    oauth2_redirect_url: Optional[str] = None,
    init_oauth: Optional[dict] = None,
) -> HTMLResponse:

    html = f"""
    <!DOCTYPE html>
    <html>
    <head>
    <link type="text/css" rel="stylesheet" href="{swagger_css_url}">
    <link rel="shortcut icon" href="{swagger_favicon_url}">
    <title>{title}</title>
    </head>
    <body>
    <div id="swagger-ui">
    </div>
    <script src="{swagger_js_url}"></script>
    <!-- `SwaggerUIBundle` is now available on the page -->
    <script>
    const ui = SwaggerUIBundle({{
        url: '{openapi_url}',
    """

    if oauth2_redirect_url:
        html += f"oauth2RedirectUrl: window.location.origin + '{oauth2_redirect_url}',"

    html += """
        dom_id: '#swagger-ui',
        presets: [
        SwaggerUIBundle.presets.apis,
        SwaggerUIBundle.SwaggerUIStandalonePreset
        ],
        layout: "BaseLayout",
        deepLinking: true,
        showExtensions: true,
        showCommonExtensions: true
    })"""

    if init_oauth:
        html += f"""
        ui.initOAuth({json.dumps(jsonable_encoder(init_oauth))})
        """

    html += """
    </script>
    </body>
    </html>
    """
    return HTMLResponse(html)