Thuta Learning
Python
ProjectsProgrammingအခြေခံ

Weather App (Enhanced)

Pythonသင်ခန်းစာ 6635 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • API key ကို source code ထဲ hard-code မလုပ်ဘဲ environment variable ကနေ ဖတ်နိုင်ဖို့
  • requests နဲ့ JSON API ကို params=၊ timeout နဲ့ HTTP status code စစ်ပြီး ခေါ်နိုင်ဖို့
  • Empty input၊ 404၊ 401၊ 429၊ timeout၊ JSON shape မှား စတဲ့ failure တစ်ခုစီကို WeatherError တစ်ခုတည်းအဖြစ် ပြောင်းနိုင်ဖို့
  • Fetch၊ dataclass အဖြစ် parse နဲ့ format ကို ခွဲထားပြီး အပိုင်းတစ်ခုချင်းစီကို offline test လုပ်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

Weather app တစ်ခုက မြင်ရတာ ရိုးရှင်းပါတယ်။ City နာမည် ရိုက်လိုက်ရင် အပူချိန် ပေါ်လာပါတယ်။ ဒါပေမယ့် အဲဒီ line တစ်ကြောင်းနောက်မှာ သင့် program က internet ပေါ်က server တစ်ခုကို data တောင်းတယ်၊ အဖြေကို စောင့်တယ်၊ ပြီးတော့ JSON အစုအဝေးကို လူဖတ်လို့ရတဲ့ စာကြောင်းအဖြစ် ပြောင်းပေးရပါတယ်။

လူအများစု ပထမဆုံးရေးတဲ့ version က အခြေအနေကောင်းတဲ့နေ့မှာ အလုပ်လုပ်ပါတယ်။ ဒီ enhanced version ကတော့ အခြေအနေဆိုးတဲ့နေ့တွေအတွက်ပါ။ City နာမည် စာလုံးပေါင်းမှားတာ၊ Wi-Fi ပြတ်တာ၊ key သက်တမ်းကုန်တာ၊ ဒါမှမဟုတ် "ခဏခဏ မေးလွန်းတယ်" လို့ service က ပြောတာမျိုးပါ။ App ကောင်းတစ်ခုက အဲဒီအခြေအနေတစ်ခုချင်းစီကို crash မဖြစ်ဘဲ၊ screen အလွတ် မပြဘဲ၊ တည်ငြိမ်ပြီး တိကျတဲ့ message နဲ့ ဖြေပေးပါတယ်။

Problem → Why → Solution

ပြဿနာ: အခြေအနေကောင်းတဲ့နေ့အတွက်ပဲ ရေးထားတဲ့ script

Tutorial အများစု စတင်လေ့ရှိတဲ့ version ကို ကြည့်ပါ။ Run လို့ရပြီး key မှန်ရင် weather ကိုတောင် ထုတ်ပြပါတယ်။ ဒါပေမယ့် အခြေအနေဆိုးတဲ့နေ့မှာ သုံးနေတဲ့ user တစ်ယောက်လို ဖတ်ကြည့်ပါ။

Key က source file ထဲမှာ ရှိနေလို့ Git ထဲနဲ့ screenshot တိုင်းထဲ ရောက်သွားပါတယ်။ URL က plain http ဖြစ်လို့ key က encrypt မလုပ်ဘဲ network ပေါ် သွားပါတယ်။ City ကို URL ထဲ တိုက်ရိုက် ကပ်ထည့်ထားလို့ "New York" ဒါမှမဟုတ် "A&B" လို နာမည်က query ကို ပျက်စေပါတယ်။ requests.get() မှာ timeout မရှိလို့ server ရပ်နေရင် app က အမြဲတမ်း ရပ်နေပါလိမ့်မယ်။ ပြီးတော့ typo ကနေ KeyError အထိ ပြဿနာ အားလုံးက မရေမရာ message တစ်ခုတည်းအဖြစ် ပေါင်းသွားပါတယ်။

weather_draft.py
import requests

API_KEY = "a1b2c3d4e5"  # a real key, now committed to Git
URL = "http://api.openweathermap.org/data/2.5/weather"

def get_weather(city):
    url = f"{URL}?q={city}&appid={API_KEY}&units=metric"
    try:
        data = requests.get(url).json()   # no timeout, status never checked
        return f"{data['main']['temp']} C"
    except Exception as e:
        return f"Error: {e}"              # a 404 shows up as: Error: 'main'

ဘာကြောင့် user တွေကို အဆင်မပြေစေတာလဲ

ဒီ code က configuration၊ transport၊ parsing နဲ့ display ဆိုတဲ့ အလုပ်လေးခုကို function တစ်ခုထဲ ရောထားပါတယ်။ ဘာမှ ခွဲမထားလို့ ဘယ်အပိုင်းကိုမှ သီးသန့် စစ်လို့ မရဘဲ failure တိုင်းက တူတူပဲ မြင်ရပါတယ်။ Error: 'main' ဆိုတဲ့ message က user ကို ဘာမှ မပြောပြပါဘူး၊ တကယ်တော့ 404 ဒါမှမဟုတ် 401 က ရုပ်ဖျက်လာတာပါ။ အလုပ်တွေကို ခွဲလိုက်ရင် failure တစ်ခုစီက သူ့ကိုယ်ပိုင် ရိုးသားတဲ့ message ကို ရပါတယ်။

Core concept: layer သေးလေးတွေနဲ့ error map

အားကိုးလို့ရတဲ့ API client ကို အလုပ်တစ်ခုစီပဲ လုပ်တဲ့ layer သေးလေးတွေနဲ့ ဆောက်ပါတယ်။ Layer တွေက ရိုးရိုး Python value တွေကိုပဲ အချင်းချင်း လွှဲပေးလို့ ကျန်တာတွေ မပါဘဲ ဘယ် layer ကိုမဆို test လုပ်လို့ရပါတယ်။ ဒီ project မှာ အဆင့်ငါးဆင့် ရှိပြီး main example က line ခြောက်ဆယ်လောက်နဲ့ အားလုံးကို implement လုပ်ထားပါတယ်။

၁။ Configuration: key ကို environment ကနေ ယူပါ

API key ကို source file ကနေ မဟုတ်ဘဲ os.environ ကနေ ဖတ်ပါတယ်။ Local မှာ shell ထဲ ဒါမှမဟုတ် Git က ignore လုပ်ထားတဲ့ .env file ထဲ သတ်မှတ်ပြီး production မှာတော့ hosting platform က ထည့်ပေးပါတယ်။ Variable မရှိရင် ပထမ request ရောက်မှ fail ဖြစ်တာထက် app စတင်ချိန်မှာပဲ ရှင်းလင်းတဲ့ message နဲ့ ရပ်သင့်ပါတယ်။

၂။ Transport: params၊ https နဲ့ timeout

fetch_weather() က session.get() ကို params= နဲ့ ခေါ်လို့ city ကို requests က URL-encode လုပ်ပေးပါတယ်။ https သုံးပြီး timeout=5 ပေးထားလို့ connection သေနေရင် အမြဲ စောင့်မနေဘဲ ငါးစက္ကန့်အကြာမှာ requests.Timeout တက်ပါတယ်။ Session ကို argument အဖြစ် လက်ခံပါတယ်။ App အစစ်က requests.Session() ကို ပေးပြီး demo ကတော့ fake တစ်ခုကို ပေးပါတယ်။

၃။ Status ကို အရင်၊ body ကို နောက်မှ

JSON ကို မထိခင် resp.status_code ကို အရင်စစ်ပါ။ 404 body မှာ main key လုံးဝ မပါပါဘူး။ ဒါကြောင့် data["main"] ကို အရင်ဖတ်တာက အပေါ်က draft မှာ ရှာမတွေ့တဲ့ city တစ်ခုကို ရှုပ်ထွေးတဲ့ KeyError အဖြစ် ပြောင်းသွားစေတဲ့ အကြောင်းရင်းပါ။

၄။ Domain model အဖြစ် parse လုပ်ပါ

Raw JSON က အဆင့်ဆင့် nest ဖြစ်ပြီး မလိုတဲ့ field တွေ အများကြီး ပါပါတယ်။ သုံးမယ့် field လေးခုကို Weather dataclass ထဲ ကူးထည့်ပါ။ Key တစ်ခုခု ပျောက်နေရင် ဒါမှမဟုတ် type မှားနေရင် WeatherError တစ်ခု raise လုပ်ပါ။ ဒါဆို program ရဲ့ ကျန်တဲ့အပိုင်းက ပြည့်စုံပြီး မှန်ကန်တဲ့ Weather ကိုပဲ မြင်ရပါမယ်။

၅။ Display ကို သီးသန့်ထားပါ

format_weather() က Weather ကို စာသားအဖြစ် ပြောင်းပါတယ်။ Request တစ်ခုမှ မလုပ်လို့ စာသားပြင်တာ ဒါမှမဟုတ် Fahrenheit ထပ်ထည့်တာက network code ကို ဘယ်တော့မှ မထိခိုက်ပါဘူး။

ဖြစ်ရပ်ဘယ်လို သိလဲUser ကို ပြမယ့် message
Input အလွတ်city.strip() က ""City နာမည် ရိုက်ပါ
မရှိတဲ့ citystatus 404City not found
Key မှား/သက်တမ်းကုန်status 401API key rejected
ခေါ်လွန်းတာstatus 429တစ်မိနစ်လောက် စောင့်ပါ
Server ရပ်နေတာrequests.TimeoutService နှေးနေတယ်
Field ပျောက်တာKeyError / IndexErrorData shape မမှန်ဘူး
Mental model: checkpoint တန်းစီ
  1. User input ကို သန့်စင်ပြီး စစ်ပါ
  2. params နဲ့ timeout တွဲပြီး ပို့ပါ
  3. Status code ကို အရင်စစ်ပါ
  4. JSON field တွေကို dataclass ထဲ ကူးပါ
  5. ရလဒ်ကို ပြဖို့ format လုပ်ပါ

Checkpoint တိုင်းက WeatherError တစ်ခုနဲ့ တန်းစီကို ရပ်နိုင်ပါတယ်။ ဒါကြောင့် ခေါ်တဲ့သူမှာ except clause တစ်ခုပဲ လိုပါတယ်။

အခြေခံ ပုံစံ

python
def fetch(query, session, api_key):
    try:
        resp = session.get(URL, params={"q": query, "key": api_key}, timeout=5)
    except requests.RequestException:
        raise AppError("network problem")
    if resp.status_code != 200:
        raise AppError(f"service answered {resp.status_code}")
    data = resp.json()
    return Model(field=data["field"])

Session ကို inject လုပ်၊ params နဲ့ timeout တွဲပို့၊ network error ကို app ရဲ့ ကိုယ်ပိုင် exception အဖြစ် ပြောင်း၊ status ကို စစ်ပြီးမှ JSON ကို model ထဲ ကူးပါ။

Enhanced weather client ကို offline test လုပ်ကြည့်မယ်

အောက်က file က input() prompt မပါတဲ့ app တစ်ခုလုံးပါ။ FakeSession က requests.Session() ရဲ့ နေရာမှာ ဝင်ကစားပါတယ်။ get() method တူတူ ရှိပေမယ့် dictionary ထဲကနေ ဖြေပေးလို့ key မလိုဘဲ network မလိုဘဲ demo ကို run လို့ရပါတယ်။

City ခြောက်ခုက fetch_weather() ထဲမှာ လမ်းကြောင်း ခြောက်မျိုး ဖြစ်စေပါတယ်။ အောင်မြင်တဲ့ လမ်းတစ်ခုနဲ့ failure ငါးမျိုးပါ။ Output ကို မကြည့်ခင် city တစ်ခုစီအတွက် ဘာထွက်မလဲ ခန့်မှန်းကြည့်ပါ။

weather_app.py
import os
from dataclasses import dataclass

import requests

API_URL = "https://api.openweathermap.org/data/2.5/weather"


class WeatherError(Exception):
    """A problem we can explain to the user in one friendly sentence."""


@dataclass
class Weather:
    city: str
    temp_c: float
    description: str
    humidity: int


def fetch_weather(city, session, api_key):
    city = city.strip()
    if not city:
        raise WeatherError("Please type a city name.")
    params = {"q": city, "appid": api_key, "units": "metric"}
    try:
        resp = session.get(API_URL, params=params, timeout=5)
    except requests.Timeout:
        raise WeatherError("The weather service is too slow, try again soon.")
    except requests.ConnectionError:
        raise WeatherError("No connection to the weather service.")

    if resp.status_code == 404:
        raise WeatherError(f"City not found: {city}")
    if resp.status_code == 401:
        raise WeatherError("API key rejected, check OPENWEATHER_API_KEY.")
    if resp.status_code == 429:
        raise WeatherError("Too many requests, wait a minute.")
    if resp.status_code != 200:
        raise WeatherError(f"Weather service error ({resp.status_code}).")

    data = resp.json()
    try:
        return Weather(
            city=data["name"],
            temp_c=float(data["main"]["temp"]),
            description=data["weather"][0]["description"],
            humidity=int(data["main"]["humidity"]),
        )
    except (KeyError, IndexError, TypeError, ValueError):
        raise WeatherError("The service sent data in an unexpected shape.")


def format_weather(w):
    return f"{w.city}: {w.temp_c:.1f} C, {w.description}, humidity {w.humidity}%"


# ---- Offline stand-ins for requests.Session (no network needed) ----
class FakeResponse:
    def __init__(self, status_code, payload):
        self.status_code = status_code
        self._payload = payload

    def json(self):
        return self._payload


class FakeSession:
    def __init__(self, outcomes):
        self.outcomes = outcomes  # city -> FakeResponse or an exception

    def get(self, url, params=None, timeout=None):
        outcome = self.outcomes[params["q"]]
        if isinstance(outcome, Exception):
            raise outcome
        return outcome


yangon = {"name": "Yangon", "main": {"temp": 31.46, "humidity": 74},
          "weather": [{"description": "scattered clouds"}]}
session = FakeSession({
    "Yangon": FakeResponse(200, yangon),
    "Atlantis": FakeResponse(404, {"message": "city not found"}),
    "Mandalay": FakeResponse(200, {"name": "Mandalay", "weather": []}),
    "Bago": requests.Timeout(),
    "Paris": FakeResponse(429, {"message": "rate limit"}),
})
# Real app: api_key = os.environ["OPENWEATHER_API_KEY"]; session = requests.Session()
api_key = os.environ.get("OPENWEATHER_API_KEY", "demo-key")

for city in ["Yangon", "   ", "Atlantis", "Mandalay", "Bago", "Paris"]:
    try:
        print(format_weather(fetch_weather(city, session, api_key)))
    except WeatherError as err:
        print(f"[{city.strip() or '?'}] {err}")

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Secret from the environmentapi_key = os.environ.get("OPENWEATHER_API_KEY", "demo-key")

    Demo ကို ဘယ်သူမဆို run လို့ရအောင် fallback value ပေးထားပါတယ်။ App အစစ်မှာ os.environ["OPENWEATHER_API_KEY"] လို့ ရေးပါ။ Variable မရှိရင် စတင်ချိန်မှာပဲ KeyError တက်ပြီး ရပ်သွားပါတယ်။

  2. params= and timeout=resp = session.get(API_URL, params=params, timeout=5)

    params dictionary ကို requests က ?q=...&appid=... အဖြစ် encode လုပ်ပေးပါတယ်။ timeout=5 က server ငါးစက္ကန့်ထက် ပိုကြာရင် requests.Timeout တက်စေပါတယ်။

  3. Status before bodyif resp.status_code == 404:

    Status code တစ်ခုစီက ကိုယ်ပိုင် message ရပါတယ်။ resp.json() ကို status 200 ဖြစ်မှသာ ဖတ်ပါတယ်။

  4. Parse or rejectexcept (KeyError, IndexError, TypeError, ValueError):

    Mandalay ရဲ့ fake payload မှာ main key မပါလို့ data["main"] က KeyError တက်ပြီး ဒီ line က ဖမ်းပါတယ်။ Traceback မဟုတ်ဘဲ ယဉ်ကျေးတဲ့ message ထွက်ပါတယ်။

  5. A fake that raisesif isinstance(outcome, Exception):

    Bago အတွက် requests.Timeout() object ကို သိမ်းထားလို့ fake session က အဲဒါကို raise လုပ်ပါတယ်။ Server တကယ်ရပ်နေတာကို စက္ကန့်ငါး မစောင့်ဘဲ simulate လုပ်တာပါ။

  6. One except for the callerexcept WeatherError as err:

    Failure ငါးမျိုးလုံးက WeatherError အဖြစ် ရောက်လာလို့ loop မှာ except တစ်ခုပဲ လိုပါတယ်။ NameError လို programming bug တွေကိုတော့ မဖမ်းလို့ ချက်ချင်း မြင်ရပါတယ်။

You should see
Yangon: 31.5 C, scattered clouds, humidity 74%
[?] Please type a city name.
[Atlantis] City not found: Atlantis
[Mandalay] The service sent data in an unexpected shape.
[Bago] The weather service is too slow, try again soon.
[Paris] Too many requests, wait a minute.

Network မပါဘဲ client ကို test လုပ်ခြင်း

Session ကို parameter အဖြစ် လက်ခံတာ (dependency injection) က ဒီ project ရဲ့ အရေးကြီးဆုံး ဆုံးဖြတ်ချက်ပါ။ Test တွေက internet ပေါ် မမှီခိုတော့လို့ မြန်ပြီး ရလဒ် အမြဲတူပါတယ်။ Server က အပိုင်းအစ JSON ပြန်ပို့တာ၊ 429 ပြန်ပို့တာလို တကယ့် service ပေါ်မှာ ဖန်တီးဖို့ ခက်တဲ့ case တွေကိုလည်း စိတ်ကြိုက် ဖန်တီးလို့ရပါတယ်။

Fake class ကိုယ်တိုင် မရေးချင်ရင် standard library ထဲက unittest.mock ကို သုံးလို့ရပါတယ်။ Mock object က ဘယ် attribute မဆို လက်ခံပြီး သင်ပြင်ဆင်ထားတဲ့ value ကို ပြန်ပေးပါတယ်။ ပြီးတော့ ဘယ် argument တွေနဲ့ ခေါ်ခံရလဲဆိုတာ မှတ်ထားလို့ timeout ပါမပါကိုပါ စစ်လို့ရပါတယ်။

mock_session.py
from unittest import mock

response = mock.Mock(status_code=404)
response.json.return_value = {"message": "city not found"}
session = mock.Mock()
session.get.return_value = response

resp = session.get("https://api.example.com/weather",
                   params={"q": "Atlantis"}, timeout=5)
print(resp.status_code, resp.json())
print("sent params:", session.get.call_args.kwargs["params"])
print("timeout used:", session.get.call_args.kwargs["timeout"])

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ

Delivery app ရဲ့ မိုးရွာမယ့် သတိပေးချက်၊ စိုက်ပျိုးရေး dashboard၊ smart-home thermostat လို production weather feature တွေက ဒီ layer တွေကိုပဲ သုံးပြီး ထပ်ဆောင်း စိုးရိမ်စရာ နှစ်ခု ရှိပါတယ်။ ပထမက ကုန်ကျစရိတ်နဲ့ quota ပါ။ Free API plan တွေက တစ်မိနစ်နဲ့ တစ်ရက်ချင်း ခေါ်နိုင်တဲ့ အကြိမ်ကို ကန့်သတ်ထားလို့ app တွေက page view တိုင်းအတွက် API ကို မခေါ်ဘဲ city တစ်ခုစီရဲ့ reading ကို မိနစ်အနည်းငယ် cache လုပ်ပြီး user တွေကြား မျှသုံးပါတယ်။ ဒုတိယက အချိန်နဲ့ပတ်သက်ပြီး ရိုးသားဖို့ပါ။ Cache ထဲက ဒါမှမဟုတ် fallback reading က ဘယ်လောက် ဟောင်းနေပြီလဲ ပြောသင့်ပြီး API က timestamp တွေကို server ရဲ့ အချိန်နဲ့ မဟုတ်ဘဲ အဲဒီ city ရဲ့ local time နဲ့ ပြသင့်ပါတယ်။

Team တွေက key ကို browser ထဲကိုလည်း လုံးဝ မရောက်စေပါဘူး။ Mobile ဒါမှမဟုတ် web front end က team ရဲ့ ကိုယ်ပိုင် backend ကို ခေါ်ပြီး OPENWEATHER_API_KEY ကို backend ကပဲ ကိုင်ထားပါတယ်။ မဟုတ်ရင် ဘယ်သူမဆို developer tools ဖွင့်ပြီး key ကို copy ကူးသွားနိုင်ပါတယ်။

အမှားများ

ဖြစ်လေ့ရှိတဲ့ အမှားများ

အရာအားလုံးကို except Exception နဲ့ ဖုံးထားတာ

except Exception က network failure တွေနဲ့အတူ variable နာမည် typo ကြောင့်ဖြစ်တဲ့ NameError လို သင့်ကိုယ်ပိုင် bug တွေကိုပါ ဖမ်းပြီး "Error: ..." message နောက်မှာ ဖုံးကွယ်ထားပါတယ်။ requests.Timeout၊ requests.ConnectionError နဲ့ parsing error တွေလို မျှော်လင့်ထားတဲ့ exception တွေကိုပဲ ဖမ်းပါ။

Timeout မပါဘဲ requests ကို ခေါ်တာ

requests မှာ default timeout မရှိပါဘူး။ Server က connection လက်ခံပြီး ဘာမှ ပြန်မပို့ရင် call က အကန့်အသတ်မရှိ စောင့်နေနိုင်ပြီး app တစ်ခုလုံး ရပ်သွားပါတယ်။ Request တိုင်းမှာ timeout= ကို ပေးပါ။

Status မစစ်ခင် JSON ကို ဖတ်တာ

Error response တွေမှာ body shape မတူပါဘူး။ data["main"] ကို အရင်ဖတ်ရင် "city not found" အစား KeyError: 'main' ကို ရပါတယ်။ status_code ကို အမြဲ အရင်စစ်ပါ။

URL အပြည့်ကို log ထုတ်တာ

Query string ထဲမှာ appid=... ပါလို့ URL အပြည့်ကို print ဒါမှမဟုတ် log ထုတ်ရင် key ပေါက်ကြားပါတယ်။ City နာမည်နဲ့ status code ကိုပဲ log ထုတ်ပါ။

Best Practices

Best practices

  • Request အများကြီး လုပ်တဲ့ program မှာ connection ကို ပြန်သုံးနိုင်အောင် requests.Session() တစ်ခုကို with block ထဲမှာ သုံးပါ
  • Temperature unit (metric/imperial) ကို output ထဲမှာ အမြဲ ဖော်ပြပါ
  • Failure path တစ်ခုစီအတွက် fake response တစ်ခုနဲ့ test တစ်ခု ထားပါ
  • Key ကို ပြောင်းလဲ (rotate) လို့ရအောင် code ထဲမှာ ဘယ်တော့မှ မထည့်ပါနဲ့

Mini challenge

Freshness label ပါတဲ့ cache ထည့်ပါ

Free API plan တွေက ခေါ်နိုင်တဲ့ အကြိမ်ကို ကန့်သတ်ပါတယ်။ City တစ်ခုစီရဲ့ reading ကို ttl_seconds အတွင်း မှတ်ထားပြီး service fail ဖြစ်ရင် error အစား reading အဟောင်းကို stale label နဲ့ ပြန်ပေးတဲ့ WeatherCache class ကို ရေးပါ။

  • get(city) က (reading, label) ကို ပြန်ပေးပါ။ label က "fresh" ဒါမှမဟုတ် "stale, N min old" ဖြစ်ပါမယ်
  • " yangon " နဲ့ "Yangon" ကို city တစ်ခုတည်းအဖြစ် သတ်မှတ်ပါ
  • ttl_seconds အတွင်းဆိုရင် fetch ကို မခေါ်ဘဲ သိမ်းထားတဲ့ reading ကို ပြန်ပေးပါ
  • fetch က WeatherError raise လုပ်ပြီး reading အဟောင်း ရှိရင် stale အဖြစ် ပြန်ပေးပါ၊ မရှိရင် re-raise လုပ်ပါ
  • Test တွေက sleep မလုပ်ဘဲ အချိန်ရွှေ့နိုင်အောင် clock ကို parameter အဖြစ် လက်ခံပါ
weather_cache.py
class WeatherError(Exception):
    pass


class WeatherCache:
    def __init__(self, fetch, clock, ttl_seconds=600):
        # TODO: store fetch, clock and the ttl; start with an empty dict
        ...

    def get(self, city):
        # TODO: turn the city into a cache key (strip + lower)
        # TODO: saved reading younger than the ttl -> return (reading, "fresh")
        # TODO: otherwise call fetch(city) and save (now, reading)
        # TODO: on WeatherError return the old reading as "stale, N min old",
        #       or re-raise when nothing was saved
        ...


# TODO: test with a fake clock (a list you change) and a fake fetch function

ရလဒ်: ပထမ call က fetch ကို တစ်ကြိမ်ခေါ်ပြီး ဒုတိယ call (၂ မိနစ်အကြာ) က fetch မခေါ်ဘဲ fresh ပြန်ရပါတယ်။ ၁၅ မိနစ်အကြာ service ပျက်နေရင် "stale, 15 min old" ရပြီး မသိမ်းရသေးတဲ့ Bago ကတော့ error ပဲ ရပါတယ်။

အရိပ်အမြွက် ကြည့်ရန်

Entry တစ်ခုစီကို (saved_at, reading) tuple အဖြစ် သိမ်းပါ။ now - saved_at < ttl ဆိုရင် fresh ပါ။ Minute ရဖို့ int((now - saved_at) // 60) ကို သုံးပါ။ Fake clock အတွက် fake_time = [0] list ကို သုံးပြီး clock=lambda: fake_time[0] လို့ ပေးနိုင်ပါတယ်။

အဖြေ ကြည့်ရန်
weather_cache.py
class WeatherError(Exception):
    pass


class WeatherCache:
    def __init__(self, fetch, clock, ttl_seconds=600):
        self.fetch = fetch          # function: city -> reading (may raise)
        self.clock = clock          # function: () -> current time in seconds
        self.ttl = ttl_seconds
        self.entries = {}           # city key -> (saved_at, reading)

    def get(self, city):
        key = city.strip().lower()
        now = self.clock()
        if key in self.entries:
            saved_at, reading = self.entries[key]
            if now - saved_at < self.ttl:
                return reading, "fresh"
        try:
            reading = self.fetch(city)
        except WeatherError:
            if key in self.entries:
                saved_at, reading = self.entries[key]
                minutes = int((now - saved_at) // 60)
                return reading, f"stale, {minutes} min old"
            raise
        self.entries[key] = (now, reading)
        return reading, "fresh"


# ---- test doubles: a fake clock and a fake fetch function ----
fake_time = [0]
calls = []
service_up = [True]


def fake_fetch(city):
    calls.append(city)
    if not service_up[0]:
        raise WeatherError("service down")
    return f"{city.strip()} 31 C"


cache = WeatherCache(fake_fetch, clock=lambda: fake_time[0], ttl_seconds=600)

print(cache.get("Yangon"), "calls:", len(calls))
fake_time[0] = 120
print(cache.get(" yangon "), "calls:", len(calls))
fake_time[0] = 900
service_up[0] = False
print(cache.get("Yangon"), "calls:", len(calls))
try:
    cache.get("Bago")
except WeatherError as err:
    print("Bago:", err)

Quick Quiz 1 / 3

Main example မှာ JSON ထဲ "main" key မပါတဲ့ Mandalay entry အတွက် loop က ဘာ print ထုတ်မလဲ။

Quick Quiz 2 / 3

fetch_weather() က city ကို f-string URL ထဲ မထည့်ဘဲ params= နဲ့ ပို့တာ ဘာကြောင့်လဲ။

Quick Quiz 3 / 3

Teammate တစ်ယောက်က timeout မပါဘဲ requests.get(url) လို့ ရေးပါတယ်။ Server က connection လက်ခံပြီး ဘယ်တော့မှ မဖြေရင် ဘာဖြစ်မလဲ။

မှတ်ထားရမယ့် အချက်များ

  • API key ကို os.environ ကနေ ဖတ်ပြီး code၊ log၊ URL print တွေထဲ ဘယ်တော့မှ မထည့်ပါနဲ့
  • params=၊ https နဲ့ timeout= ကို request တိုင်းမှာ သုံးပါ
  • Status code ကို အရင်စစ်ပြီးမှ JSON ကို dataclass ထဲ parse လုပ်ပါ
  • Failure အားလုံးကို ကိုယ်ပိုင် exception တစ်ခုအဖြစ် ပြောင်းပြီး message တစ်ခုစီကို တိကျအောင် ရေးပါ
  • Session ကို inject လုပ်ရင် failure path တိုင်းကို network မပါဘဲ test လုပ်နိုင်ပါတယ်

Requests — User Guide — Requests

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Weather App (Enhanced) | Thuta Learning