ในบทช่วยสอนนี้ เราจะดูสภาพอากาศของเมืองโดยใช้ OpenWeatherMap เอพีไอ ในการใช้ OpenWeatherMap API เราต้องได้รับคีย์ API เราจะได้รับโดยการสร้างบัญชีบนเว็บไซต์ของพวกเขา
สร้างบัญชีและรับรหัส API ของคุณ โทรฟรีถึง 60 ครั้งต่อนาที คุณต้องจ่ายถ้าคุณต้องการมากกว่านั้น สำหรับบทช่วยสอนนี้ เวอร์ชันฟรีก็เพียงพอแล้ว เราต้องการคำขอ โมดูลสำหรับคำขอ HTTP และ JSON โมดูลที่จะทำงานกับการตอบสนอง ทำตามขั้นตอนด้านล่างเพื่อดูสภาพอากาศของเมืองต่างๆ
-
นำเข้าคำขอและโมดูล JSON
-
เริ่มต้น URL พื้นฐานของ weather API https://api.openweathermap.org/data/2.5/weather?.
-
เริ่มต้นเมืองและคีย์ API
-
อัปเดต URL ฐานด้วยคีย์ API และชื่อเมือง
-
ส่งคำขอรับโดยใช้เมธอด Request.get()
-
และดึงข้อมูลสภาพอากาศโดยใช้ JSON โมดูลจากการตอบสนอง
ตัวอย่าง
มาดูโค้ดกันเลย
# importing requests and json
import requests, json
# base URL
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
# City Name CITY = "Hyderabad"
# API key API_KEY = "Your API Key"
# upadting the URL
URL = BASE_URL + "q=" + CITY + "&appid=" + API_KEY
# HTTP request
response = requests.get(URL)
# checking the status code of the request
if response.status_code == 200:
# getting data in the json format
data = response.json()
# getting the main dict block
main = data['main']
# getting temperature
temperature = main['temp']
# getting the humidity
humidity = main['humidity']
# getting the pressure
pressure = main['pressure']
# weather report
report = data['weather']
print(f"{CITY:-^30}")
print(f"Temperature: {temperature}")
print(f"Humidity: {humidity}")
print(f"Pressure: {pressure}")
print(f"Weather Report: {report[0]['description']}")
else:
# showing the error message
print("Error in the HTTP request") ผลลัพธ์
หากคุณเรียกใช้โปรแกรมข้างต้น คุณจะได้ผลลัพธ์ดังต่อไปนี้
----------Hyderabad----------- Temperature: 295.39 Humidity: 83 Pressure: 1019 Weather Report: mist
บทสรุป
หากคุณพบปัญหาในการทำตามบทช่วยสอน โปรดระบุในส่วนความคิดเห็น