Fix Black target-version and format code

- Remove py312 from Black target-version (unsupported)
- Format mdclient/auth.py and mdclient/client.py with Black
- Update code style: double quotes for strings

Co-Authored-By: Claude Sonnet 4 <noreply@anthropic.com>
This commit is contained in:
2026-03-17 14:40:34 +08:00
parent 38b4bc5377
commit 1f8b7858c3
3 changed files with 46 additions and 53 deletions

View File

@@ -33,7 +33,7 @@ class MDAuth:
Returns: Returns:
儲存的 Cookie 字典 儲存的 Cookie 字典
""" """
with open(self.cookie_file, 'w', encoding='utf-8') as f: with open(self.cookie_file, "w", encoding="utf-8") as f:
json.dump(cookies, f, indent=2) json.dump(cookies, f, indent=2)
print(f"✓ Cookie 已儲存到: {self.cookie_file}") print(f"✓ Cookie 已儲存到: {self.cookie_file}")
@@ -49,7 +49,7 @@ class MDAuth:
if not self.cookie_file.exists(): if not self.cookie_file.exists():
return None return None
with open(self.cookie_file, 'r', encoding='utf-8') as f: with open(self.cookie_file, "r", encoding="utf-8") as f:
return json.load(f) return json.load(f)
def login(self, email: str, password: str) -> bool: def login(self, email: str, password: str) -> bool:
@@ -75,19 +75,19 @@ class MDAuth:
print("2. 傳送登入請求...") print("2. 傳送登入請求...")
login_data = { login_data = {
'email': email, "email": email,
'password': password, "password": password,
} }
headers = { headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36', "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
'Content-Type': 'application/x-www-form-urlencoded', "Content-Type": "application/x-www-form-urlencoded",
'Origin': self.base_url, "Origin": self.base_url,
'Referer': self.login_url, "Referer": self.login_url,
} }
# 嘗試不同的登入端點 # 嘗試不同的登入端點
login_endpoints = ['/login', '/auth/login', '/api/login', '/signin'] login_endpoints = ["/login", "/auth/login", "/api/login", "/signin"]
for endpoint in login_endpoints: for endpoint in login_endpoints:
try: try:
@@ -99,7 +99,7 @@ class MDAuth:
data=login_data, data=login_data,
headers=headers, headers=headers,
allow_redirects=True, allow_redirects=True,
timeout=10 timeout=10,
) )
print(f" 狀態碼: {response.status_code}") print(f" 狀態碼: {response.status_code}")
@@ -119,7 +119,7 @@ class MDAuth:
# 顯示主要 cookie 資訊 # 顯示主要 cookie 資訊
for name, value in cookie_dict.items(): for name, value in cookie_dict.items():
if 'sid' in name.lower() or 'session' in name.lower(): if "sid" in name.lower() or "session" in name.lower():
print(f"{name}: {value[:20]}...") print(f"{name}: {value[:20]}...")
return True return True
@@ -150,15 +150,12 @@ class MDAuth:
print(f"{self.cookie_file} 載入 Cookie...") print(f"{self.cookie_file} 載入 Cookie...")
headers = { headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36', "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
} }
try: try:
response = requests.get( response = requests.get(
f"{self.base_url}/", f"{self.base_url}/", cookies=cookies, headers=headers, timeout=10
cookies=cookies,
headers=headers,
timeout=10
) )
print(f"測試請求狀態碼: {response.status_code}") print(f"測試請求狀態碼: {response.status_code}")
return response.status_code == 200 return response.status_code == 200

View File

@@ -16,7 +16,7 @@ class MDClient:
base_url: str = "https://codimd.lotimmy.com", base_url: str = "https://codimd.lotimmy.com",
cookie_file: str = "key.conf", cookie_file: str = "key.conf",
email: Optional[str] = None, email: Optional[str] = None,
password: Optional[str] = None password: Optional[str] = None,
): ):
""" """
初始化客戶端 初始化客戶端
@@ -37,15 +37,11 @@ class MDClient:
if not self.cookie_file.exists(): if not self.cookie_file.exists():
return None return None
with open(self.cookie_file, 'r', encoding='utf-8') as f: with open(self.cookie_file, "r", encoding="utf-8") as f:
return json.load(f) return json.load(f)
def _request( def _request(
self, self, method: str, endpoint: str, data: Optional[Dict] = None, params: Optional[Dict] = None
method: str,
endpoint: str,
data: Optional[Dict] = None,
params: Optional[Dict] = None
) -> Optional[requests.Response]: ) -> Optional[requests.Response]:
""" """
傳送帶 Cookie 的請求 傳送帶 Cookie 的請求
@@ -67,18 +63,22 @@ class MDClient:
return None return None
headers = { headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36', "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
} }
url = f"{self.base_url}{endpoint}" url = f"{self.base_url}{endpoint}"
try: try:
if method == 'GET': if method == "GET":
response = requests.get(url, cookies=cookies, headers=headers, params=params, timeout=10) response = requests.get(
elif method == 'POST': url, cookies=cookies, headers=headers, params=params, timeout=10
headers['Content-Type'] = 'application/json' )
response = requests.post(url, cookies=cookies, headers=headers, json=data, timeout=10) elif method == "POST":
elif method == 'DELETE': headers["Content-Type"] = "application/json"
response = requests.post(
url, cookies=cookies, headers=headers, json=data, timeout=10
)
elif method == "DELETE":
response = requests.delete(url, cookies=cookies, headers=headers, timeout=10) response = requests.delete(url, cookies=cookies, headers=headers, timeout=10)
else: else:
raise ValueError(f"不支援的 HTTP 方法: {method}") raise ValueError(f"不支援的 HTTP 方法: {method}")
@@ -97,10 +97,10 @@ class MDClient:
""" """
print("正在取得使用者資訊...") print("正在取得使用者資訊...")
endpoints = ['/api/me', '/me', '/api/user/me'] endpoints = ["/api/me", "/me", "/api/user/me"]
for endpoint in endpoints: for endpoint in endpoints:
response = self._request('GET', endpoint) response = self._request("GET", endpoint)
if response and response.status_code == 200: if response and response.status_code == 200:
try: try:
data = response.json() data = response.json()
@@ -121,10 +121,10 @@ class MDClient:
""" """
print("正在取得筆記列表...") print("正在取得筆記列表...")
endpoints = ['/api/me/notes', '/api/notes', '/history', '/me/notes'] endpoints = ["/api/me/notes", "/api/notes", "/history", "/me/notes"]
for endpoint in endpoints: for endpoint in endpoints:
response = self._request('GET', endpoint) response = self._request("GET", endpoint)
if response and response.status_code == 200: if response and response.status_code == 200:
try: try:
data = response.json() data = response.json()
@@ -133,10 +133,10 @@ class MDClient:
# 處理不同的回應格式 # 處理不同的回應格式
if isinstance(data, list): if isinstance(data, list):
return data return data
elif isinstance(data, dict) and 'history' in data: elif isinstance(data, dict) and "history" in data:
return data['history'] return data["history"]
elif isinstance(data, dict) and 'notes' in data: elif isinstance(data, dict) and "notes" in data:
return data['notes'] return data["notes"]
return data return data
except json.JSONDecodeError: except json.JSONDecodeError:
@@ -166,12 +166,12 @@ class MDClient:
] ]
for endpoint in endpoints: for endpoint in endpoints:
response = self._request('GET', endpoint) response = self._request("GET", endpoint)
if response and response.status_code == 200: if response and response.status_code == 200:
try: try:
# 如果是直接訪問筆記頁面,可能需要解析 HTML # 如果是直接訪問筆記頁面,可能需要解析 HTML
content_type = response.headers.get('content-type', '') content_type = response.headers.get("content-type", "")
if 'text/html' in content_type: if "text/html" in content_type:
# 這是 HTML 頁面,不是 API 回應 # 這是 HTML 頁面,不是 API 回應
continue continue
@@ -182,11 +182,7 @@ class MDClient:
# 如果不是 JSON可能是純文字內容 # 如果不是 JSON可能是純文字內容
if response.text: if response.text:
print(f"✓ 取得筆記內容 (端點: {endpoint})") print(f"✓ 取得筆記內容 (端點: {endpoint})")
return { return {"id": note_id, "content": response.text, "title": note_id}
'id': note_id,
'content': response.text,
'title': note_id
}
print("✗ 無法取得筆記內容") print("✗ 無法取得筆記內容")
return None return None
@@ -205,11 +201,11 @@ class MDClient:
print(f"正在建立筆記: {title}") print(f"正在建立筆記: {title}")
data = { data = {
'title': title, "title": title,
'content': content, "content": content,
} }
response = self._request('POST', '/api/notes', data=data) response = self._request("POST", "/api/notes", data=data)
if response and response.status_code in [200, 201]: if response and response.status_code in [200, 201]:
try: try:
@@ -235,7 +231,7 @@ class MDClient:
是否刪除成功 是否刪除成功
""" """
print(f"正在刪除筆記: {note_id}") print(f"正在刪除筆記: {note_id}")
response = self._request('DELETE', f"/api/notes/{note_id}") response = self._request("DELETE", f"/api/notes/{note_id}")
if response and response.status_code in [200, 204]: if response and response.status_code in [200, 204]:
print("✓ 筆記刪除成功") print("✓ 筆記刪除成功")
@@ -265,7 +261,7 @@ class MDClient:
] ]
for endpoint in endpoints: for endpoint in endpoints:
response = self._request('GET', endpoint) response = self._request("GET", endpoint)
if response and response.status_code == 200: if response and response.status_code == 200:
print("✓ 筆記匯出成功") print("✓ 筆記匯出成功")
return response.text return response.text
@@ -285,7 +281,7 @@ class MDClient:
""" """
print(f"正在搜尋筆記: {query}") print(f"正在搜尋筆記: {query}")
response = self._request('GET', '/api/search', params={'q': query}) response = self._request("GET", "/api/search", params={"q": query})
if response and response.status_code == 200: if response and response.status_code == 200:
try: try:

View File

@@ -50,7 +50,7 @@ include = ["mdclient*"]
[tool.black] [tool.black]
line-length = 100 line-length = 100
target-version = ["py38", "py39", "py310", "py311", "py312"] target-version = ["py38", "py39", "py310", "py311"]
[tool.mypy] [tool.mypy]
python_version = "3.8" python_version = "3.8"