async def main(): """Provide the program's entry point when directly executed.""" requestor = asyncprawcore.Requestor("asyncprawcore_script_auth_example") try: authenticator = asyncprawcore.TrustedAuthenticator( requestor, os.environ["asyncprawcore_CLIENT_ID"], os.environ["asyncprawcore_CLIENT_SECRET"], ) authorizer = asyncprawcore.ScriptAuthorizer( authenticator, os.environ["asyncprawcore_USERNAME"], os.environ["asyncprawcore_PASSWORD"], ) await authorizer.refresh() async with asyncprawcore.session(authorizer) as session: data = await session.request("GET", "/api/v1/me/friends") for friend in data["data"]["children"]: print(friend["name"]) return 0 finally: await requestor.close()
async def main(): """Provide the program's entry point when directly executed.""" if len(sys.argv) != 2: print(f"Usage: {sys.argv[0]} USERNAME") return 1 requestor = asyncprawcore.Requestor("asyncprawcore_read_only_example") try: authenticator = asyncprawcore.TrustedAuthenticator( requestor, os.environ["asyncprawcore_CLIENT_ID"], os.environ["asyncprawcore_CLIENT_SECRET"], ) authorizer = asyncprawcore.ReadOnlyAuthorizer(authenticator) await authorizer.refresh() user = sys.argv[1] async with asyncprawcore.session(authorizer) as session: data = await session.request("GET", f"/api/v1/user/{user}/trophies") for trophy in data["data"]["trophies"]: description = trophy["data"]["description"] print( f"{trophy['data']['name']}{(f' ({description})' if description else '')}" ) return 0 finally: await requestor.close()
async def test_request__use_custom_session(self): override = "REQUEST OVERRIDDEN" custom_header = "CUSTOM SESSION HEADER" headers = {"session_header": custom_header} return_of_request = asyncio.Future() return_of_request.set_result(override) attrs = { "request.return_value": return_of_request, "_default_headers": headers, } session = Mock(**attrs) self.requestor = asyncprawcore.Requestor( "asyncprawcore:test (by /u/Lil_SpazJoekp)", session=session ) self.assertEqual( f"asyncprawcore:test (by /u/Lil_SpazJoekp) asyncprawcore/{asyncprawcore.__version__}", self.requestor._http._default_headers["User-Agent"], ) self.assertEqual( self.requestor._http._default_headers["session_header"], custom_header, ) self.assertEqual(await self.requestor.request("https://reddit.com"), override)
async def test_initialize(self): self.requestor = asyncprawcore.Requestor( "asyncprawcore:test (by /u/Lil_SpazJoekp)" ) self.assertEqual( f"asyncprawcore:test (by /u/Lil_SpazJoekp) asyncprawcore/{asyncprawcore.__version__}", self.requestor._http._default_headers["User-Agent"], )
async def test_request__wrap_request_exceptions(self, mock_session): exception = Exception("asyncprawcore wrap_request_exceptions") session_instance = mock_session.return_value session_instance.request.side_effect = exception self.requestor = asyncprawcore.Requestor( "asyncprawcore:test (by /u/Lil_SpazJoekp)" ) with self.assertRaises(asyncprawcore.RequestException) as context_manager: await self.requestor.request("get", "http://a.b", data="bar") self.assertIsInstance(context_manager.exception, RequestException) self.assertIs(exception, context_manager.exception.original_exception) self.assertEqual(("get", "http://a.b"), context_manager.exception.request_args) self.assertEqual({"data": "bar"}, context_manager.exception.request_kwargs)
async def main(): """Provide the program's entry point when directly executed.""" if len(sys.argv) != 2: print(f"Usage: {sys.argv[0]} USERNAME") return 1 caching_requestor = asyncprawcore.Requestor( "asyncprawcore_device_id_auth_example", session=CachingSession()) try: authenticator = asyncprawcore.TrustedAuthenticator( caching_requestor, os.environ["asyncprawcore_CLIENT_ID"], os.environ["asyncprawcore_CLIENT_SECRET"], ) authorizer = asyncprawcore.ReadOnlyAuthorizer(authenticator) await authorizer.refresh() user = sys.argv[1] async with asyncprawcore.session(authorizer) as session: data1 = await session.request("GET", f"/api/v1/user/{user}/trophies") async with asyncprawcore.session(authorizer) as session: data2 = await session.request("GET", f"/api/v1/user/{user}/trophies") for trophy in data1["data"]["trophies"]: description = trophy["data"]["description"] print( "Original:", trophy["data"]["name"] + (f" ({description})" if description else ""), ) for trophy in data2["data"]["trophies"]: description = trophy["data"]["description"] print( "Cached:", trophy["data"]["name"] + (f" ({description})" if description else ""), ) print( "----\nCached == Original:", data2["data"]["trophies"] == data2["data"]["trophies"], ) finally: await caching_requestor.close()
async def main(): """Provide the program's entry point when directly executed.""" if len(sys.argv) < 2: print(f"Usage: {sys.argv[0]} SCOPE...") return 1 requestor = asyncprawcore.Requestor("asyncprawcore_refresh_token_example") try: authenticator = asyncprawcore.TrustedAuthenticator( requestor, os.environ["ASYNCPRAWCORE_CLIENT_ID"], os.environ["ASYNCPRAWCORE_CLIENT_SECRET"], os.environ["ASYNCPRAWCORE_REDIRECT_URI"], ) state = str(random.randint(0, 65000)) url = authenticator.authorize_url("permanent", sys.argv[1:], state) print(url) client = receive_connection() data = client.recv(1024).decode("utf-8") param_tokens = data.split(" ", 2)[1].split("?", 1)[1].split("&") params = { key: value for (key, value) in [token.split("=") for token in param_tokens] } if state != params["state"]: send_message( client, f"State mismatch. Expected: {state} Received: {params['state']}", ) return 1 elif "error" in params: send_message(client, params["error"]) return 1 authorizer = asyncprawcore.Authorizer(authenticator) await authorizer.authorize(params["code"]) send_message(client, f"Refresh token: {authorizer.refresh_token}") return 0 finally: await requestor.close()
async def test_request__too__many_requests__without_retry_headers(self): with VCR.use_cassette( "Session_request__too__many_requests__without_retry_headers"): requestor = asyncprawcore.Requestor("python-requests/2.25.1") with self.assertRaises(asyncprawcore.exceptions.ResponseException ) as context_manager: asyncprawcore.Session(await readonly_authorizer(requestor=requestor)) self.assertEqual(429, context_manager.exception.response.status) self.assertFalse( context_manager.exception.response.headers.get("retry-after")) self.assertEqual("Too Many Requests", context_manager.exception.response.reason) self.assertEqual( await context_manager.exception.response.json(), { "message": "Too Many Requests", "error": 429 }, )
async def main(): """Provide the program's entry point when directly executed.""" if len(sys.argv) != 2: print(f"Usage: {sys.argv[0]} USERNAME") return 1 authenticator = asyncprawcore.UntrustedAuthenticator( asyncprawcore.Requestor("asyncprawcore_device_id_auth_example"), os.environ["asyncprawcore_CLIENT_ID"], ) authorizer = asyncprawcore.DeviceIDAuthorizer(authenticator) await authorizer.refresh() user = sys.argv[1] async with asyncprawcore.session(authorizer) as session: data = await session.request("GET", f"/api/v1/user/{user}/trophies") for trophy in data["data"]["trophies"]: description = trophy["data"]["description"] print(trophy["data"]["name"] + (f" ({description})" if description else "")) return 0
def test_initialize__failures(self): for agent in [None, "shorty"]: with self.assertRaises(asyncprawcore.InvalidInvocation): self.requestor = asyncprawcore.Requestor(agent)