Пример #1
0
 def _prepare_untrusted_asyncprawcore(self, requestor):
     authenticator = UntrustedAuthenticator(requestor,
                                            self.config.client_id,
                                            self.config.redirect_uri)
     read_only_authorizer = DeviceIDAuthorizer(authenticator)
     self._read_only_core = session(read_only_authorizer)
     if self.config.refresh_token:
         authorizer = Authorizer(authenticator, self.config.refresh_token)
         self._core = self._authorized_core = session(authorizer)
     else:
         self._core = self._read_only_core
Пример #2
0
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()
Пример #3
0
 def _prepare_untrusted_asyncprawcore(self, requestor):
     authenticator = UntrustedAuthenticator(requestor,
                                            self.config.client_id,
                                            self.config.redirect_uri)
     read_only_authorizer = DeviceIDAuthorizer(authenticator)
     self._read_only_core = session(read_only_authorizer)
     self._prepare_common_authorizer(authenticator)
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()
Пример #5
0
    def _prepare_common_authorizer(self, authenticator):
        if self._token_manager is not None:
            warn(
                "Token managers have been depreciated and will be removed in the near"
                " future. See https://www.reddit.com/r/redditdev/comments/olk5e6/"
                "followup_oauth2_api_changes_regarding_refresh/ for more details.",
                category=DeprecationWarning,
                stacklevel=2,
            )
            if self.config.refresh_token:
                raise TypeError(
                    "``refresh_token`` setting cannot be provided when providing"
                    " ``token_manager``")

            self._token_manager.reddit = self
            authorizer = Authorizer(
                authenticator,
                post_refresh_callback=self._token_manager.
                post_refresh_callback,
                pre_refresh_callback=self._token_manager.pre_refresh_callback,
            )
        elif self.config.refresh_token:
            authorizer = Authorizer(authenticator,
                                    refresh_token=self.config.refresh_token)
        else:
            self._core = self._read_only_core
            return
        self._core = self._authorized_core = session(authorizer)
Пример #6
0
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()
Пример #7
0
    def _prepare_trusted_asyncprawcore(self, requestor):
        authenticator = TrustedAuthenticator(
            requestor,
            self.config.client_id,
            self.config.client_secret,
            self.config.redirect_uri,
        )
        read_only_authorizer = ReadOnlyAuthorizer(authenticator)
        self._read_only_core = session(read_only_authorizer)

        if self.config.username and self.config.password:
            script_authorizer = ScriptAuthorizer(authenticator,
                                                 self.config.username,
                                                 self.config.password)
            self._core = self._authorized_core = session(script_authorizer)
        else:
            self._prepare_common_authorizer(authenticator)
Пример #8
0
    async def authorize(self, code: str) -> Optional[str]:
        """Complete the web authorization flow and return the refresh token.

        :param code: The code obtained through the request to the redirect uri.
        :returns: The obtained refresh token, if available, otherwise ``None``.

        The session's active authorization will be updated upon success.

        """
        authenticator = self._reddit._read_only_core._authorizer._authenticator
        authorizer = Authorizer(authenticator)
        await authorizer.authorize(code)
        authorized_session = session(authorizer)
        self._reddit._core = self._reddit._authorized_core = authorized_session
        return authorizer.refresh_token
Пример #9
0
    def _prepare_common_authorizer(self, authenticator):
        if self._token_manager is not None:
            if self.config._do_not_use_refresh_token != self.config.CONFIG_NOT_SET:
                raise TypeError(
                    "legacy ``refresh_token`` setting cannot be provided when providing"
                    " ``token_manager``")

            self._token_manager.reddit = self
            authorizer = Authorizer(
                authenticator,
                post_refresh_callback=self._token_manager.
                post_refresh_callback,
                pre_refresh_callback=self._token_manager.pre_refresh_callback,
            )
        elif self.config._do_not_use_refresh_token != self.config.CONFIG_NOT_SET:
            authorizer = Authorizer(
                authenticator,
                refresh_token=self.config._do_not_use_refresh_token)
        else:
            self._core = self._read_only_core
            return
        self._core = self._authorized_core = session(authorizer)
Пример #10
0
    def implicit(self, access_token: str, expires_in: int, scope: str) -> None:
        """Set the active authorization to be an implicit authorization.

        :param access_token: The access_token obtained from Reddit's callback.
        :param expires_in: The number of seconds the ``access_token`` is valid
            for. The origin of this value was returned from Reddit's callback.
            You may need to subtract an offset before passing in this number to
            account for a delay between when Reddit prepared the response, and
            when you make this function call.
        :param scope: A space-delimited string of Reddit OAuth2 scope names as
            returned from Reddit's callback.

        :raises: :class:`.InvalidImplicitAuth` if :class:`.Reddit` was
            initialized for a non-installed application type.

        """
        authenticator = self._reddit._read_only_core._authorizer._authenticator
        if not isinstance(authenticator, UntrustedAuthenticator):
            raise InvalidImplicitAuth
        implicit_session = session(
            ImplicitAuthorizer(authenticator, access_token, expires_in, scope))
        self._reddit._core = self._reddit._authorized_core = implicit_session
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
Пример #12
0
 async def test_session(self):
     session = asyncprawcore.session(InvalidAuthorizer())
     try:
         self.assertIsInstance(session, asyncprawcore.Session)
     finally:
         await session.close()