import asyncio
import functools
import sys
from typing import Optional
from playwright.async_api import BrowserContext, Page
from tenacity import (RetryError, retry, retry_if_result, stop_after_attempt,
wait_fixed)
asyncio用于异步编程,functools用于高阶函数操作,sys用于与Python解释器交互,typing用于类型提示,以及playwright.async_api和tenacity中的一些类和函数。
根据代码中的内容,它可能涉及到异步操作、函数重试、以及与浏览器的交互。这些模块和函数可能会在实现一个具有重试机制的异步操作过程中发挥作用。
class BilibiliLogin(AbstractLogin):
def __init__(self,
login_type: str,
browser_context: BrowserContext,
context_page: Page,
login_phone: Optional[str] = "",
cookie_str: str = ""
):
self.login_type = login_type
self.browser_context = browser_context
self.context_page = context_page
self.login_phone = login_phone
self.cookie_str = cookie_str
这段代码定义了一个名为BilibiliLogin的类,它似乎是继承自之前提到的AbstractLogin抽象基类。在这个类的构造函数中,它接受了几个参数,包括login_type、browser_context、context_page、login_phone和cookie_str,并将它们保存为实例变量。根据参数名和类型,它可能是用于实现Bilibili网站的登录功能,其中login_type表示登录类型,browser_context和context_page可能是与浏览器操作相关的对象,login_phone是登录手机号,cookie_str是用于登录的cookie字符串。
async def begin(self):
"""Start login xiaohongshu"""
utils.logger.info("Begin login Bilibili ...")
if self.login_type == "qrcode":
await self.login_by_qrcode()
elif self.login_type == "phone":
await self.login_by_mobile()
elif self.login_type == "cookie":
await self.login_by_cookies()
else:
raise ValueError("Invalid Login Type Currently only supported qrcode or phone or cookie ...")
这段代码定义了一个名为begin的异步方法,它似乎是用于开始进行Bilibili网站的登录操作。在方法中,首先记录了一条日志,然后根据登录类型的不同,调用了相应的登录方法:如果登录类型是"qrcode",则调用login_by_qrcode方法;如果登录类型是"phone",则调用login_by_mobile方法;如果登录类型是"cookie",则调用login_by_cookies方法。如果登录类型不是这三种之一,则会抛出一个值错误。这种设计方式可以根据不同的登录类型执行不同的登录流程。
@retry(stop=stop_after_attempt(20), wait=wait_fixed(1), retry=retry_if_result(lambda value: value is False))
async def check_login_state(self) -> bool:
"""
Check if the current login status is successful and return True otherwise return False
retry decorator will retry 20 times if the return value is False, and the retry interval is 1 second
if max retry times reached, raise RetryError
"""