Reputation: 71
How can I use custom filter Jinja2 template in FastApi?
I could find adding custom filter in Jinja2 but not specified in FastApi ,
and other answer from stackoverflow and tried that answer but I got "app doesn't have template_filter property" error.
If there is workaround for changing time format in template , that would be helpful, too.
import alpaca_trade_api as tradeapi
from polygon import RESTClient
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import sqlite3
import config
import helpers
# getting ready alpaca api
api = tradeapi.REST(config.ALPACA_API_KEY_ID, config.ALPACA_API_SECRET, base_url=config.ALPACA_API_URL)
# getting ready web app
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.get("/stock/120days_bars/{symbol}/")
def home(request: Request, symbol):
# RESTClient can be used as a context manager to facilitate closing the underlying http session
# https://requests.readthedocs.io/en/master/user/advanced/#session-objects
with RESTClient(config.POLIGON_API_KEY_ID) as client:
from_ = helpers.get_Y_m_d_str_days_before(120)
to = helpers.get_now_Y_m_d_str()
# ref) https://polygon.io/docs/get_v2_aggs_ticker__stocksTicker__range__multiplier___timespan___from___to__anchor
resp = client.stocks_equities_aggregates(symbol, 1, "day", from_, to, unadjusted=False, sort='desc')
print(f"Minute aggregates for {resp.ticker} between {from_} and {to}.")
context = {"symbol":symbol}
bars = []
if resp.queryCount > 0 :
# there is query result
bars = resp.results
context["bars"] =bars
return templates.TemplateResponse("120days_bars.html", {"request": request, "context":context})
def ts_to_datetime(ts) -> str:
return datetime.datetime.fromtimestamp(ts / 1000.0).strftime('%Y-%m-%d %H:%M')
<html>
<head>
<title>Stocks</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', path='/semantic.min.css') }}">
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<script src="{{ url_for('static', path='/semantic.min.js') }}"></script>
</head>
<body>
<div class="ui container">
<table class="ui inverted teal table">
<thead>
<tr>
<th>Time</th>
<th>Volume</th>
<th>VWAP</th>
<th>Open</th>
<th>Close</th>
<th>High</th>
<th>Low</th>
<th>Name</th>
<th>Timestamp</th>
<th>Num transaction</th>
</tr>
</thead>
<tbody>
{% for bar in context.bars %}
<tr>
<td>{{bar.t | ts_to_date_str}}</td> <!-- i want to use custom filter here to change time format -->
<td>{{bar.v}}</td>
<td>{{bar.vw}}</td>
<td>{{bar.o}}</td>
<td>{{bar.c}}</td>
<td>{{bar.h}}</td>
<td>{{bar.l}}</td>
<td>{{bar.t}}</td>
<td>{{bar.n}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>
Upvotes: 7
Views: 3767
Reputation: 73
Try to update env in template object
templates = Jinja2Templates(
directory=os.path.join(
os.path.abspath("."),
"app/constructor/applications/views",
)
)
def upperstring(input):
"""Custom filter"""
return input.upper()
templates.env.filters["upperstring"] = upperstring
Upvotes: 6