【问题标题】:Error while trying to display data using sqlite3 and flask尝试使用 sqlite3 和烧瓶显示数据时出错
【发布时间】:2021-06-07 19:58:12
【问题描述】:

我正在尝试显示股票组合。任务是访问数据库,然后查找股票的当前价格,显示它、股票的总价值、10000 的剩余现金和总计,这应该根据当前的股票价格而变化。 我尝试了各种方法来访问和显示数据,但我经常遇到错误,我需要帮助,拜托。我还尝试创建一个 for 循环并将数据附加到列表中,但同样没有成功。 错误是: 文件“/home/ubuntu/finance/application.py”,第 58 行,在索引中 current_price=lookup(row["symbol"]["price"]) TypeError:“NoneType”对象不可下标 我的代码如下:

   @app.route("/")
        @login_required
        def index():
        
            """Show portfolio of stocks"""
            #Access the stocks of the current user from DB
            rows=db.execute("SELECT symbol, name, sum(shares) as shares FROM stocks WHERE user_id=:user_id ORDER BY symbol", user_id=session["user_id"])
            #Check the current price of each stock using the helper function lookup and calculate the total cost of each stock( * number of shares by price)
            #add that info to rows and render it on the index page
            sum_total_cost=0
            for row in rows:
                #symbol=row["symbol"]
                #current_price=lookup(symbol["price"])
                current_price=lookup(row["symbol"]["price"])
                total_cost=current_price*(row["shares"])
                row["current_price"]=usd(current_price)
                row["total_cost"]=usd(total_cost)
                sum_total_cost+=total_cost
            #Check the current cash of the user
            user_id=session["user_id"]
            user = db.execute("SELECT cash FROM users WHERE id=:user_id", user_id=user_id)
            cash=user[0]["cash"]
            grand_total = cash+sum_total_cost
        
            return render_template("index.html", rows=rows, cash = cash, grand_total=grand_total)

HTML

{% 扩展“layout.html”%}

{% block title %}
    Index
{% endblock %}

{% block main %}
    <h2>Portfolio</h2>
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Symbol</th>
                            <th>Name</th>
                            <th>Shares</th>
                            <th>Price</th>
                            <th>Total Cost</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- TODO: Loop through the database to display all transactions and the balance -->
                        {% for row in rows %}
                           <tr>
                               <td>{{row.symbol}}
                               <td>{{row.name}}</td>
                               <td>{{row.shares}}</td>
                               <td>{{row.current_price}}</td>
                               <td>{{row.total_cost}}</td>
                         {% endfor %}

                           </tr>


                           <tr>
                               <th>Cash</th>
                               <td></td>
                               <td></td>
                               <td></td>
                               <td>{{cash}}</td>

                           </tr>
                           <tr>
                               <th>Grand Total</th>
                               <td></td>
                               <td></td>
                               <td></td>
                               <td>{{grand_total}}</td>

                           </tr>

                    </tbody>

                </table>
            </div>

        </div>
{% endblock %}

查找函数

def lookup(symbol):
    """Look up quote for symbol."""

    # Contact API
    try:
        api_key = os.environ.get("API_KEY")
        url = f"https://cloud-sse.iexapis.com/stable/stock/{urllib.parse.quote_plus(symbol)}/quote?token={api_key}"
        response = requests.get(url)
        response.raise_for_status()
    except requests.RequestException:
        return None

    # Parse response
    try:
        quote = response.json()
        return {
            "name": quote["companyName"],
            "price": float(quote["latestPrice"]),
            "symbol": quote["symbol"]
        }
    except (KeyError, TypeError, ValueError):
        return None    

【问题讨论】:

  • 首先,请准确说明您遇到了什么样的“错误”。这是 Python/Flask 错误还是结果不是您想要的?
  • 对不起,刚刚编辑了原帖。当前的错误是python,虽然之前尝试了不同的方法,但我能够显示数据,但总价值永远不正确。
  • 不应该这current_price=lookup(row["symbol"]["price"]) 读`current_price = lookup(row["symbol"])["price"] (close paren move) 因为lookup返回一个dict并且你想要price的值?

标签: python-3.x sqlite flask


【解决方案1】:

错误信息不言自明,应该是导致问题的那一行:

current_price=lookup(row["symbol"]["price"])

由于您正在从表中读取数据,因此您很可能会使用row["symbol"],可能会通过某些操作进行转换。您正在处理该字段,就好像它是一个字典一样。我不知道你的查找是做什么的。我猜它只需要一个参数,所以它可能只是这样的:current_price=lookup(row["symbol"])

如果您无法解决问题,也许可以发布查找功能的代码。

PS:也许整个计算都可以在SQL中完成,可能是JOINing两个表什么的。

【讨论】:

  • 谢谢。我测试了 current_price=lookup(row["symbol"]) 但它也没有工作。也对此进行了测试:#symbol=row["symbol"] #current_price=lookup(symbol["price"]) 但仅使用 2 行是相同的。由于太长,我正在原始帖子中查找查找。
  • 我解决了它:))) 对数据库进行了小幅修正。谢谢你的提示,匿名。这种访问数据的方式对我来说太复杂了,我很高兴找到了解决方案,我能够完全理解。
猜你喜欢
  • 2017-02-10
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 1970-01-01
  • 2022-08-18
  • 2020-02-17
  • 2017-05-02
  • 1970-01-01
相关资源
最近更新 更多