ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
requests.get() ကို တစ်ခါခေါ်တိုင်း ဖုန်းဆက်ပြီး ကိုယ့်နာမည်၊ အကောင့်နံပါတ်ကို အစကနေ ပြန်ပြော၊ ပြီးတာနဲ့ ဖုန်းချတာနဲ့ တူပါတယ်။ မေးခွန်း တစ်ခုနှစ်ခုဆိုရင် အဆင်ပြေပေမယ့် မေးခွန်း ရာချီရှိရင် အချိန်ကုန်ပါတယ်။
requests.Session ကတော့ ဖုန်းလိုင်းကို ဖွင့်ထားပြီး ကိုယ့်အချက်အလက်ကို တစ်ခါပဲ ပြောထားတာနဲ့ တူပါတယ်။ Header, cookie နဲ့ connection တွေကို request တိုင်းမှာ ပြန်သုံးပေးလို့ code လည်း တိုပြီး program လည်း ပိုမြန်ပါတယ်။
Problem → Why → Solution
ပြဿနာ: loop ထဲမှာ requests.get() နဲ့ verify=False
အောက်က script က item စာမျက်နှာ ၅၀၀ ကို ဆွဲယူပါတယ်။ Request တိုင်းမှာ connection အသစ်နဲ့ TLS handshake ကို အစကနေ ပြန်လုပ်ရလို့ နှေးပြီး header ကိုလည်း ထပ်ခါထပ်ခါ ရေးထားပါတယ်။ ပိုဆိုးတာက တစ်ယောက်ယောက်က SSL certificate error ကို "ပြင်" ဖို့ verify=False ထည့်ထားလို့ man-in-the-middle တိုက်ခိုက်မှုကို တံခါးဖွင့်ပေးထားပါတယ်။ timeout နဲ့ status စစ်တာလည်း မပါပါဘူး။
import requests
items = []
for page in range(1, 501):
r = requests.get(f"https://api.example.com/items?page={page}",
headers={"Authorization": f"Bearer {TOKEN}"},
verify=False) # silences the SSL error... and the safety
items.extend(r.json()) # no timeout, no status checkဘာကြောင့် နှေးပြီး အန္တရာယ်ရှိတာလဲ
Module-level requests.get() က ခေါ်တိုင်း Session အသစ်တစ်ခု ဖန်တီးပြီး ပြီးတာနဲ့ ပိတ်ပစ်လို့ keep-alive connection ကို ပြန်မသုံးနိုင်ပါဘူး။ verify=False က server ရဲ့ certificate ကို လုံးဝ မစစ်တော့လို့ network ကြားက တစ်ယောက်ယောက်က server အယောင်ဆောင်ပြီး Bearer token ကို ခိုးယူနိုင်ပါတယ်။ Session တစ်ခု၊ timeout တစ်ခု၊ raise_for_status() တစ်ခုနဲ့ ဒီပြဿနာ အားလုံးကို ဖြေရှင်းလို့ရပါတယ်။
Core concept: Session, timeout နဲ့ exception များ
requests.Session() က request တွေကြား state ကို သိမ်းထားပါတယ်။ session.headers.update(...) နဲ့ ထည့်ထားတဲ့ header တွေ၊ server ပို့တဲ့ cookie တွေ၊ session.auth တို့ကို request တိုင်းမှာ အလိုအလျောက် ပါစေပြီး အောက်ခြေမှာ urllib3 connection pool က host တစ်ခုတည်းဆီ connection တွေကို ပြန်သုံးပေးပါတယ်။ session.get(), post(), put(), patch(), delete() က module function တွေနဲ့ argument အတူတူ လက်ခံပါတယ်။ with requests.Session() as session: နဲ့ ရေးရင် အဆုံးမှာ connection တွေကို ပိတ်ပေးပါတယ်။
params= က dict ကို URL encode လုပ်ပြီး query string အဖြစ် ပေါင်းပေးပါတယ် — space က + ဖြစ်ပြီး & လို စာလုံးတွေကိုလည်း escape လုပ်ပါတယ်။ timeout=5 ဆိုတာ စုစုပေါင်း ၅ စက္ကန့် မဟုတ်ပါဘူး၊ connect လုပ်တာနဲ့ server က byte တွေကြား စောင့်တာ (read) နှစ်ခုစီကို သီးခြား ကန့်သတ်တာပါ။ timeout=(3.05, 10) လို tuple နဲ့ connect timeout နဲ့ read timeout ကို ခွဲပေးလို့ရပါတယ်။ TLS certificate ကိုလည်း default အနေနဲ့ စစ်ပါတယ်၊ company ရဲ့ internal CA ဆိုရင် verify="/path/to/ca.pem" ပေးပါ၊ False မပေးပါနဲ့။
ပြန်လာတဲ့ Response object မှာလည်း သိထားသင့်တဲ့ attribute တွေ ရှိပါတယ်။ response.ok က status 400 အောက်ဆိုရင် True ဖြစ်ပြီး response.headers က စာလုံးအကြီးအသေး မခွဲတဲ့ dict ပါ — headers["content-type"] နဲ့ headers["Content-Type"] တူတူပါပဲ။ response.content က raw bytes၊ response.text က encoding နဲ့ decode လုပ်ထားတဲ့ string ဖြစ်ပြီး response.url က redirect တွေ ပြီးနောက် နောက်ဆုံး URL၊ response.history က ဖြတ်ခဲ့တဲ့ redirect response တွေပါ။
| Exception | ဘယ်အချိန် ဖြစ်လဲ |
|---|---|
| ConnectionError | DNS မတွေ့၊ server ငြင်း၊ network ပြတ် |
| Timeout (ConnectTimeout, ReadTimeout) | သတ်မှတ်ချိန်အတွင်း မချိတ်နိုင် ဒါမှမဟုတ် data မလာ |
| HTTPError | raise_for_status() က 4xx/5xx တွေ့ |
| JSONDecodeError | response.json() က JSON မဟုတ်တဲ့ body ကို တွေ့ |
| RequestException | အပေါ်က အားလုံးရဲ့ base class |
Exception အားလုံးက requests.exceptions.RequestException ကနေ ဆင်းသက်လို့ except အစဉ်က အရေးကြီးပါတယ် — တိကျတဲ့ class (HTTPError, Timeout) ကို အရင်ဖမ်းပြီး RequestException ကို နောက်ဆုံးမှာ ထားပါ။ session.mount(prefix, adapter) က URL prefix တစ်ခုအတွက် request တွေကို ဘယ် transport adapter က ပို့မလဲ ရွေးပေးပါတယ်။ HTTPAdapter(max_retries=...) နဲ့ retry ထည့်တာ၊ test မှာ network ကို fake adapter နဲ့ အစားထိုးတာ ဒီနည်းနဲ့ပါပဲ။
- Session က default header ပေါင်းထည့်
- params ကို URL ထဲ encode
- Prefix နဲ့ ကိုက်တဲ့ adapter က ပို့
- raise_for_status() နဲ့ status စစ်
Adapter ကို လဲလိုက်ရုံနဲ့ retry ထည့်တာ၊ offline test လုပ်တာ ဖြစ်နိုင်ပြီး ကျန်တဲ့ code ကို ပြင်စရာ မလိုပါဘူး။
အထွေထွေ ပုံစံ
with requests.Session() as session:
session.headers.update({"Header-Name": "value"})
try:
resp = session.get(url, params=query, timeout=(connect_s, read_s))
resp.raise_for_status()
data = resp.json()
except requests.exceptions.HTTPError as e:
handle_status(e.response.status_code)
except requests.exceptions.RequestException as e:
handle_network_problem(e)Session ကို with နဲ့ ဖွင့်၊ default header ကို တစ်ခါပဲ သတ်မှတ်၊ request တိုင်းမှာ timeout ပေးပါ။ HTTPError ကို အရင်ဖမ်းပြီး network ပြဿနာ အားလုံးကို RequestException နဲ့ နောက်ဆုံးမှာ ဖမ်းပါ။
Example: fake adapter ပေါ်က Session
Internet မလိုအောင် FakeTransport adapter က network အစား response တွေကို ကိုယ်တိုင် ဖန်တီးပြန်ပေးပါတယ်။ Session, params encode လုပ်တာ, timeout ကို adapter ဆီ လွှဲပေးတာ, raise_for_status() တို့ကတော့ requests ရဲ့ တကယ့် code ပါ။ Adapter က ပို့လာတဲ့ request ကို print ထုတ်ပြလို့ Session က ဘာတွေ ပေါင်းထည့်ပေးလဲ မြင်ရပါတယ်။
import json
import requests
from requests.adapters import BaseAdapter
# --- Offline stand-in for the network: a transport adapter that answers itself ---
class FakeTransport(BaseAdapter):
def send(self, request, **kwargs):
print(f"-> {request.method} {request.url} timeout={kwargs['timeout']}")
print(f" Accept: {request.headers['Accept']}")
resp = requests.Response()
resp.request, resp.url = request, request.url
if "/users/1" in request.url:
resp.status_code, resp.reason = 200, "OK"
resp._content = json.dumps({"id": 1, "name": "Aye"}).encode()
elif "/users?" in request.url:
resp.status_code, resp.reason = 200, "OK"
resp._content = json.dumps([{"id": 7, "name": "Aye Mya"}]).encode()
else:
resp.status_code, resp.reason = 404, "Not Found"
resp._content = b'{"error": "no such user"}'
resp.headers["Content-Type"] = "application/json"
return resp
def close(self):
pass
API = "https://api.example.com"
session = requests.Session()
session.headers.update({"Accept": "application/json"})
session.mount(API, FakeTransport())
r = session.get(f"{API}/users/1", timeout=5)
r.raise_for_status()
print("user:", r.json())
r = session.get(f"{API}/users", params={"q": "aye mya", "page": 2}, timeout=(3.05, 10))
print("search:", r.status_code, r.json())
try:
r = session.get(f"{API}/users/42", timeout=5)
r.raise_for_status()
except requests.exceptions.HTTPError as e:
print("HTTPError:", e)Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Default header
session.headers.update({"Accept": "application/json"})တစ်ခါပဲ ရေးထားပေမယ့် output မှာ request သုံးခုလုံး Accept: application/json ပါသွားတာကို မြင်ရပါတယ်။
- Mount
session.mount(API, FakeTransport())https://api.example.com နဲ့ စတဲ့ URL တွေကို FakeTransport က ပို့ပါတယ်။ Production မှာတော့ ဒီ line ကို ဖျက်ရုံ (ဒါမှမဟုတ် retry ပါတဲ့ HTTPAdapter နဲ့ အစားထိုး) ပါပဲ။
- params + tuple timeout
r = session.get(f"{API}/users", params={"q": "aye mya", "page": 2}, timeout=(3.05, 10))URL က ?q=aye+mya&page=2 ဖြစ်လာပြီး adapter က timeout=(3.05, 10) ကို လက်ခံရရှိပါတယ်။ Real HTTPAdapter ဆိုရင် connect ကို 3.05 စက္ကန့်၊ read ကို 10 စက္ကန့် ကန့်သတ်ပါမယ်။
- Adapter receives kwargs
def send(self, request, **kwargs):Session က PreparedRequest ကို adapter.send() ဆီ timeout, verify, proxies လို keyword တွေနဲ့ လွှဲပေးပါတယ်။ Fake ဖြစ်ပေမယ့် တကယ့် adapter interface အတိုင်းပါ။
- HTTPError message
r.raise_for_status() except requests.exceptions.HTTPError as e:404 ဖြစ်လို့ HTTPError ပစ်ပြီး message မှာ status, reason နဲ့ URL ပါပါတယ်။ e.response ကနေ response တစ်ခုလုံးကို ပြန်ယူလို့ရပါတယ်။
-> GET https://api.example.com/users/1 timeout=5
Accept: application/json
user: {'id': 1, 'name': 'Aye'}
-> GET https://api.example.com/users?q=aye+mya&page=2 timeout=(3.05, 10)
Accept: application/json
search: 200 [{'id': 7, 'name': 'Aye Mya'}]
-> GET https://api.example.com/users/42 timeout=5
Accept: application/json
HTTPError: 404 Client Error: Not Found for url: https://api.example.com/users/42
HTTPAdapter နဲ့ retry ထည့်ခြင်း
requests ကိုယ်တိုင်က retry မလုပ်ပေးပါဘူး၊ ဒါပေမယ့် urllib3 ရဲ့ Retry object ကို HTTPAdapter ထဲ ထည့်ပြီး mount လုပ်လို့ရပါတယ်။ backoff_factor က ကြိုးစားမှုတစ်ခုနဲ့တစ်ခုကြား စောင့်ချိန်ကို တဖြည်းဖြည်း တိုးပေးပြီး status_forcelist က ဘယ် status တွေမှာ ပြန်ကြိုးစားမလဲ သတ်မှတ်ပါတယ်။ allowed_methods ကို GET နဲ့ HEAD ပဲ ထားတာက POST ကို မတော်တဆ နှစ်ခါ မပို့မိအောင်ပါ။ ဒီ snippet က adapter ကို ပြင်ဆင်ရုံပဲ လုပ်ပြီး request မပို့ပါဘူး။
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
retry = Retry(total=3, backoff_factor=0.5,
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["GET", "HEAD"]) # never blindly retry POST
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))
adapter = session.get_adapter("https://api.example.com/items")
print(type(adapter).__name__, adapter.max_retries.total)လက်တွေ့ project တွေမှာ
Real project တွေမှာ ဘယ်လို သုံးလဲ
Third-party API ကို ခေါ်တဲ့ service တိုင်းမှာ Session တစ်ခုကို module တစ်ခုထဲ ဒါမှမဟုတ် client class တစ်ခုထဲ ဖန်တီးထားပြီး ပြန်သုံးလေ့ ရှိပါတယ်။ အဲဒီ Session မှာ User-Agent, Authorization header, retry ပါတဲ့ adapter နဲ့ timeout default ကို တစ်နေရာတည်းမှာ သတ်မှတ်ထားလို့ request ရေးတဲ့ နေရာတိုင်းက ဒီ policy ကို အလိုအလျောက် လိုက်နာပါတယ်။ Page ရာချီ ဆွဲတဲ့ sync job တွေမှာ connection ပြန်သုံးတာကြောင့် runtime သိသိသာသာ လျော့တာကို တွေ့ရလေ့ ရှိပါတယ်။
Response ကိုလည်း ယုံကြည်ပြီး တန်းသုံးလို့ မရပါဘူး။ Production code မှာ Content-Type က application/json ဟုတ်မဟုတ်၊ Content-Length က ကိုယ်လက်ခံနိုင်တဲ့ အရွယ်ထက် မကျော်ဘူးလားကို စစ်ပြီး file ကြီးတွေကို stream=True နဲ့ iter_content() သုံးကာ အပိုင်းလိုက် ဒေါင်းလုဒ်လုပ်ပါတယ်။ Test တွေမှာတော့ ဒီ lesson ထဲကလို fake adapter ဒါမှမဟုတ် responses လို library နဲ့ network ကို အစားထိုးလို့ test တွေ မြန်ပြီး တည်ငြိမ်ပါတယ်။
အမှားများ
အဖြစ်များတဲ့ အမှားတွေ
1. verify=False နဲ့ certificate error ကို ပိတ်တာ
Error ပျောက်သွားပေမယ့် server ကို အတည်ပြုတာ လုံးဝ ရပ်သွားလို့ token နဲ့ data တွေ ခိုးယူခံရနိုင်ပါတယ်။ Internal CA ဆိုရင် verify ကို CA bundle path ပေးပြီး system clock နဲ့ certificate သက်တမ်းကိုလည်း စစ်ပါ။
2. timeout=5 က စုစုပေါင်း ကန့်သတ်ချက်လို့ ထင်တာ
Read timeout က byte တွေကြား စောင့်ချိန်ပဲ ဖြစ်လို့ server က data ကို ဖြည်းဖြည်းချင်း ပို့နေရင် request တစ်ခုလုံးက ၅ စက္ကန့်ထက် အများကြီး ကြာနိုင်ပါတယ်။ စုစုပေါင်း deadline လိုရင် stream=True နဲ့ ကိုယ်တိုင် အချိန်တိုင်းပါ။
3. HTTPError ကိုပဲ ဖမ်းတာ
except HTTPError တစ်ခုတည်း ရေးထားရင် DNS error, connection refused, timeout တွေက ဖမ်းမမိဘဲ program crash ပါတယ်။ HTTPError ပြီးရင် RequestException ကို ထပ်ဖမ်းပါ၊ Exception အကျယ်ကြီးကိုတော့ မဖမ်းပါနဲ့ — ကိုယ့် code ထဲက bug တွေပါ ပျောက်သွားလို့ပါ။
4. POST ကို မစဉ်းစားဘဲ retry လုပ်တာ
Server က order ကို ဖန်တီးပြီးမှ response ပြန်လာတဲ့လမ်းမှာ timeout ဖြစ်ရင် POST ကို ပြန်ပို့တာနဲ့ order နှစ်ခု ဖြစ်သွားပါတယ်။ API က idempotency key ကို လက်ခံရင် သုံးပါ၊ မဟုတ်ရင် GET လို ဘေးကင်းတဲ့ method တွေကိုပဲ အလိုအလျောက် retry လုပ်ပါ။
Best Practices
အကောင်းဆုံး အလေ့အကျင့်များ
- API တစ်ခုစီအတွက် Session တစ်ခု ဖန်တီးပြီး base URL, header, timeout default တို့ကို client class တစ်ခုထဲ စုထားပါ။
- User-Agent header မှာ ကိုယ့် app နာမည်နဲ့ version ကို ထည့်ပါ၊ API provider ဘက်က ပြဿနာ ရှာရ လွယ်ပါတယ်။
- Retry ကို GET လို ဘေးကင်းတဲ့ method တွေနဲ့ 429, 5xx လို ယာယီ status တွေမှာပဲ ကန့်သတ်ပြီး backoff ထည့်ပါ။
- Test တွေမှာ တကယ့် network ကို မခေါ်ပါနဲ့၊ adapter ဒါမှမဟုတ် mock နဲ့ response ကို ထိန်းချုပ်ပါ။
Mini challenge
Mini challenge: ဘေးကင်းတဲ့ get_json()
Session နဲ့ URL ကို လက်ခံပြီး JSON data ဒါမှမဟုတ် ရှင်းလင်းတဲ့ error string ကို ပြန်ပေးတဲ့ get_json() ကို ရေးပါ။ Network မလိုအောင် ROUTES ထဲက response တွေကို ပြန်ပေးတဲ့ FakeTransport adapter ကိုလည်း ကိုယ်တိုင် ဖြည့်ရေးပါ။
- FakeTransport.send() က ROUTES ထဲက status, Content-Type, body နဲ့ requests.Response ကို ဆောက်ပြီး /slow ဆိုရင် ReadTimeout ကို raise လုပ်ရမယ်
- get_json() က timeout=(3.05, 10) နဲ့ ပို့ပြီး raise_for_status() ကို ခေါ်ရမယ်
- Timeout ဆို "error: timed out"၊ HTTPError ဆို "error: HTTP <code>" ပြန်ရမယ်
- Content-Type က application/json မဟုတ်ရင် .json() မခေါ်ဘဲ error string ပြန်ရမယ်
import requests
from requests.adapters import BaseAdapter
ROUTES = { # path -> (status, content type, body)
"/status": (200, "application/json", b'{"healthy": true}'),
"/login": (200, "text/html", b"<html>Please sign in</html>"),
"/report": (500, "application/json", b'{"error": "db down"}'),
}
class FakeTransport(BaseAdapter):
def send(self, request, **kwargs):
# TODO: for request.path_url == "/slow", raise requests.exceptions.ReadTimeout
# TODO: otherwise build a requests.Response from ROUTES and return it
...
def close(self):
pass
def get_json(session, url):
# TODO: GET with timeout=(3.05, 10), then raise_for_status()
# TODO: turn Timeout / HTTPError into "error: ..." strings
# TODO: refuse bodies whose Content-Type is not application/json
...
# TODO: mount FakeTransport on a Session and call get_json for
# /status, /login, /report and /slowရလဒ်: Path လေးခုအတွက် output: /status -> {'healthy': True} /login -> error: expected JSON, got text/html /report -> error: HTTP 500 /slow -> error: timed out
အရိပ်အမြွက် ကြည့်ရန်
Fake response အတွက် status_code, url, reason, headers["Content-Type"] နဲ့ _content (bytes) ကို သတ်မှတ်ရင် လုံလောက်ပါတယ်။ ReadTimeout က Timeout ရဲ့ subclass ဖြစ်လို့ except requests.exceptions.Timeout က ဖမ်းမိပါတယ်။
အဖြေ ကြည့်ရန်
import requests
from requests.adapters import BaseAdapter
ROUTES = { # path -> (status, content type, body)
"/status": (200, "application/json", b'{"healthy": true}'),
"/login": (200, "text/html", b"<html>Please sign in</html>"),
"/report": (500, "application/json", b'{"error": "db down"}'),
}
class FakeTransport(BaseAdapter):
def send(self, request, **kwargs):
path = request.path_url
if path == "/slow":
raise requests.exceptions.ReadTimeout("read timed out", request=request)
status, ctype, body = ROUTES[path]
resp = requests.Response()
resp.status_code, resp.url, resp._content = status, request.url, body
resp.reason = "OK" if status == 200 else "Internal Server Error"
resp.headers["Content-Type"] = ctype
return resp
def close(self):
pass
def get_json(session, url):
try:
response = session.get(url, timeout=(3.05, 10))
response.raise_for_status()
except requests.exceptions.Timeout:
return "error: timed out"
except requests.exceptions.HTTPError as e:
return f"error: HTTP {e.response.status_code}"
content_type = response.headers.get("Content-Type", "")
if not content_type.startswith("application/json"):
return f"error: expected JSON, got {content_type}"
return response.json()
session = requests.Session()
session.mount("https://api.example.com", FakeTransport())
for path in ["/status", "/login", "/report", "/slow"]:
print(path, "->", get_json(session, "https://api.example.com" + path))Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Request အများကြီး ပို့ရင် Session ကို သုံးပါ — header, cookie, connection တွေကို ပြန်သုံးပေးပါတယ်။
- params= နဲ့ query string ကို ဆောက်ပြီး request တိုင်းမှာ timeout (ဒါမှမဟုတ် (connect, read) tuple) ထည့်ပါ။
- HTTPError ကို အရင်ဖမ်းပြီး RequestException ကို နောက်ဆုံးမှာ ဖမ်းပါ၊ verify=False ကို ဘယ်တော့မှ မသုံးပါနဲ့။
- session.mount() နဲ့ adapter ကို လဲပြီး retry ထည့်တာ၊ network မပါဘဲ test လုပ်တာ လုပ်နိုင်ပါတယ်။
Requests — User Guide — Requests