初步实现携带cookie请求

This commit is contained in:
suyiiyii 2024-09-02 23:13:29 +08:00
parent 1cd778c2e0
commit 7901b845ea
2 changed files with 45 additions and 1 deletions

View File

@ -9,6 +9,7 @@ from bs4 import BeautifulSoup as bs
from ..post import Post from ..post import Post
from .platform import NewMessage from .platform import NewMessage
from ..types import Target, RawPost from ..types import Target, RawPost
from ..utils.site import create_cookie_client_manager
from ..utils import Site, text_fletten, text_similarity from ..utils import Site, text_fletten, text_similarity
@ -16,6 +17,7 @@ class RssSite(Site):
name = "rss" name = "rss"
schedule_type = "interval" schedule_type = "interval"
schedule_setting = {"seconds": 30} schedule_setting = {"seconds": 30}
client_mgr = create_cookie_client_manager("rss")
class RssPost(Post): class RssPost(Post):
@ -63,7 +65,7 @@ class Rss(NewMessage):
return post.id return post.id
async def get_sub_list(self, target: Target) -> list[RawPost]: async def get_sub_list(self, target: Target) -> list[RawPost]:
client = await self.ctx.get_client() client = await self.ctx.get_client(target)
res = await client.get(target, timeout=10.0) res = await client.get(target, timeout=10.0)
feed = feedparser.parse(res) feed = feedparser.parse(res)
entries = feed.entries entries = feed.entries

View File

@ -1,9 +1,12 @@
import json
from typing import Literal from typing import Literal
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
import httpx
from httpx import AsyncClient from httpx import AsyncClient
from ..types import Target from ..types import Target
from ..config import config
from .http import http_client from .http import http_client
@ -35,6 +38,45 @@ class DefaultClientManager(ClientManager):
pass pass
class CookieClientManager(ClientManager):
_platform_name: str
async def _choose_cookie(self, target: Target) -> dict[str, str]:
if not target:
return {}
cookies = await config.get_cookie_by_target(target, self._platform_name)
if not cookies:
return {}
cookie = sorted(cookies, key=lambda x: x.last_usage, reverse=True)[0]
return json.loads(cookie.content)
async def get_client(self, target: Target | None) -> AsyncClient:
client = http_client()
cookie = await self._choose_cookie(target)
cookies = httpx.Cookies()
if cookie:
cookies.update(cookie)
client.cookies = cookies
return client
async def get_client_for_static(self) -> AsyncClient:
pass
async def get_query_name_client(self) -> AsyncClient:
pass
async def refresh_client(self):
pass
def create_cookie_client_manager(platform_name: str) -> type[CookieClientManager]:
return type(
"CookieClientManager",
(CookieClientManager,),
{"_platform_name": platform_name},
)
class Site: class Site:
schedule_type: Literal["date", "interval", "cron"] schedule_type: Literal["date", "interval", "cron"]
schedule_setting: dict schedule_setting: dict