From f224c16f40f9a2b1393f0951cfba7a05c73a9935 Mon Sep 17 00:00:00 2001 From: sudosnok Date: Sat, 26 Mar 2022 18:15:24 +0000 Subject: [PATCH] Added the basics for the session handling --- Github/http.py | 47 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/Github/http.py b/Github/http.py index fafe578..f39f1a1 100644 --- a/Github/http.py +++ b/Github/http.py @@ -1,5 +1,50 @@ #== http.py ==# import aiohttp -import asyncio +from types import SimpleNamespace + +from .exceptions import * +from .urls import * + +# aiohttp request tracking / checking bits +async def on_req_start( + session: aiohttp.ClientSession, + ctx: SimpleNamespace, + params: aiohttp.TraceRequestStartParams +) -> None: + """Before-request hook to make sure we don't overrun the ratelimit.""" + print(repr(session), repr(ctx), repr(params)) + +async def on_req_end( + session: aiohttp.ClientSession, + ctx: SimpleNamespace, + params: aiohttp.TraceRequestEndParams +) -> None: + """After-request hook to adjust remaining requests on this time frame.""" + print(repr(session), repr(ctx), repr(params)) + +trace_config = aiohttp.TraceConfig() +trace_config.on_request_start.append(on_req_start) +trace_config.on_request_end.append(on_req_end) + +async def make_session(*, headers: dict[str, str]) -> aiohttp.ClientSession: + """This makes the ClientSession, attaching the trace config and ensuring a UA header is present.""" + if not headers.get('User-Agent'): + headers['User-Agent'] = 'Github-API-Wrapper' + + session = aiohttp.ClientSession( + headers=headers, + trace_configs=[trace_config] + ) + return session + +# user-related functions / utils +GitHubUserData = dict[str, str|int] + +async def get_user(session: aiohttp.ClientSession, *, _username: str) -> GitHubUserData: + """Returns a user's public data in JSON format.""" + result = await session.get(USERS_URL.format(_username)) + if result.status == 200: + return await result.json() + raise UserNotFound()