更新 login.py

This commit is contained in:
chickliu 2025-02-14 11:57:10 +08:00
parent 5a7bcc49f2
commit e88109e61c

View File

@ -3,6 +3,23 @@ from PIL import Image
from io import BytesIO
import base64
import time
import os
# 新增函数从api.txt获取服务器地址
def get_api_base_url():
try:
with open("api.txt", "r") as f:
# 读取第一行有效内容(忽略空行和空白)
lines = [line.strip() for line in f.readlines() if line.strip()]
if lines:
return lines[0].rstrip('/') # 移除末尾的斜杠
except FileNotFoundError:
print("api.txt文件未找到使用默认地址")
except Exception as e:
print(f"读取api.txt失败: {e},使用默认地址")
# 默认地址
return "http://localhost:3000"
# 获取当前时间戳
def get_current_timestamp():
@ -10,7 +27,8 @@ def get_current_timestamp():
# 获取unikey
def get_unikey():
url = f"http://localhost:3000/login/qr/key?time={get_current_timestamp()}"
base_url = get_api_base_url()
url = f"{base_url}/login/qr/key?time={get_current_timestamp()}"
response = requests.get(url)
data = response.json()
if data['code'] == 200:
@ -19,7 +37,8 @@ def get_unikey():
# 创建二维码
def create_qr(unikey):
url = f"http://localhost:3000/login/qr/create?key={unikey}&qrimg=1&time={get_current_timestamp()}"
base_url = get_api_base_url()
url = f"{base_url}/login/qr/create?key={unikey}&qrimg=1&time={get_current_timestamp()}"
response = requests.get(url)
data = response.json()
if data['code'] == 200:
@ -35,12 +54,12 @@ def display_qr_image(qrimg_base64):
# 监控扫码状态
def check_scan_status(unikey):
url = f"http://localhost:3000/login/qr/check?key={unikey}&time={get_current_timestamp()}"
base_url = get_api_base_url()
url = f"{base_url}/login/qr/check?key={unikey}&time={get_current_timestamp()}"
response = requests.get(url)
#print(f"响应内容: {response.text}") # 打印每次请求的响应内容
return response.json()
# 登录函数
# 登录函数(保持原有实现不变)
def login():
unikey = get_unikey()
if not unikey:
@ -52,30 +71,29 @@ def login():
print("无法创建二维码")
return None
# 显示二维码图像
display_qr_image(qrimg_base64)
print("请扫描二维码,等待扫码成功...")
# 监控扫码状态
while True:
status = check_scan_status(unikey)
if status['code'] == 803:
print("授权登录成功")
cookie = status['cookie']
print(f"保存的 Cookie: {cookie}")
# 保存 cookie 到文件
with open("cookies.txt", "w") as f:
f.write(cookie)
return cookie # 返回 cookie
return cookie
elif status['code'] == 801:
print("等待扫码,继续请求中...")
elif status['code'] == 802:
print("授权中,继续请求中...")
else:
print(f"扫码失败: {status['message']}")
return None # 返回 None表示扫码失败
return None
time.sleep(2) # 每隔2秒检查一次扫码状态
time.sleep(2)
# 使用示例
if __name__ == "__main__":
login()