Create a Python script that periodically fetches weather data from an API (e.g., OpenWeatherMap) and stores it in an InfluxDB time-series database. The script should accept command line arguments for the API key, location, polling interval, and InfluxDB connection details (host, port, database).
PLAINFORMAT
import argparse
import time

import requests
from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS

# Parse command line arguments
parser = argparse.ArgumentParser(description="Fetch weather data and store it in InfluxDB")
parser.add_argument("api_key", help="OpenWeatherMap API key")
parser.add_argument("location", help="Location for which to fetch weather data (e.g., 'London,uk')")
parser.add_argument("interval", type=int, help="Polling interval in seconds")
parser.add_argument("host", help="InfluxDB host")
parser.add_argument("port", type=int, help="InfluxDB port")
parser.add_argument("database", help="InfluxDB database")

args = parser.parse_args()

# Initialize InfluxDB client
client = InfluxDBClient(url=f"http://{args.host}:{args.port}", token="", org="")
client.switch_database(args.database)

# Function to fetch weather data and write it to InfluxDB
def fetch_and_write_weather_data():
    # Fetch weather data from OpenWeatherMap API
    response = requests.get(
        f"https://api.openweathermap.org/data/2.5/weather?q={args.location}&appid={args.api_key}"
    )
    data = response.json()

    # Extract relevant information
    temperature = data["main"]["temp"]
    humidity = data["main"]["humidity"]
    pressure = data["main"]["pressure"]

    # Create a point with the fetched data
    point = (
        Point("weather")
        .tag("location", args.location)
        .field("temperature", temperature)
        .field("humidity", humidity)
        .field("pressure", pressure)
    )

    # Write the point to InfluxDB
    write_api = client.write_api(write_options=SYNCHRONOUS)
    write_api.write(bucket=args.database, record=point)

# Periodically fetch weather data and store it in InfluxDB
while True:
    try:
        fetch_and_write_weather_data()
        print(f"Fetched weather data for {args.location} and wrote it to InfluxDB")
    except Exception as e:
        print(f"Error fetching or writing weather data: {e}")

    time.sleep(args.interval)