mongodb数据可视化
Using Python to connect to Taiwan Government PM2.5 open data API, and schedule to update data in real time to MongoDB — Part 2
使用Python连接到台湾政府PM2.5开放数据API,并计划将数据实时更新到MongoDB —第2部分
目标 (Goal)
This time I’m using the same PM2.5 open data API (used in Part 1) to showcase how to refresh real time data into mongoDB for every 2 min (because it’s the time for the government’s portal to refresh its API). The strength of mongoDB is it’s simple to use, especially with JSON document format data. This makes connecting to open data much easier. Also we can directly show real time data changes from our database using its Charts & Dashboard features.
这次,我使用相同的PM2.5开放数据API(在第1部分中使用过)来展示如何每2分钟将实时数据刷新到mongoDB中(因为这是政府门户网站刷新其API的时间)。 mongoDB的优势在于它易于使用,尤其是使用JSON文档格式数据时。 这使得连接打开的数据变得更加容易。 我们还可以使用其“图表和仪表板”功能直接从数据库中显示实时数据更改。
How convenient!
多么方便!
The below demo uses Taipei City (the capital city of Taiwan) as example:
下面的演示以台北市(台湾省会城市)为例:
Skills covered:
涵盖技能:
- Connect to API with required parameters to filter out all sensors data in Taipei City 连接到具有所需参数的API,以过滤掉台北市中的所有传感器数据
- Insert the first batch of data into mongoDB 将第一批数据插入mongoDB
- Set a schedule to extract new batch of PM2.5 data from API into mongoDB 设置时间表以从API将新的PM2.5数据批次提取到mongoDB中
- Create charts into dashboard 将图表创建到仪表板
So, let’s get started.
因此,让我们开始吧。
处理 (Process)
Import all required libraries:
导入所有必需的库:
# connect to mongoDB cloud cluster
import pymongo
from pymongo import MongoClient
# convert timezone
import pytz, dateutil.parser
# connect to government open data API
import requests
Connect to API with required parameters to filter out all sensors data in Taipei City. Raw data looks like below (total count of sensors is 100):
使用必需的参数连接到API,以过滤掉台北市中的所有传感器数据。 原始数据如下所示(传感器总数为100):
All data was stored in “first_batch” variable:
所有数据都