简体   繁体   中英

How to call a function from python inside a html loop?

I am new to web coding... I was not able to find a good solution on my own. I need to add a function in my buttons and write the function in "application.py". I can't create a new html and I would prefer not to write a script in the html, if possible. The function should use the "i.stock" of the moment since it is inside a for loop. Any help is appreciated, thanks.

My html code:

{% extends "layout.html" %}

{% block head %}
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet">
{% endblock %}

{% block title %}
    Your Portfolio
{% endblock %}

{% block main %}
    <h2> This is your current Portfolio:</h2>
    <table class="table">
      <thead class="thead-light">
        <tr>
          <th scope="col">Symbol</th>
          <th scope="col">Name</th>
          <th scope="col">Shares</th>
          <th scope="col">Current Price</th>
          <th scope="col">Total</th>
          <th scope="col">Buy</th>
          <th scope="col">Sell</th>
        </tr>
      </thead>
      <tbody>
      {% for i in portfolio %}
        <tr>
          <th scope="row">{{ i.stock_symbol }}</th>
          <td>{{ i.stock_name }}</td>
          <td>{{ i.stock_shares }}</td>
          <td>{{ i.stock_price }}</td>
          <td>{{ i.total_amount }}</td>
          <td><a type="button" class="btn btn-success" onClick="buy()">+</a></td>
          <td><a type="button" class="btn btn-danger">-</a></td>
        </tr>
      {% endfor %}
      </tbody>
    </table>

    <h4> Your currently have {{cash}} available in cash </h4>
    <h4> Your Total (stocks + cash) is {{total}}</h4>

{% endblock %}

My python below [the part that matters, the def index is for the table]. The i.stock here does not work (obviously you may say) any suggestions on how to fix that?

Maybe I should create another @? I will need to refresh his portfolio once he buys another stock.

@app.route("/")
@login_required
def index():
    """Show portfolio of stocks"""

    ...

#Function to buy stocks directly from index
def buy():

    cost = float(i.stock["price"])

    #Looks in the datababse for the amount of cash the user still has
    query = db.execute("SELECT cash FROM users WHERE id = :id", \
                      id=session["user_id"])

    cash = query[0]["cash"]

    #See if user has enough money and handle when user does not
    if cost > cash:
        return apology("You don't have enough money")

    #Append information to the history table
    db.execute("INSERT INTO history (user_id, stock_symbol, stock_price, stock_amount, total_amount) \
                VALUES (:user_id, :stock_symbol, :stock_price, :stock_amount, :total_amount)", \
                user_id = session["user_id"], stock_symbol = i.stock["symbol"], stock_price = usd(i.stock["price"]), stock_amount = 1, total_amount = cost)

    #Calculates new cash amount and update database
    net_cash = int(cash - cost)
    db.execute("UPDATE users SET cash = :new_cash WHERE id = :id", \
                id = session["user_id"], new_cash = net_cash)

You can't access Python functions in HTML. Instead, you send an AJAX request to the server. To do this, you need to modificate your buy-function:

import json
from flask import request

@app.route('/buy', methods=['POST'])
def buy():
    i = json.loads(request.args.get('i'))

Now you can create the actual JavaScript- buy -function that will call the Python- buy -function:

function buy() {
    var i = {}; // You need to get the details
    var i_json = JSON.stringify(i);
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "/buy", true);
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          console.log("Done.");
        }
    };
    xhttp.send(i_json); 
}

Now the only thing you have left to do, is passing all the necessary information ( i ) to the JS- buy -function.

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