繁体   English   中英

如何添加自定义过滤器 FastApi Jinja2 模板?

[英]How can I add custom filter FastApi Jinja2 template?

如何在 FastApi 中使用自定义过滤器 Jinja2 模板?

我可以在 Jinja2 中找到添加自定义过滤器,但未在 FastApi 中指定,

和来自 stackoverflow 的其他答案并尝试了该答案,但我收到“应用程序没有 template_filter 属性”错误。

如果在模板中有更改时间格式的解决方法,那也会有帮助。

主程序


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')

120days_bars.html

<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>

尝试更新模板 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM