how to use url_for() to pass data to another route? fastapi & jinja2
I want to call a fastapi route from jinja2 template and pass data to the called route. All my attempts fail.
I tried something in the jinja2 template like {{ url_for('function1', uustr=data.uustr, interval=1) }}
this is the fastapi route I want to call (syntax simplified for demo purposes):
@app.get("/updates/data/{uustr}",response_class=HTMLResponse)
async def function1(request: Request, uustr:str, interval:int):
return"""
<html>
<head>
<title>{{ uustr }}</title>
</head>
<body>
<h1>{{ interval }}</h1>
</body>
</html>
"""
I get this error:
raise ValueError('context must include a "request" key')
ValueError: context must include a "request" key
Does anybody have an idea?
Solution 1:
I found a very easy solution without using url_for()
In case someone coming from flask world has a similar problem here my solution: I created a simple HTML button in my jinja2 template:
<button onclick="myFunction()">pass data to route</button>
and I created a very simple javascript function for passing data to route:
<script>
function myFunction() {
window.location.href = "/updates/data/{{data.uustr}}?interval=2";
}
</script>
that's it.