简体   繁体   English

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

[英]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".我需要在我的按钮中添加一个函数并在“application.py”中编写该函数。 I can't create a new html and I would prefer not to write a script in the html, if possible.我无法创建新的 html,如果可能的话,我不想在 html 中编写脚本。 The function should use the "i.stock" of the moment since it is inside a for loop.该函数应使用当前的“i.stock”,因为它位于 for 循环内。 Any help is appreciated, thanks.任何帮助表示赞赏,谢谢。

My html code:我的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 %}

My python below [the part that matters, the def index is for the table].下面我的python [重要的部分,def 索引用于表]。 The i.stock here does not work (obviously you may say) any suggestions on how to fix that?这里的 i.stock 不起作用(显然你可能会说)关于如何解决这个问题的任何建议?

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.您无法在 HTML 中访问 Python 函数。 Instead, you send an AJAX request to the server.相反,您向服务器发送 AJAX 请求。 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:现在您可以创建实际的 JavaScript- buy function 来调用 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.现在你已经离开唯一能做的,是通过所有必要的信息( i )给JS- buy -功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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