gpt4 book ai didi

python - 如何将 json 数据从 Python .py 文件传递​​到我的 html 文件?

转载 作者:行者123 更新时间:2023-12-01 08:34:31 27 4
gpt4 key购买 nike

我目前正在尝试将此免费使用的第 3 方 API 集成到我的网站中。我正在使用Python,它使用flask,所以我将使用渲染模板,那么我如何通过我的模板传递这些数据?

下面是我的 .py 类中的方法,它也安装了打包的请求。注意:我只是为了安全措施而使用了无效的 API key 。

@app.route('/Api', methods=['POST'])
def index():

# BBC news api
main_url = " https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=123"

# fetching data in json format
open_bbc_page = requests.get(main_url).json()

# getting all articles in a string article
article = open_bbc_page["articles"]

# empty list which will
# contain all trending news
results = []

for ar in article:
results.append(ar["title"])

for i in range(len(results)):

# printing all trending news
print(i + 1, results[i])

return render_template('home_page.html')

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

另外我如何在我的 html 文件中显示它?

最佳答案

render_template 方法在第一个参数之后采用 **context 参数,这些参数是在模板上下文中可用的变量。例如,

return render_template('home_page.html', results=results)

您可以根据需要解析从请求中收到的响应。

如果您要返回列表,则可以使用以下内容迭代模板中的列表:

{% for result in results %}
<p>{{result}}</p>
{% endfor %}

关于python - 如何将 json 数据从 Python .py 文件传递​​到我的 html 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53789125/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com