From cc15cb585735411a03b23a2319a24a0870eedfae Mon Sep 17 00:00:00 2001 From: Alexander Graf Date: Thu, 30 Aug 2018 13:51:55 +0200 Subject: [PATCH] Cache and reuse profiles for Profile.from_id() --- instaloader/instaloadercontext.py | 3 +++ instaloader/structures.py | 6 +++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/instaloader/instaloadercontext.py b/instaloader/instaloadercontext.py index d17ce43..9571a20 100644 --- a/instaloader/instaloadercontext.py +++ b/instaloader/instaloadercontext.py @@ -69,6 +69,9 @@ class InstaloaderContext: # Can be set to True for testing, disables supression of InstaloaderContext._error_catcher self.raise_all_errors = False + # Cache profile from id (mapping from id to Profile) + self.profile_id_cache = dict() + @contextmanager def anonymous_copy(self): session = self._session diff --git a/instaloader/structures.py b/instaloader/structures.py index 2c66899..5c8a6f2 100644 --- a/instaloader/structures.py +++ b/instaloader/structures.py @@ -402,6 +402,8 @@ class Profile: :param profile_id: userid :raises: :class:`ProfileNotExistsException`, :class:`ProfileHasNoPicsException` """ + if profile_id in context.profile_id_cache: + return context.profile_id_cache[profile_id] data = context.graphql_query("472f257a40c653c64c666ce877d59d2b", {'id': str(profile_id), 'first': 1}, rhx_gis=context.root_rhx_gis)['data']['user'] @@ -415,7 +417,9 @@ class Profile: raise ProfileHasNoPicsException("Profile with ID {0}: no pics found.".format(str(profile_id))) else: raise LoginRequiredException("Login required to determine username (ID: " + str(profile_id) + ").") - return Post(context, data['edges'][0]['node']).owner_profile + profile = Post(context, data['edges'][0]['node']).owner_profile + context.profile_id_cache[profile_id] = profile + return profile def _asdict(self): json_node = self._node.copy()