微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在html循环中从python调用函数?

如何解决如何在html循环中从python调用函数?

我是Web编码的新手...我自己找不到一个好的解决方案。我需要在按钮中添加一个函数,然后在“ application.py”中编写该函数。我无法创建新的html,并且如果可能的话,我不希望在html中编写脚本。该函数应该使用当前的“ i.stock”,因为它位于for循环中。谢谢您的任何帮助。

我的HTML代码

{% 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 %}

下面的我的python [重要部分,def索引用于表]。 i.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)

解决方法

您无法使用HTML访问Python函数。相反,您将AJAX请求发送到服务器。为此,您需要修改购买功能:

import json
from flask import request

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

现在,您可以创建实际的JavaScript-buy-函数,该函数将调用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); 
}

现在剩下要做的就是将所有必要的信息(i)传递给JS-buy函数。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。