-
Notifications
You must be signed in to change notification settings - Fork 429
Expand file tree
/
Copy pathcookies.py
More file actions
44 lines (35 loc) · 1.14 KB
/
Copy pathcookies.py
File metadata and controls
44 lines (35 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# -*- coding: utf-8 -*-
import os.path
import threading
import requests
from api.config import GlobalConst as gc
# 定义全局 Cookie 文件锁,保证读写绝对安全
cookie_lock = threading.RLock()
def save_cookies(session: requests.Session):
with cookie_lock:
buffer = ""
for k, v in session.cookies.items():
buffer += f"{k}={v};"
buffer = buffer.removesuffix(";")
with open(gc.COOKIES_PATH, "w") as f:
f.write(buffer)
def use_cookies() -> dict:
with cookie_lock:
if not os.path.exists(gc.COOKIES_PATH):
return {}
cookies = {}
try:
with open(gc.COOKIES_PATH, "r") as f:
buffer = f.read().strip()
if not buffer:
return {}
for item in buffer.split(";"):
item = item.strip()
if not item:
continue
parts = item.split("=", 1)
if len(parts) == 2:
cookies[parts[0]] = parts[1]
except Exception:
return {}
return cookies