use external pleroma.py
This commit is contained in:
parent
82320560a1
commit
03305c4a55
4 changed files with 18 additions and 210 deletions
46
utils.py
46
utils.py
|
|
@ -1,10 +1,10 @@
|
|||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
import sys
|
||||
import anyio
|
||||
import aiohttp
|
||||
import contextlib
|
||||
from functools import wraps
|
||||
from datetime import datetime, timezone
|
||||
from dateutil.parser import parse as parsedate
|
||||
|
||||
def as_corofunc(f):
|
||||
@wraps(f)
|
||||
|
|
@ -36,34 +36,14 @@ def removeprefix(s, prefix):
|
|||
# compatibility for pre-3.9
|
||||
return s[len(prefix):] if s.startswith(prefix) else s
|
||||
|
||||
async def sleep_until(dt):
|
||||
await anyio.sleep((dt - datetime.now(timezone.utc)).total_seconds())
|
||||
|
||||
class HandleRateLimits:
|
||||
def __init__(self, http):
|
||||
self.http = http
|
||||
|
||||
def request(self, *args, **kwargs):
|
||||
return _RateLimitContextManager(self.http, args, kwargs)
|
||||
|
||||
class _RateLimitContextManager(contextlib.AbstractAsyncContextManager):
|
||||
def __init__(self, http, args, kwargs):
|
||||
self.http = http
|
||||
self.args = args
|
||||
self.kwargs = kwargs
|
||||
|
||||
async def __aenter__(self):
|
||||
self._request_cm = self.http.request(*self.args, **self.kwargs)
|
||||
return await self._do_enter()
|
||||
|
||||
async def _do_enter(self):
|
||||
resp = await self._request_cm.__aenter__()
|
||||
if resp.headers.get('X-RateLimit-Remaining') not in {'0', '1'}:
|
||||
return resp
|
||||
|
||||
await sleep_until(parsedate(resp.headers['X-RateLimit-Reset']))
|
||||
await self._request_cm.__aexit__(*(None,)*3)
|
||||
return await self.__aenter__()
|
||||
|
||||
async def __aexit__(self, *excinfo):
|
||||
return await self._request_cm.__aexit__(*excinfo)
|
||||
def http_session_factory(headers={}, **kwargs):
|
||||
py_version = '.'.join(map(str, sys.version_info))
|
||||
user_agent = (
|
||||
'pleroma-ebooks (https://github.com/ioistired/pleroma-ebooks); '
|
||||
f'aiohttp/{aiohttp.__version__}; '
|
||||
f'python/{py_version}'
|
||||
)
|
||||
return aiohttp.ClientSession(
|
||||
headers={'User-Agent': user_agent, **headers},
|
||||
**kwargs,
|
||||
)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue