首页 > 解决方案 > 如何使用 API 从每个国家/地区分别从烧瓶中获取数据

问题描述

这是迄今为止的项目:http: //oussama1997.pythonanywhere.com/

这是 Flask-Python 代码:

    from flask import Flask, render_template, request, url_for, session
import requests

app = Flask(__name__)


country = 'Morocco'

@app.route("/", methods=['GET', 'POST'])
@app.route("/covid", methods=['GET', 'POST'])
def home():
    if request.method == 'POST':
        global country
        new_country = request.form.get('country')
        country = new_country


    url = "https://coronavirus-19-api.herokuapp.com/countries/{}"

    
    r = requests.get(url.format(country)).json()

    covid = {
                'country': country.upper(),
                'confirmed': r['cases'],
                'recovered': r['recovered'],
                'critical': r['critical'],
                'deaths': r['deaths'],
                'todayCases': r['todayCases'],
                'todayDeaths': r['todayDeaths'],
                'active': r['active'],
                'totalTests': r['totalTests'],
            }
    
    print(covid)

    return render_template("index.html", covid=covid)


@app.route("/protect")
def protect():
    return render_template("protect.html")

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

现在在 html 中,我想制作新闻代码,但我不知道如何分别从每个国家/地区获取信息,例如:

美国:5498464 | 加拿大:5465465 | 西班牙:5465654 | 德国:8765165...

谢谢你们。

标签: pythonflaskpython-requests

解决方案


好吧,目前您正在向 api 询问有关给定国家/地区的数据。这个 api 提供了一种方法来提取所有国家的数据,这是一个 GET 请求:

https://coronavirus-19-api.herokuapp.com/countries

使用它,您可以迭代响应以构建所需的输出,例如:

r = requests.get('https://coronavirus-19-api.herokuapp.com/countries').json()
for country_data in r
    print(country_data.country, country_data.cases)

推荐阅读