[Xiao Mu learns Python] Python implements free weather forecast acquisition (OpenWeatherMap)

1 Introduction

https://openweathermap.org/Weather
forecast is very necessary for our daily life. It helps us prepare and plan based on expectations. Many weather stations are placed around the world to obtain real-time weather element data.

The weather API contains a wealth of weather data, including not only basic data such as real-time temperature, humidity, wind speed, precipitation, etc., but also past historical weather data and future weather forecast data. The top weather API interface will also include weather disaster warnings, air Quality index, astronomical and meteorological data related to sunrise and sunset, tides and moon phases.
Insert image description here
The data includes six elements such as precipitation, wind, atmospheric pressure, cloud cover and temperature. With these, you can analyze trends, know tomorrow's data predictions or predict the weather.

1.1 Introduction to tools

Insert image description here
OpenWeatherMap access current weather data for any location on Earth! We collect and process weather data from diverse sources such as global and local weather models, satellites, radar and an extensive network of weather stations. Data is provided in JSON, XML or HTML format.
Insert image description here

1.2 Fees

OpenWeatherMap. Free and paid services available. It all depends on the type and size of data required. Additionally, it also depends on the number of requests per request.
Insert image description here

1.3 Registration

https://home.openweathermap.org/users/sign_in
Insert image description here

1.4 Apply for key

https://home.openweathermap.org/api_keys
Insert image description here

2. Interface description

For every point on Earth, OpenWeather provides hyperlocal minute-to-minute forecasts, historical data, current status, and weather data from short-term to annual and forecast. All data is available through industry standard APIs.

http://www.openweathermap.org/api
http://www.openweathermap.org/current
http://www.openweathermap.org/forecast
http://www.openweathermap.org/weather-conditions

2.1 One Call 3.0

  • Current weather
  • 1 hour minute forecast
  • 48 hour hourly forecast
  • 8-day daily forecast
  • government weather alerts
  • Weather data for any timestamp from January 1, 1979 up to 4 days ahead of the forecast
  • Daily summary of 40+ years of archived and 1.5-year forecast weather data
https://api.openweathermap.org/data/3.0/onecall?lat={
    
    lat}&lon={
    
    lon}&exclude={
    
    part}&appid={
    
    API key}

2.2 Current Weather and Forecasts collection

  • Current status updated every 10 minutes
  • 4-day forecast with hourly granularity
  • 16-day forecast, giving you data four times a day at night, day, evening and morning
  • 30 day forecast

2.2.1 API call

https://openweathermap.org/current

# city name
https://api.openweathermap.org/data/2.5/weather?q={
    
    city name}&appid={
    
    API key}

# JSON
https://api.openweathermap.org/data/2.5/weather?q=London&appid={
    
    API key}

# XML
https://api.openweathermap.org/data/2.5/weather?q=London&mode=xml&appid={
    
    API key}

# Latitude & Longitude
https://api.openweathermap.org/data/2.5/weather?lat={
    
    lat}&lon={
    
    lon}&appid={
    
    API key}
https://api.openweathermap.org/data/2.5/weather?lat=44.34&lon=10.99&appid={
    
    API key}

2.2.2 API parameters

parameter name Optional describe
q Required The city name, state code and country code are separated by commas. Please refer to ISO 3166 for the state code or country code. You can specify parameters not only in English. In this case, if the location is in our predefined list of over 200,000 locations, the API response should be returned in the same language as the requested location name.
lat Required latitude. If you need a geocoder to automatically convert city names and zip codes into geographic coordinates and vice versa, use our Geocoding API
lon Required longitude. If you need a geocoder to automatically convert city names and zip codes into geographic coordinates and vice versa, use our Geocoding API
appid Required Your unique API key (you can always find it under the "API Keys" tab on your account page)
mode Optional Response format. Possible values ​​are xml and html. If no parameters are used, the default format is JSON.
units Optional unit of measurement. standard, metric, imperial, and provide units. If this parameter is not used, units will be applied by default.
lang Optional You can use this parameter to get the output for your language.

2.3 Historical Weather collection

  • Historical archive from 40+ years ago, with hourly granularity
  • Archive of historical forecasts, including previous forecasts for the next 16 days for any location around the world
  • Historical API, containing weather data for a month or a year, depending on your subscription
  • Statistical Weather API that provides statistics on key weather parameters by selected days or months of the year or for the entire year

We provide hourly historical weather data for any location around the world via the History API. The availability of hourly historical data depends on the type of subscription.

  • History API
https://history.openweathermap.org/data/2.5/history/city?lat={
    
    lat}&lon={
    
    lon}&type=hour&start={
    
    start}&end={
    
    end}&appid={
    
    API key}

https://history.openweathermap.org/data/2.5/history/city?lat={
    
    lat}&lon={
    
    lon}&type=hour&start={
    
    start}&cnt={
    
    cnt}&appid={
    
    API key}

2.4 Weather Maps collection

  • Weather Map 2.0 features 15 weather layers showing historical, current and forecast weather data
  • Global precipitation map based on radar data, satellite imagery and powered by machine learning
  • Landform map as the base layer of OpenWeather map

Forecast, historical and current weather maps. 15 weather map layers. You can get all of this with just one simple URL!

  • Weather Maps 2.0, 3-hour step
http://maps.openweathermap.org/maps/2.0/weather/{
    
    op}/{
    
    z}/{
    
    x}/{
    
    y}?appid={
    
    API key}

2.5 Other weather APIs

  • Hourly air quality data with aerosol characteristics: PM2.5, PM10; carbon CO2; precursors SO2, NO2; ozone O3; AQ index

  • The Geocoding API is a simple tool that simplifies location searches when using geographic names and coordinates

  • Current air pollution data

http://api.openweathermap.org/data/2.5/air_pollution?lat={
    
    lat}&lon={
    
    lon}&appid={
    
    API key}

3. Interface testing

3.1 Example 1: Current Weather + flask

  • test1.py
from flask import Flask, request
import requests
import datetime

app = Flask(__name__)
 
@app.route('/weather', methods=['GET'])
def get_weather():
    # 设置请求参数,包括城市名和 API Key
    params = {
    
    
        "q": "beijing",
        "appid": "your api key",
        "units": "metric"
    }
 
    # 向 OpenWeather API 发送 GET 请求,获取实时天气数据
    response = requests.get('http://api.openweathermap.org/data/2.5/weather', params=params)
    weather_data = response.json()
    print(weather_data)

    # 提取最近几天的天气信息
    weather_list = []
    # 可以通过对获取的实时天气数据进行解析,得到今天、明天和后天的天气数据
    # 这里只演示了提取当前天气的温度和描述信息的代码

    time_str = datetime.datetime.fromtimestamp(weather_data['dt'])

    weather_list.append({
    
    
        "date": time_str,
        "temperature": weather_data['main']['temp'],
        "description": weather_data['weather'][0]['description']
    })
 
    # 返回最近几天的天气信息
    return {
    
    "weather": weather_list}
 
if __name__ == '__main__':
    app.run()

The python script runs as follows:
Insert image description here
The browser access is as follows:

http://127.0.0.1:5000/weather

Insert image description here

3.2 Example 2: Current Weather + node.js

  • Set up the project and initialize the Node.js project by using the command below.
npm init -y

This command accepts all default options from the terminal dialog. It creates a new configuration file in the root directory called package.json.
Insert image description here
Insert image description here

  • Install dependencies
npm i express dotenv body-parser request ejs

Insert image description here
Insert image description here
Add a line of code "start": "node server.js" in the package.json file,
Insert image description here

  • Create a new file: server.js
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const app = express();

require("dotenv").config();

const apiKey = `${
      
      process.env.API_KEY}`;

app.use(express.static("public"));
app.use(bodyParser.urlencoded({
    
     extended: true }));
app.set("view engine", "ejs");

app.get("/", function (req, res) {
    
    
  // It will not fetch and display any data in the index page
  res.render("index", {
    
     weather: null, error: null });
});

app.post('/', function(req, res) {
    
    

    // Get city name passed in the form
    let city = req.body.city;

    // Use that city name to fetch data
    // Use the API_KEY in the '.env' file
    let url = `http://api.openweathermap.org/data/2.5/weather?q=${
      
      city}&units=metric&appid=${
      
      apiKey}`;

	request(url, function(err, response, body) {
    
    

        // On return, check the json data fetched
        if (err) {
    
    
            res.render('index', {
    
     weather: null, error: 'Error, please try again' });
        } else {
    
    
            let weather = JSON.parse(body);
			console.log(weather);

            if (weather.main == undefined) {
    
    
                res.render('index', {
    
     weather: null, error: 'Error, please try again' });
            } else {
    
    
                // we shall use the data got to set up your output
                let place = `${
      
      weather.name}, ${
      
      weather.sys.country}`,
                  /* you shall calculate the current timezone using the data fetched*/
                  weatherTimezone = `${
      
      new Date(
                    weather.dt * 1000 - weather.timezone * 1000
                  )}`;
                let weatherTemp = `${
      
      weather.main.temp}`,
                  weatherPressure = `${
      
      weather.main.pressure}`,
                  /* you will fetch the weather icon and its size using the icon data*/
                  weatherIcon = `http://openweathermap.org/img/wn/${
      
      weather.weather[0].icon}@2x.png`,
                  weatherDescription = `${
      
      weather.weather[0].description}`,
                  humidity = `${
      
      weather.main.humidity}`,
                  clouds = `${
      
      weather.clouds.all}`,
                  visibility = `${
      
      weather.visibility}`,
                  main = `${
      
      weather.weather[0].main}`,
                  weatherFahrenheit;
                weatherFahrenheit = (weatherTemp * 9) / 5 + 32;

                // you shall also round off the value of the degrees fahrenheit calculated into two decimal places
                function roundToTwo(num) {
    
    
                  return +(Math.round(num + "e+2") + "e-2");
                }
                weatherFahrenheit = roundToTwo(weatherFahrenheit);
				res.render("index", {
    
    
                  weather: weather,
                  place: place,
                  temp: weatherTemp,
                  pressure: weatherPressure,
                  icon: weatherIcon,
                  description: weatherDescription,
                  timezone: weatherTimezone,
                  humidity: humidity,
                  fahrenheit: weatherFahrenheit,
                  clouds: clouds,
                  visibility: visibility,
                  main: main,
                  error: null,
                });
            }
        }
    });
});

app.listen(5000, function () {
    
    
  console.log("Weather app listening on port 5000!");
});

  • Create a new file: .env
API_KEY=your api key
  • Create a new file: views\index.ejs
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Weather</title>
    <!-- Required meta tags -->
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />

    <!-- Bootstrap CSS -->
    <!-- Use some bootstrap CSS and google fonts to quicken the process -->
    <!-- you shall also add a favicon -->
    <link
      rel="shortcut icon"
      href="https://img.icons8.com/office/16/000000/sunset--v2.png"
      type="image/x-icon"
    />
    <link rel="stylesheet" type="text/css" href="/css/style.css" />
    <link
      href="https://fonts.googleapis.com/css?family=Open+Sans:300"
      rel="stylesheet"
      type="text/css"
    />
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
      crossorigin="anonymous"
    />
  </head>

  <body>
    <div class="container">

  <!-- This shall hold the input fields and the output data -->
  <fieldset>
    <!-- This form shall be used to fetch your city name -->
    <form action="/" method="post">
      <input name="city" type="text" class="ghost-input" placeholder="Enter a City" required>
      <input type="submit" class="ghost-button" value="Get Weather">
    </form>

    <!-- Upon fetching of data you will display it -->
    <%if( weather !== null){
    
     %>
    <div class="grid">
      <p>
        <%= place %>
      </p>
      <p class="text-muted small">
        <%= timezone %>
      </p>
    </div>

    <!-- You can find other data fetched by the app on the console in JSON form and display it as you please -->
    <div class="card-deck">
      <div class="card card-accent-dark mb-3" style="max-width: 18rem;">
        <div class="card-header">Summary</div>
        <div class="card-body text-dark">Bootstrap CSS
          <img src="<%= icon %>" alt="Weather-Icon">
          <h5 class="card-title">Temperature</h5>
          <p class="card-text">
            In Degrees:
            <%= temp %>°C/
            <%= fahrenheit %>°F
          </p>
          <h5 class="card-title">Main</h5>
          <p class="card-text">
            <%= main %>
          </p>
        </div>
      </div>
      <div class="card-deck">
        <div class="card card-acTomorrowcent-dark mb-3" style="max-width: 18rem;">
          <div class="card-header">Description</div>
          <div class="card-body text-dark">
            <h5 class="card-title">Overall Description: </h5>
            <p class="card-text">
              <%= description %>
            </p>
            <h5 class="card-title">Cloud coverage: </h5>
            <p class="card-text">
              <%= clouds %>%
            </p>
            <h5 class="card-title">Visibility: </h5>
            <p class="card-text">
              <%= visibility %> meters
            </p>
          </div>
        </div>
        <div class="card-deck">
          <div class="card card-accent-dark mb-3" style="max-width: 18rem;">
            <div class="card-header">Other info</div>
            <div class="card-body text-dark">
              <h5 class="card-title">Humidity: </h5>
              <p class="card-text">
                <%= humidity %> g.m-3
              </p>
            </div>
            <div class="card-body text-dark">
              <h5 class="card-title">Pressure: </h5>
              <p class="card-text">
                <%= pressure %> N·m−2
              </p>
            </div>
          </div>
        </div>

        <% } %>

        <% if(error !== null){
    
     %>
        <p>
          <%= error %>
        </p>
        <% } %>
  </fieldset>
</div>

    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script
      src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
      integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
      integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
      integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
      crossorigin="anonymous"
    ></script>
  </body>
</html>

  • Create a new file: public\css\style.css
body {
    
    
  width: auto;
  margin: 0 auto;
  font-family: "Open Sans", sans-serif;
}

/* This will format the whole fieldset content*/

.container {
    
    
  width: 80%;
  margin: 0 auto;
}

/* This will format the whole fieldset content*/

fieldset {
    
    
  display: block;
  -webkit-margin-start: 0px;
  -webkit-margin-end: 0px;
  -webkit-padding-before: 0em;
  -webkit-padding-start: 0em;
  -webkit-padding-end: 0em;
  -webkit-padding-after: 0em;
  border: 0px;
  border-image-source: initial;
  border-image-slice: initial;
  border-image-width: initial;
  border-image-outset: initial;
  border-image-repeat: initial;
  min-width: -webkit-min-content;
  padding: 30px;
}

/* Format the input section */

/* Format the input, paragraph, hover effect, focus and button */
.ghost-input,
p {
    
    
  display: block;
  font-weight: 300;
  width: 100%;
  font-size: 25px;
  border: 0px;
  outline: none;
  width: 100%;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  color: #4b545f;
  background: #fff;
  font-family: Open Sans, Verdana;
  padding: 10px 15px;
  margin: 30px 0px;
  -webkit-transition: all 0.1s ease-in-out;
  -moz-transition: all 0.1s ease-in-out;
  -ms-transition: all 0.1s ease-in-out;
  -o-transition: all 0.1s ease-in-out;
  transition: all 0.1s ease-in-out;
}

.ghost-input:focus {
    
    
  border-bottom: 1px solid #ddd;
}

.ghost-button {
    
    
  background-color: transparent;
  border: 2px solid #ddd;
  padding: 10px 30px;
  width: 100%;
  min-width: 350px;
  -webkit-transition: all 0.1s ease-in-out;
  -moz-transition: all 0.1s ease-in-out;
  -ms-transition: all 0.1s ease-in-out;
  -o-transition: all 0.1s ease-in-out;
  transition: all 0.1s ease-in-out;
}

.ghost-button:hover {
    
    
  border: 2px solid #515151;
}

p {
    
    
  color: #e64a19;
}

Run the following command in the terminal as follows:

npm run start
#or 
node server.js

Insert image description here
Browser access is as follows:

http://127.0.0.1:5000/

Insert image description here

3.3 Example 3: Current Weather + tkinter

from tkinter import *
import requests
import json
from datetime import datetime

root =Tk()
root.geometry("400x400")
root.resizable(0,0) 
root.title("天气预报APP - 爱看书的小沐")

city_value = StringVar()

def time_format_for_location(utc_with_tz):
    local_time = datetime.utcfromtimestamp(utc_with_tz)
    return local_time.time()

def showWeather():
    #Enter you api key, copies from the OpenWeatherMap dashboard
    api_key = "your api key"  #sample API

    # Get city name from user from the input field (later in the code)
    city_name=city_value.get()

    # API url
    weather_url = 'http://api.openweathermap.org/data/2.5/weather?q=' + city_name + '&appid='+api_key

    # Get the response from fetched url
    response = requests.get(weather_url)

    # changing response from json to python readable 
    weather_info = response.json()
    print(weather_info)

    if weather_info['cod'] == 200:
        kelvin = 273 # value of kelvin

        temp = int(weather_info['main']['temp'] - kelvin)   #converting default kelvin value to Celcius
        feels_like_temp = int(weather_info['main']['feels_like'] - kelvin)
        pressure = weather_info['main']['pressure']
        humidity = weather_info['main']['humidity']
        wind_speed = weather_info['wind']['speed'] * 3.6
        sunrise = weather_info['sys']['sunrise']
        sunset = weather_info['sys']['sunset']
        timezone = weather_info['timezone']
        cloudy = weather_info['clouds']['all']
        description = weather_info['weather'][0]['description']

        sunrise_time = time_format_for_location(sunrise + timezone)
        sunset_time = time_format_for_location(sunset + timezone)

        weather = f"\nWeather of: {
      
      city_name}\nTemperature (Celsius): {
      
      temp}°\nFeels like in (Celsius): {
      
      feels_like_temp}°\nPressure: {
      
      pressure} hPa\nHumidity: {
      
      humidity}%\nSunrise at {
      
      sunrise_time} and Sunset at {
      
      sunset_time}\nCloud: {
      
      cloudy}%\nInfo: {
      
      description}"
    else:
        weather = f"\n\tWeather for '{
      
      city_name}' not found!\n\tKindly Enter valid City Name !!"

    tfield.delete("1.0", "end")
    tfield.insert(INSERT, weather)   #to insert or send value in our Text Field to display output


Label(root, text = '输入城市名称:', font = 'Arial 12 bold').pack(pady=10) #to generate label heading
Entry(root, textvariable = city_value,  width = 24, font='Arial 14 bold').pack()
Button(root, command = showWeather, text = "获取天气数据", font="Arial 10", bg='lightblue', fg='black', activebackground="teal", padx=5, pady=5 ).pack(pady= 20)
Label(root, text = "今天天气:", font = 'arial 12 bold').pack(pady=10)

tfield = Text(root, width=46, height=10)
tfield.pack()

root.mainloop()

Run the python code as follows:
information

3.4 Example 4: Current Weather + React.js

  • Initialize the project using React scaffolding
    Initialize the project, command.
npx create-react-app my-app

Insert image description here

Start the project and execute the command in the project root directory:

npm start

Insert image description here
Browser access:

http://localhost:3000/

Insert image description here

  • Modify the file: react-demo\src\App.js
import logo from './logo.svg';
import './App.css';
import Weather from './components/Weather';

function App() {
    
    
  return (
    <div className="App">
     <Weather/>
    </div>
  );
}

export default App;

  • Create a new file: react-demo\src\components\Weather.js
import React, {
    
     useState } from 'react'
// import './Weather.css'
import WeatherCard from './WeatherCard'

export default function Weather() {
    
    

    const [formData, setFormData] = useState([]);
    const [data, setData] = useState(null);

    const apiKey = 'your api key'; // https://openweathermap.org/

    const handlerChange = (e) => {
    
    
        setFormData(prev => ({
    
     ...prev, [e.target.name]: e.target.value }))
    }

    const handlerSubmit = async () => {
    
    
        if (!formData.city) {
    
    
            alert("Please Eneter City");
            return
        }

        if (!formData.country) {
    
    
            alert("Please Eneter Country");
            return
        }

        const res = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${
      
      formData.city},${
      
      formData.country}&appid=${
      
      apiKey}`).then((res) => {
    
    
            res.json().then((data) => {
    
    
                setData(data);
                console.log(data);
            });
            ;
        }).catch((err) => {
    
    
            console.log(err);
            setData(null)
            return
        })
    }
    return (
        <div className='weather'>

            <br />

            {
    
    !data ? (
                <div>
                    <span className='title' style={
    
    {
    
    
                        fontSize: 35
                    }}>This is Your weather</span>
                    <input type="text" onChange={
    
    handlerChange} className='input-control' name="city" placeholder="Enter your city" />
                    <input type="text" onChange={
    
    handlerChange} className='input-control' name="country" placeholder="Enter your Country" />
                    <button className='btn' onClick={
    
    handlerSubmit}>
                        Find Now Weather
                    </button>
                </div>
            ) : (
                <>
                    <WeatherCard {
    
    ...data} />

                    <div class="location-container">
                        <button onClick={
    
    () => setData(null)} class="location-button"> <i data-feather="map-pin"></i><span>Change location</span></button>
                    </div>
                </>
            )}

            {
    
    /* Weather Card */}
            {
    
    /* */}

        </div>
    )
}

  • Create a new file: react-demo\src\components\WeatherCard.js
import React from 'react'
// import './WeatherCard.css'

export default function WeatherCard({
     
      name, sys, main, weather, wind,visibility }) {
    
    
    return (
        <div>
            <div class="container">
                <div class="weather-side">
                    <div class="weather-gradient"></div>
                    <div class="date-container">
                        <h2 class="date-dayname"></h2><span class="date-day">
                            {
    
    new Date().toLocaleDateString()}
                        </span><i class="location-icon" data-feather="map-pin"></i><span class="location">
                            {
    
    name} {
    
    sys.country}
                        </span>
                    </div>
                    <div class="weather-container"><i class="weather-icon" data-feather="sun"></i>
                        <img src={
    
    `http://openweathermap.org/img/wn/${
      
      weather[0].icon}.png`} width={
    
    85} />
                        <span>

                        </span>
                        <h1 class="weather-temp">{
    
    Math.floor(main.temp - 273.15)} °C</h1>
                        <h4>
                        Hight/Low {
    
    " - "}
                            {
    
    Math.floor(main.temp_max - 273.15)}
                            / {
    
    " "}
                            {
    
    Math.floor(main.temp_max - 273.15)} °C
                        </h4>



                        <h3 class="weather-desc">{
    
    weather[0].main} ({
    
    weather[0].description})</h3>
                    </div>
                </div>
                <div style={
    
    {
    
    
                    width: '350px'
                }} class="info-side">
                    <div class="today-info-container">
                        <div class="today-info">
                            <div class="precipitation"> <span class="title">PRESSURE</span><span class="value">{
    
    main.pressure} hPa</span>
                                <div class="clear"></div>
                            </div>
                            <div class="humidity"> <span class="title">HUMIDITY</span><span class="value">{
    
    main.humidity} %</span>
                                <div class="clear"></div>
                            </div>
                            <div class="wind"> <span class="title">WIND</span><span class="value">{
    
    Math.floor((wind.speed * 18) / 5)} km/h</span>
                                <div class="clear"></div>
                            </div>
                            <div class="wind"> <span class="title">VISIBILITY</span><span class="value">{
    
    visibility / 1000} km</span>
                                <div class="clear"></div>
                            </div>
                        </div>
                    </div>
                    <div class="week-container">
                    </div>
                </div>
            </div>
        </div>
    )
}

Insert image description here

3.5 Example 5: Current Weather + Vue.js

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>天气预报</title>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
</head>

<body>
  <div id="app">
    <div class="weather">
      <span class="city">{
    
    {
    
     city }}</span>
      <span class="temp">{
    
    {
    
     temperature }}°C</span>
      <span class="description">{
    
    {
    
     description }}</span>
      <img :src="iconUrl" />
    </div>
  </div>

  <script>
    var app = new Vue({
    
    
      el: '#app',
      data: {
    
    
        city: "beijing",
        apiKey: "your api key",
        temperature: "",
        description: "",
        iconCode: ""
      },
      methods: {
    
    
        getWeatherData: function () {
    
    
          let url =
            `https://api.openweathermap.org/data/2.5/weather?q=${
      
      this.city}&appid=${
      
      this.apiKey}&lang=zh_cn`;

          fetch(url)
            .then(response => response.json())
            .then(data => {
    
    
              console.log(data);

              this.temperature = Math.round(data.main.temp - 273.15);
              this.description = data.weather[0].description;
              this.iconCode = data.weather[0].icon;
            })
            .catch(err => {
    
    
              console.log(err);
            });
        }
      },
      computed: {
    
    
        iconUrl: function () {
    
    
          return `http://openweathermap.org/img/w/${
      
      this.iconCode}.png`;
        }
      },
      mounted: function () {
    
    
        this.getWeatherData();
      }
    });
  </script>

</body>
</html>

Browser access is as follows:
Insert image description here

4、PyOWM

4.1 Introduction

PyOWM is a client-side Python wrapper library for the OpenWeatherMap (OWM) Web API. It allows using OWM data in Python applications quickly and easily in a human-friendly way through a simple object model.

PyOWM runs on Python 3.7+.

PyOWM fetches OpenWeatherMap's OneCall API data as a lightweight replacement for Dark Sky.

4.2 Function

  • Weather API v2.5 + OneCall API, providing current weather data, weather forecast, weather history
  • Agro API v1.0, providing soil data and satellite image search and download
  • Air Pollution API v3.0, providing data on CO, O3, NO2 and SO2
  • UV Index API v3.0, providing data on UV exposure
  • Stations API v3.0, allows to create and manage weather stations and publish local weather measurements
  • Weather Alert API v3.0, allows setting triggers on weather conditions and regions, and polling for generated alerts
  • Image tiles for multiple map layers provided by OWM
  • Geocoding API v1.0 allows performing direct/reverse geocoding

4.3 Installation

pip install PyOWM

Insert image description here

4.4 Use

import pyowm

owm = pyowm.OWM('your api key') # TODO: Replace <api_key> with your API key
mgr = owm.weather_manager()
# sf = mgr.weather_at_place('San Francisco, US')
sf = mgr.weather_at_place('beijing, CN')
w = sf.weather
print(w)
print(w.temperature('celsius'))

Insert image description here

5. Others

  • Amap Weather API - free, stable, minimalist, suitable for basic needs of weather forecasting
  • Xinzhi Weather API - Free, lightweight and professional, suitable for basic needs of weather forecasting
  • Hefeng Weather API - Free and paid have the same permissions, unlimited free for non-commercial use, including air quality, astronomy and meteorology
  • OpenWeather - free 1 million times/month minute-level real-time forecasts, weather cloud images
  • AccuWeather - the world's largest weather data service provider, with a long history, accurate data, and the king of weather APIs
  • Visual Crossing - Free access to 50 years of historical weather data that is friendly to non-developers

5.1 Amap Weather API

https://lbs.amap.com/api/webservice/guide/api/weatherinfo
Weather query is a simple HTTP interface that queries the current/future weather conditions in the target area based on the adcode entered by the user. The data source is the China Meteorological Administration. .
Insert image description here

https://restapi.amap.com/v3/weather/weatherInfo?parameters
https://restapi.amap.com/v3/weather/weatherInfo?city=110101&key=<用户key>
https://restapi.amap.com/v3/weather/weatherInfo?key=<用户key>&city=110000&extensions=all

5.2 Xinzhi Weather API

https://www.seniverse.com/
HyperData is a high-precision meteorological data product of Xinzhiwei. It provides standardized data access through the standard Restful API interface. Whether it is APP, smart hardware or enterprise-level systems, you can easily access the detailed weather data you know.
Insert image description here

Xinzhi Weather provides new registered users with a free 14-day trial period of the full interface and enjoys 10,000 free visits.

https://api.seniverse.com/v3/weather/now.json?key=your_api_key&location=beijing&language=zh-Hans&unit=c
https://api.seniverse.com/v3/weather/daily.json?key=<用户key>&location=beijing&language=zh-Hans&unit=c&start=-1&days=5

5.3 Zefeng Weather API

https://www.qweather.com/Hefeng
weather development service provides API, iOS SDK and Android SDK to access location-based weather data, including live weather, 30-day forecast, hourly forecast, air quality AQI, and disaster warning , minute-level precipitation, living index and other weather data services.

GET https://api.qweather.com/v7/weather/now?{
    
    查询参数}
curl -L -X GET --compressed 'https://api.qweather.com/v7/weather/now?location=101010100&key=YOUR_KEY'

Conclusion

如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;╮( ̄▽ ̄)╭
如果您感觉方法或代码不咋地//(ㄒoㄒ)// ,就在评论处留言,作者继续改进;o_O???
如果您需要相关功能的代码定制化开发,可以留言私信作者;(✿◡‿◡)
感谢各位大佬童鞋们的支持!( ´ ▽´ )ノ ( ´ ▽´)! ! !

Guess you like

Origin blog.csdn.net/hhy321/article/details/135315446