การดึงข้อมูล key-value ด้วย Redis
หลังจากฝึกบันทึก key-value pairs ด้วย Redis และ Python แล้ว ถึงเวลาสำรวจอีกด้านของกระบวนการนั้น นั่นคือการดึงข้อมูล key-value pairs กลับมา ในแบบฝึกหัดนี้จะได้ฝึกดึงข้อมูล key-value pairs หลายรูปแบบที่อาจพบได้ในเว็บแอปพลิเคชันสำหรับรายงานข้อมูลสภาพอากาศ
ได้สร้าง connection object และเก็บไว้ในตัวแปร redis_conn ให้พร้อมแล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
NoSQL เบื้องต้น
คำแนะนำการฝึกหัด
- ใช้ตัวแปร
redis_connและเมธอดที่เหมาะสมเพื่อดึงค่าอุณหภูมิของแต่ละcityในรายการcitiesจาก Redis - หากค่า
temperatureที่ได้จาก key นั้นเป็นNoneให้กำหนดค่า"unknown temperature"สำหรับ key นั้น และแสดงข้อความสั้น ๆ
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Loop through each of the cities
for city in cities:
# Grab the temperature
temperature = ____.___(f"{city}_temp")
# Check if the temperature is None
if temperature is None:
# Store an unknown temperature
____.____(f"{city}_temp", "unknown temperature")
print(f"Unknown temperature in {city}")
else:
# Otherwise, print the temperature
print(f"The temperature in {city} is {temperature}")