Home > Mobile >  Is there an easy way to pass to Python dataclasses into a flask application?
Is there an easy way to pass to Python dataclasses into a flask application?

Time:01-06

I have a Python dataclass that stores things like the stock name and technical analysis information that I calculate in the script. However, after that process finishes, I want to send the objects to an HTML table for easy viewing and color coordination. I have thought about converting it to dictionaries and then sending it to the flask page that way, but that would be one line of code for each obj I need to convert. On top of that, I would need to pass each dictionary into the flask web app which would be tedious.

Wondering if anyone knows of any better ways to reference a Python dataclass in a flask/HTML page without having to redo the project and use a massive Python dictionary. Below is an example of the data class I am using. I would then make a separate obj for each stock I want, then ultimately hoping to pass the obj into an HTML table using flask/jinja

    @dataclass
class stockData:
    #Class to load in stock data and TA values
    ticker:             str
    lastPrice:          float = 0
    moneyFlowIndex:     float = 0
    twentyPeriodCMF:    float = 0
    VWAPUpper:          float = 0
    VWAP:               float = 0
    VWAPLower:          float = 0
    channelUpper:       float = 0
    channel:            float = 0
    channelLower:       float = 0

CodePudding user response:

If you create a list of your objects, you can send the list to a flask template and iterate over the elements in the list there. e.g.:

{% for stock in stockdatas %}
                    <div> {{stock.ticker}}{stock.lastprice}}...</div>
{% endfor %}

and render it e.g. where 'stockdatas' is a list of 'stockdata' objects:

rendered_html = render_template("stocks.html",stock=stockdatas)

CodePudding user response:

It might be possible to send it to a database using SQLite, then connecting to a .db file in python, then sending the data to the database, which is handy, as SQL uses tables to store data, then accessing the database in javascript.

  •  Tags:  
  • Related