Try   HackMD

使用API抓取新冠肺炎(COVID-19)的最新狀態

tags: python covid-19 colab flask

RapidAPI

介紹

https://rapidapi.com/login

RapidAPI是一個API的市集,就像Apple的App Store和Google PlayStore上面有各式各樣的App可以下載一樣,只是這裡可以讓你找到的不是APP,而是API,讓你不需要再發明輪子,直接使用全世界各國的開發者開發好的功能,讓你可以快速建立你的應用。

申請Application Key

API並非開放使用,每次的呼叫都遠端都會確認有經過授權,因為API的運作需要源源不斷的雲端服務,因為為了阻擋沒有經過同意的呼叫,每次呼叫API時都必須帶入這個Application Key。

申請或修改Application Key可以到「MyApps」選擇左邊已經建立App名稱,然後到「Security」頁面下設定。

以Python開發

需要的模組

模組名稱 說明 安裝
Flask 開發網站用 pip3 install flask
requests HTTP要求模組,用來直接透過網路讀取網頁資料 pip3 install requests
Json 操作CSV檔案格式模組 不需安裝

取的COVID-19的最新資料

本範例使用的API:https://rapidapi.com/KishCom/api/covid-19-coronavirus-statistics

X-RapidAPI-Host(必要欄位)
covid-19-coronavirus-statistics.p.rapidapi.com
X-RapidAPI-Key(必要欄位)
4e99a51760msh101eb7f3fbb43a8p19880djsm1178154416e9

這只是一個範例,並非真實的Application Key,請填入跟RapidAPI申請的Application Key,每個人會不同。

完整整程式碼

# -*- coding: utf-8 -*-
from flask import Flask

import requests
import json
import sys

url = "https://covid-19-coronavirus-statistics.p.rapidapi.com/v1/total"

querystring = {"country":"Global"}

headers = {
    'x-rapidapi-host': "covid-19-coronavirus-statistics.p.rapidapi.com",
    'x-rapidapi-key': "3e99a92190msh101eb7e3faa43a8p13070djsn1178154416e5"
    }
app = Flask(__name__)

@app.route('/')
def update_covid_19():
    response = requests.request("GET", url, headers=headers, params=querystring)
    # print(response.text)

    data = json.loads(response.text) # 將JSON格式轉成Python資料型態

    if data['statusCode'] != 200:
        print('無法取得資料.')
        sys.exit() 
        
    # 最後要輸出到網頁的內容
    result = f'''
    <!DOCTYPE html>
    <html>
       <head>
          <meta charset"utf-8"/>
          <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.0.0/animate.min.css"  />

       </head>
       <body style="margin: 5px; text-align: center;" >
          <h1 class="animate__animated animate__bounce">全球武漢肺炎狀況最新資訊</h1>
          <img class="animate__animated animate__slideInLeft" src="https://www.cdc.gov.tw/Uploads/3d07c50d-5769-4cac-9b26-95a50589160e.png" width="600px"/><br/><br/>
          <p>更新時間:{data['data']['lastChecked'][:-6].replace('T', ' ')}<br/>
             確診人數:{str(data['data']['confirmed'])}<br/>
             死亡人數:{str(data['data']['deaths'])}<br/>
             復原人數:{str(data['data']['recovered'])}<br/>
          </p>
          <iframe width="540" height="260" src="https://www.youtube.com/embed/FHSKtyfqGJU" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </body>
    </html>
    '''

    print('全球武漢肺炎狀況更新')
    print('更新時間:', data['data']['lastChecked'][:-6].replace('T', ' '))
    print('確診人數:', data['data']['confirmed'])
    print('死亡人數:', data['data']['deaths'])
    print('復原人數:', data['data']['recovered'])

    print('輸出網頁:', result)

    try:
        # 寫入檔案,可在本地端直接用瀏覽器開啟,如果僅需API,可以不須寫到檔案
        with open('index.html', 'w') as src:
            src.write(result)
    except:
        print('Cannot write index.html')

	# HTTP Response
    return result

if __name__ == '__main__':
    # 這裡只會在本地端執行生效
    app.run(host='127.0.0.1', port=80, debug=True)

注意:

x-rapidapi-key欄位內需要填入RapidAAPI配發的Application Key。

執行結果

  1. 程式執行成功會在目前路徑下產生index.html靜態網頁檔案,可以直接用瀏覽器打開觀看結果。
  2. 啟動一個HTTP伺服器,在瀏覽器輸入:127.0.0.1就可以打開該網頁。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

在Google Colab上執行

前言

因為Google Colab是雲端環境,所有的程式碼都是在雲端執行,因此我們無法直接在雲端啟動一個Flask HTTP伺服器來接受外面的連線;所以需要透過其他方式處理。

ngrok這個服務可以幫忙來把連線的要求用轉接的方式幫忙轉到Colab裡面去,而且有提供Pyhon模組支援,且使用簡易,只需要加少少的程式碼就可以做到使用Colab來啟動HTTP伺服器。

使用步驟如下:

  1. 安裝flask-ngrok模組,Colab並沒有支援ngrok,所以要額外安裝。

    ​​​!pip install flask-ngrok
    

    補充

    在瀏覽器關閉以前,只需要安裝一次即可,因此可以額外開一個新的Cell來執行這個安裝指令。

  2. 引入flask-ngrok模組

    ​​​from flask_ngrok import run_with_ngrok
    

    補充

    可以在from flask import Flask上面來進行引入。

  3. 加上將Flask物件轉拋給ngrok套件的程式碼:

    ​​​run_with_ngrok(app)
    

    補充

    請將該行加在app = Flask(__name__)下面即可。

  4. 將最後app.run()內的參數全部移除:

    ​​​app.run()
    

執行結果

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

說明

紅框圈起來就是ngrok服務幫忙轉拋的網址,點擊該連結就可以打開剛剛開發的網頁;只是每次重新執行程式都會變,舊的會失效,請使用每次執行後新的網址來測試網頁。