使用 Wea​​therbit 时未在结果中显示度量 API

Not showing measures in results when using Weatherbit API

使用Python,需要使用网站API https://www.weatherbit.io/api显示当前天气数据。天气数据应以文本形式显示。我得到了这样的东西,但它没有按预期工作,结果它显示以下没有措施:

#Output

 Enter city name : Paris
 Temperature (in kelvin unit) = ['temp']
 atmospheric pressure (in hPa unit) = ['pres']
 humidity (in percentage) = ['rh']
 description = ['description']

完整代码:

# import required modules
import requests, json

# Enter your API key here
api_key = "API_key"

# base_url variable to store url
base_url = "https://api.weatherbit.io/v2.0/current?"
# Give city name
city_name = input("Enter city name : ")

# complete_url variable to store
# complete url address
complete_url = base_url + "appid=" + api_key + "&q=" + city_name

# get method of requests module
# return response object
response = requests.get(complete_url)

# json method of response object
# convert json format data into
# python format data
x = response.json()


# store the value corresponding
# to the "temp" key of y
current_temperature = ["temp"]

# store the value corresponding
# to the "pressure" key of y
current_pressure = ["pres"]

# store the value corresponding
# to the "humidity" key of y
current_humidity = ["rh"]

# store the value of "weather"
# key in variable z
z = ["weather"]

# store the value corresponding
# to the "description" key at
# the 0th index of z
weather_description = ["description"]

# print following values
print(" Temperature (in kelvin unit) = " +
      str(current_temperature) +
      "\n atmospheric pressure (in hPa unit) = " +
      str(current_pressure) +
      "\n humidity (in percentage) = " +
      str(current_humidity) +
      "\n description = " +
      str(weather_description))

您在所有行中都忘记了 x

为了使其更具可读性,我将使用 name data 而不是 miningless x.

data = response.json()

current_temperature = data["temp"]
current_pressure    = data["pres"]
current_humidity    = data["rh"]
z                   = data["weather"]
weather_description = data["description"]

顺便说一句:

您可以使用名称 weather 而不是 z 来提高代码的可读性。

查看更多PEP 8 -- Style Guide for Python Code


编辑:

具有其他更改的完整代码(但我没有 API_KEY 来测试它)。

  • 你不需要import json
  • 为了安全起见,您可以从环境(或 dot file)中读取 API_KEY
  • 您不必创建完整的 URL 但您可以为此使用 get(..., params=...)
  • 您可以使用 f-string 使代码更具可读性
  • 如果您对每一行分别使用 print(),代码将更具可读性。
import requests

#import os
#api_key = os.getenv("API_KEY")

api_key = "API_KEY"

city_name = input("Enter city name : ")

url = "https://api.weatherbit.io/v2.0/current" # url without `?`

payload = {
    'appid': api_key,
    'q': city_name,
}   

response = requests.get(url, params=payload)

data = response.json()

if 'error' in data:
    print('Error:', data['error'])
else:
    temperature = data["temp"]
    pressure    = data["pres"]
    humidity    = data["rh"]
    weather     = data["weather"]
    description = data["description"]

    print(f"Temperature (in kelvin unit) = {temperature}")
    print(f"atmospheric pressure (in hPa unit) = {pressure}")
    print(f"humidity (in percentage) = {humidity}")
    print(f"description = {description}")

编辑:

我检查了 API 的 current weather 文档,它在 URL 中使用了不同的名称。

必须

payload = {
    'key': api_key,
    'city': city_name,
    #'lang': 'pl'  # for descriptions in my native language Polish
}   

它在 data["data"][0]["temp"] 中给出 temperature,在 data["data"][0]["pres"] 中给出 pressure,等等 - 所以它需要

temperature = data["data"][0]["temp"]
pressure    = data["data"][0]["pres"]
# etc.

或者你也可以

data = data['data'][0]

temperature = data["temp"]
pressure    = data["pres"]

它还在data["data"][0]["weather"]["description"]

中给出了description

在其他请求中,它可能有比 [0] 更多的结果,因此您可能需要使用 for-loop

data = data['data']

for item in data:
    temperature = item["temp"]
    pressure    = item["pres"]
    print(f"Temperature (in kelvin unit) = {temperature}")
    print(f"atmospheric pressure (in hPa unit) = {pressure}")

import requests

#import os
#api_key = os.getenv("API_KEY")

api_key = "ef.............................."

#city_name = input("Enter city name : ")

city_name = 'Warsaw'
url = "https://api.weatherbit.io/v2.0/current" # url without `?`

payload = {
    'key': api_key,
    'city': city_name,
    #'lang': 'pl'  # for descriptions in my native language Polish
}   

response = requests.get(url, params=payload)

data = response.json()

if 'error' in data:
    print('Error:', data['error'])
else:
    #print(data)
    
    data = data['data'][0]
    
    temperature = data["temp"]
    pressure    = data["pres"]
    humidity    = data["rh"]
    weather     = data["weather"]
    description = data["weather"]["description"]
    
    print(f"Temperature (in kelvin unit) = {temperature}")
    print(f"atmospheric pressure (in hPa unit) = {pressure}")
    print(f"humidity (in percentage) = {humidity}")
    print(f"description = {description}")