Calling Python Script Within Services

Hello community fellows,
I’m building an app that relies on a python script to call an external api and return values. The app will then uses these values for visualization purpose.
Python script looks like the following:

import FundamentalAnalysis as fa

api_key = "my-api-key"

class Checklist:
    def __init__(self, stock_ticker="AAPL"):
        self.time_now = datetime.datetime.now().strftime("%Y-%m-%d")
        self.ticker = stock_ticker
        self.income_statement = fa.income_statement(
            stock_ticker, api_key, period="annual"
        )
        self.cash_f_statement = fa.cash_flow_statement(
            stock_ticker, api_key, period="annual"
        )
        self.balance_s_statement = fa.balance_sheet_statement(
            stock_ticker, api_key, period="annual"
        )
        self.key_ratios = fa.financial_ratios(stock_ticker, api_key)
        self.key_metrics = fa.key_metrics(stock_ticker, api_key)
        self.dividend = fa.stock_dividend(
            stock_ticker, api_key, begin="1000-01-01", end=self.time_now
        )


    def price_to_earning(self, years=10):
        """
        P/E ratio over the years
        """
        return self.key_ratios.loc["priceEarningsRatio"].values[0:years]

Is there a way that I can integrate this python script as part of the services? What’re the recommended approach to integrate a python script as part of the api?
Some examples would be very helpful.
Thank you.

Maybe you can use spawn or something like that within a redwood service?
https://medium.com/swlh/run-python-script-from-node-js-and-send-data-to-browser-15677fcf199f

If the script is simple enough maybe it’s worth rewriting in JS? Could even automate that little bit: Python to javascript converter. I imagine that’s not going to be ideal for most situations though.

For running python in the front end there’s apparently now (https://pyscript.net/) but I wouldn’t recommend that. I think it’s still too early to integrate into production code.

As a python dev who just started using redwoodjs, I would love to know what you end up landing on as best practice!

Thanks @afrias I’ll give it a shot and let you know how it goes.
In the meantime, let me know if you find anything :slight_smile:

Aside from the “why do you need to do this” question, you can do it without making RPCs to a python server with FFI:

Quick google found:

I ended up writing the function in JS and used it as service on the api side since it was more intuitive.

2 Likes