1

I send a time.time() variable t0 to my template from FastAPI, which is the time update was triggered:

return templates.TemplateResponse("jobs.html", {
   "request": request, "jobs": sorted(out, key=lambda d: d['id'], reverse=True),
   "project_ids": ','.join([str(id) for id in myids]),
   "sorted_collumn": 'id',
   "filter": filter,
   "alljobs":alljobs,
   "nrecent": nrecent,
   "t0": t0
})

How can I time it at the end of rendering aka:

f"processtime:{time.time()-t0:.2f}sec"

time: {{ import time; time.time()-t0 }} 
jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got 'time'

or

time: {{ time.time()-t0 }}
jinja2.exceptions.UndefinedError: 'float object' has no attribute 'time'
Chris
  • 18,724
  • 6
  • 46
  • 80
MortenB
  • 2,749
  • 1
  • 31
  • 35
  • 1
    You might find [this answer](https://stackoverflow.com/a/73580096/17865804) helpful, which uses an `APIRoute` class to measure the time taken to process a request. – Chris Nov 28 '22 at 15:34

1 Answers1

1

Looking at the source code of Starlette (i.e., startlette/templating.py)

You can see the following line: env.globals["url_for"] = url_for in:

So adding the line:

templates.env.globals["now"] = time.time

before the return template above fixes it, and adding the below to jobs.html template:

time: {{ "{0:0.2f}".format(now()-t0) }} sec
time: 16.01 sec
Chris
  • 18,724
  • 6
  • 46
  • 80
MortenB
  • 2,749
  • 1
  • 31
  • 35
  • 1
    Similar approach has also been described [here](https://stackoverflow.com/a/71068465/17865804) to make classes/functions accessible from Jinja2 templates, when one needs to specify _query_, not only _path_, parameters in the `url_for()` function (may prove helpful to anyone who's facing similar issues). – Chris Nov 28 '22 at 17:29