簡體   English   中英

如何在 html 循環內從 python 調用函數?

[英]How to call a function from python inside a html loop?

我是網絡編碼的新手……我自己找不到好的解決方案。 我需要在我的按鈕中添加一個函數並在“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 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); 
}

現在你已經離開唯一能做的,是通過所有必要的信息( i )給JS- buy -功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM