question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

CANNOT RENDER HTML IN FASTAPI

See original GitHub issue

I am a beginner in python and I am trying to build an app in fastapi.

My task is to get text from html, render html in fastpi run python code on the text and return the output to html page

This is my code

`from typing import Optional

from fastapi import FastAPI, Request, Response from fastapi.staticfiles import StaticFiles from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates,

app = FastAPI()

app.mount(“/static”, StaticFiles(directory=“static”), name=“static”)

templates = Jinja2Templates(directory=“templates”)

@app.get(“/”, response_class=HTMLResponse) async def get(): return templates.TemplateResponse(“layout.html”)

@app.post(“/”) async def post(request: Request): text = request.get(“sent”) `

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:18 (6 by maintainers)

github_iconTop GitHub Comments

12reactions
Kludexcommented, Aug 11, 2020

WE’D LOVE TO HELP YOU! ☮️

But we need your help first… 🏃

Can you:

  • Format your code snippet:
    • Image: image
    • Generated code:
from fastapi import FastAPI

app = FastAPI()
  • Be specific on how we can help you.
    • What is the problem?
    • What is failing?
    • What do you want to achieve?
  • Last but the most important: please, follow our question issue template. It makes us know where you have searched possible solutions, understand your issue better and several benefits for those who have the same problem as you and for those who are trying to help as well. 😎
1reaction
ricardo-reis-1970commented, Jul 30, 2021

Dear @siamhassan66,

I realise you got somewhere, but I can’t find your solution here. I came here to find help and I’m sure more people do the same. So, as promised, here is the solution I came up with, hoping the next person will find it useful.

My approach is to break away from templates.TemplateResponse, because I came to realise that this is designed to do just that: pack and send back a response. Instead, I use a two-step approach where I acquire a template — via templates.get_template — and then I render it with some values — via template.render.

This approach allows me to get the generated HTML, while doing away with the need to provide a request. This way, the whole processing can be done at middleware level.

Here’s the gist:

from fastapi.templating import Jinja2Templates

templates = Jinja2Templates(directory=r"manager_backend\templates")
template = templates.get_template("item.jinja2")

@app.get("/items/{id}")
async def read_item(id: str):
    text = template.render(id=id)
    response = whatever(text) # do some processing with the text
    return response

Please notice that, compared with the previous snippet:

  1. I changed the template from item.html to item.jinja2;
  2. the arguments to template.render don’t include the request, so I removed it from the path operation signature;
  3. the arguments to template.render are no longer a dict, but rather kwargs;
  4. I removed the response_class=HTMLResponse from the signature;
  5. in my particular case, the function is returning a pdf file, but this is not a saved file, so I could not use FileResponse; instead, I did something like this:
@router.get("/{id}")
def generate_report_id(id):
    pdf, file_name = generate_report(id)
    return Response(content = pdf, headers = {
        'Content-Type': 'application/pdf',
        'Content-Disposition': f'attachment; filename={file_name}',
        'x-suggested-filename': file_name,
    })

This allows me to click a button on the frontend and get a pdf downloaded.

I hope this helps. I wish I had something like this in the examples.

Read more comments on GitHub >

github_iconTop Results From Across the Web

FastAPI - render template in index.html - not working
Good day I am using FastAPI and I want to render the database contents on index.html - however I get the following error:...
Read more >
Templates - FastAPI
Use the templates you created to render and return a TemplateResponse , passing the request as one of the key-value pairs in the...
Read more >
FastAPI - render template in index.html - not working - Reddit
It seems that you are not passing the notes you're fetching from the database to your Jinja template. Instead, you're trying to pass...
Read more >
FastAPI Server HTML response using Jinja2 - Ultra Fast
If you want to render an html resource as the output for any of the routes, its very easy with the help of...
Read more >
Jinja2 Templates with FastAPI for Python - YouTube
This video covers how to use Jinja2 templates in a Python FastAPI appThe example code for this project can be found on GitHub...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found