以下保留檔案原文,沒有改寫資料或結果。可使用「複製原始內容」取得完整檔案。
"""Only HTTP I/O and read-only observations; no expected values or pass/fail."""
import json
import sqlite3
from urllib.error import HTTPError
from urllib.request import Request, urlopen
class PaymentAdapter:
def __init__(self, base_url, database):
self.base_url = base_url
self.database = database
def pay(self, payload):
request = Request(
self.base_url + "/payments", data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"}, method="POST",
)
try:
response = urlopen(request, timeout=5)
except HTTPError as error:
response = error
with response:
return response.status, json.loads(response.read())
def observe(self, order_id):
with sqlite3.connect(self.database.as_uri() + "?mode=ro", uri=True) as connection:
row = connection.execute("SELECT status FROM orders WHERE id = ?", (order_id,)).fetchone()
count = connection.execute(
"SELECT COUNT(*) FROM payments WHERE order_id = ?", (order_id,)
).fetchone()[0]
return {"status": row[0] if row else None, "payments": count}