Redis でキー・バリュー データを取得する
Redis と Python を使ってキーと値のペアを保存する練習ができたので、次はそのもう一方のプロセスである取得に進みます。ここでは、天気データをレポートする Web アプリケーションで見かけるかもしれない、いくつかのキーと値のペアを取得する練習をします。
接続オブジェクトは作成済みで、変数 redis_conn に格納されています。さあ始めましょう!
この演習はコースの一部です
NoSQL入門
演習の手順
redis_conn変数と適切なメソッドを使って、citiesのリストにある各cityの気温を Redis から取得してみてください。- 渡されたキーに対する
temperatureの値がNoneの場合は、そのキーの値として"unknown temperature"を設定し、短いメッセージを出力します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# 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}")