aws / chalice

Python Serverless Microframework for AWS
Apache License 2.0
10.67k stars 1.01k forks source link

Unable to Render HTML Page with Chalice and Jinja2 #2071

Closed safaraliyevelmir closed 1 year ago

safaraliyevelmir commented 1 year ago

I am trying to render an HTML page using Chalice and Jinja2, but when I use the @route decorator to specify the route, the HTML page is not rendering as expected. Here's my code:

import os
from chalice.app import Blueprint, Response
import jinja2
from chalicelib.api.utils import route

routes = Blueprint(__name__)

def swagger_render(tpl_path):
    path, filename = os.path.split(tpl_path)
    env = jinja2.Environment(loader=jinja2.FileSystemLoader(path))

    try:
        # Load the template file
        template = env.get_template(filename)
        # Render the template
        rendered_template = template.render()

        return rendered_template
    except Exception as e:
        return f"Error rendering template: {str(e)}"

@route(routes, "/docs", methods=["GET"])
def docs():
    template = swagger_render("chalicelib/swagger/template/index.html")
    return Response(template, status_code=200, headers={"Content-Type": "text/html"})

The issue I'm experiencing is that when I access the /docs route, the HTML page is not being rendered as expected. Instead, it's returning the raw HTML code as text. The HTML page I'm trying to render looks like this:

<!DOCTYPE html>

My API

Expected Behavior:

I expect that when I access the /docs route, the HTML page should be rendered and displayed in the browser as shown in the provided HTML template.

Additional Information:

Chalice Version: 1.29.0 Python Version: python 3.10.12 Operating System: linux 6.2.0-32-generic Any help to resolve this issue would be greatly appreciated. Thank you!