You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flask项目中展示API获取的植物详情?

解决方案

1. 确保 plant.py 能返回完整植物数据

首先检查并调整 plant.py,让它返回包含所有所需字段的完整响应数据,而不是仅提取名称:

# plant.py
import requests

def get_plant_details(plant_name):
    # 替换为你的RapidAPI接口地址、密钥和主机名
    url = "https://your-plant-api.p.rapidapi.com/search"
    headers = {
        "X-RapidAPI-Key": "your-api-key-here",
        "X-RapidAPI-Host": "your-api-host-here"
    }
    # 根据目标API的参数要求调整键名(比如有的API用"query"而非"name")
    params = {"name": plant_name}

    response = requests.get(url, headers=headers, params=params)
    if response.status_code == 200:
        # 返回完整的API响应JSON,后续在模板中按需提取字段
        return response.json()
    # 请求失败时返回None,用于后续错误提示
    return None

2. 修改 app.py 传递完整植物数据到模板

在路由中调用 get_plant_details 函数,把完整的植物数据传递给 result.html:

# app.py
from flask import Flask, render_template, request
from plant import get_plant_details

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        plant_name = request.form.get('plant_name').strip()
        # 获取完整的植物详情数据
        plant_data = get_plant_details(plant_name)
        # 将植物名称和完整数据一起传入模板
        return render_template('result.html', plant_name=plant_name, plant_data=plant_data)
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

3. 调整 result.html 渲染所有需要的字段

在模板中通过 Jinja2 语法提取并展示 plant_data 中的拉丁名、气候、温度上限等字段,同时处理数据为空的情况:

<!-- templates/result.html -->
<!DOCTYPE html>
<html>
<head>
    <title>植物查询结果</title>
</head>
<body>
    <h1>{{ plant_name }} 的详细信息</h1>
    {% if plant_data %}
        <div class="plant-info">
            <!-- 注意:以下字段名需和RapidAPI返回的JSON键名完全一致 -->
            <p><strong>拉丁名:</strong> {{ plant_data.latin_name }}</p>
            <p><strong>适宜气候:</strong> {{ plant_data.climate }}</p>
            <p><strong>温度上限:</strong> {{ plant_data.max_temperature }} ℃</p>
            <!-- 可根据API返回的其他字段继续添加 -->
        </div>
    {% else %}
        <p>未找到该植物的信息,请检查名称是否正确,或稍后重试。</p>
    {% endif %}
    <a href="/">返回重新查询</a>
</body>
</html>

关键注意事项

  • 务必核对 RapidAPI 返回的 JSON 结构,确保模板中使用的字段名(比如 latin_name、climate)和实际响应的键名完全匹配(部分API可能使用驼峰命名如 latinName)。
  • 如果 API 返回的是数组形式的结果(比如多个匹配项),需要在 plant.py 中先提取第一个有效结果,再传递给模板。

内容的提问来源于stack exchange,提问作者Natique Ibrar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 18:22:39