简体   繁体   中英

Running function within template file (Python/Bottle)

I'm using bottle to create a simple retirement calculator of sorts, but I'm having trouble with the template file's handling of python code. For example, I have this code

<%
import statistics, numpy

medianStockReturn = []

def stockReturn():
    global medianStockReturn
    yearStockReturn = numpy.random.normal(11.4, 19.7, 1000)
    yearMedianStockReturn = statistics.median(yearStockReturn)
    yearMedianStockReturn = yearMedianStockReturn / 100 + 1
    medianStockReturn.append(yearMedianStockReturn)
stockReturn()
end
%>

<!DOCTYPE html>
<html lang = "en-us">
    <head>
        <title>Retirement Calculator</title>
        <meta charset = "utf-8">
        <link rel="stylesheet" type="text/css" href="../static/retirementStyle.css">
   </head>
   <body>
       <h2> this is a test; your stock return is {{medianStockReturn}}</h2>
   </body>
</html>

However, this code results in an output of: "this is a test; your stock return is []"

As written, the function should append medianStockReturn with a generated value, but it does not, and I am not exactly sure why.

You need to move the end to after the end of function definition above stockReturn()

<%
import statistics, numpy

medianStockReturn = []

def stockReturn():
    global medianStockReturn
    yearStockReturn = numpy.random.normal(11.4, 19.7, 1000)
    yearMedianStockReturn = statistics.median(yearStockReturn)
    yearMedianStockReturn = yearMedianStockReturn / 100 + 1
    medianStockReturn.append(yearMedianStockReturn)
end
stockReturn()
%>

<!DOCTYPE html>
<html lang = "en-us">
    <head>
        <title>Retirement Calculator</title>
        <meta charset = "utf-8">
        <link rel="stylesheet" type="text/css" href="../static/retirementStyle.css">
   </head>
   <body>
       <h2> this is a test; your stock return is {{medianStockReturn}}</h2>
   </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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