Use cached_property decorator (#1065)

* Use @cached_property in PlexSession.user

* Use @cached_property in PlexServer.library

* Use @cached_property in PlexServer.settings

* Tests: Update clearing plex.settings cache

* Use @cached_property in LibrarySection.totalSize

* Add backports.cached-property==1.0.2; python_version<="3.7" dependency

* Import cached_property from dist or backports

* Add backports.cached-property to requirements_dev.txt

* Remove version pin for backports.cached-property in requirements.txt

Co-authored-by: JonnyWong16 <9099342+JonnyWong16@users.noreply.github.com>

Co-authored-by: JonnyWong16 <9099342+JonnyWong16@users.noreply.github.com>
This commit is contained in:
Elan Ruusamäe 2022-12-21 21:51:45 +02:00 committed by GitHub
parent ac41fbf4fb
commit 7580fc84a9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 31 additions and 36 deletions

View file

@ -6,6 +6,7 @@ from xml.etree import ElementTree
from plexapi import log, utils
from plexapi.exceptions import BadRequest, NotFound, UnknownType, Unsupported
from plexapi.utils import cached_property
USER_DONT_RELOAD_FOR_KEYS = set()
_DONT_RELOAD_FOR_KEYS = {'key'}
@ -848,7 +849,6 @@ class PlexSession(object):
user = data.find('User')
self._username = user.attrib.get('title')
self._userId = utils.cast(int, user.attrib.get('id'))
self._user = None # Cache for user object
# For backwards compatibility
self.players = [self.player] if self.player else []
@ -856,18 +856,16 @@ class PlexSession(object):
self.transcodeSessions = [self.transcodeSession] if self.transcodeSession else []
self.usernames = [self._username] if self._username else []
@property
@cached_property
def user(self):
""" Returns the :class:`~plexapi.myplex.MyPlexAccount` object (for admin)
or :class:`~plexapi.myplex.MyPlexUser` object (for users) for this session.
"""
if self._user is None:
myPlexAccount = self._server.myPlexAccount()
if self._userId == 1:
self._user = myPlexAccount
else:
self._user = myPlexAccount.user(self._username)
return self._user
myPlexAccount = self._server.myPlexAccount()
if self._userId == 1:
return myPlexAccount
return myPlexAccount.user(self._username)
def reload(self):
""" Reload the data for the session.

View file

@ -7,7 +7,7 @@ from plexapi import X_PLEX_CONTAINER_SIZE, log, media, utils
from plexapi.base import OPERATORS, PlexObject
from plexapi.exceptions import BadRequest, NotFound
from plexapi.settings import Setting
from plexapi.utils import deprecated
from plexapi.utils import cached_property, deprecated
class Library(PlexObject):
@ -418,7 +418,6 @@ class LibrarySection(PlexObject):
self._filterTypes = None
self._fieldTypes = None
self._totalViewSize = None
self._totalSize = None
self._totalDuration = None
self._totalStorage = None
@ -456,12 +455,10 @@ class LibrarySection(PlexObject):
item.librarySectionID = librarySectionID
return items
@property
@cached_property
def totalSize(self):
""" Returns the total number of items in the library for the default library type. """
if self._totalSize is None:
self._totalSize = self.totalViewSize(includeCollections=False)
return self._totalSize
return self.totalViewSize(includeCollections=False)
@property
def totalDuration(self):

View file

@ -17,7 +17,7 @@ from plexapi.media import Conversion, Optimized
from plexapi.playlist import Playlist
from plexapi.playqueue import PlayQueue
from plexapi.settings import Settings
from plexapi.utils import deprecated
from plexapi.utils import cached_property, deprecated
from requests.status_codes import _codes as codes
# Need these imports to populate utils.PLEXOBJECTS
@ -109,8 +109,6 @@ class PlexServer(PlexObject):
self._showSecrets = CONFIG.get('log.show_secrets', '').lower() == 'true'
self._session = session or requests.Session()
self._timeout = timeout
self._library = None # cached library
self._settings = None # cached settings
self._myPlexAccount = None # cached myPlexAccount
self._systemAccounts = None # cached list of SystemAccount
self._systemDevices = None # cached list of SystemDevice
@ -173,27 +171,22 @@ class PlexServer(PlexObject):
def _uriRoot(self):
return f'server://{self.machineIdentifier}/com.plexapp.plugins.library'
@property
@cached_property
def library(self):
""" Library to browse or search your media. """
if not self._library:
try:
data = self.query(Library.key)
self._library = Library(self, data)
except BadRequest:
data = self.query('/library/sections/')
# Only the owner has access to /library
# so just return the library without the data.
return Library(self, data)
return self._library
try:
data = self.query(Library.key)
except BadRequest:
# Only the owner has access to /library
# so just return the library without the data.
data = self.query('/library/sections/')
return Library(self, data)
@property
@cached_property
def settings(self):
""" Returns a list of all server settings. """
if not self._settings:
data = self.query(Settings.key)
self._settings = Settings(self, data)
return self._settings
data = self.query(Settings.key)
return Settings(self, data)
def account(self):
""" Returns the :class:`~plexapi.server.Account` object this server belongs to. """

View file

@ -24,6 +24,11 @@ try:
except ImportError:
tqdm = None
try:
from functools import cached_property
except ImportError:
from backports.cached_property import cached_property # noqa: F401
log = logging.getLogger('plexapi')
# Search Types - Plex uses these to filter specific media types when searching.

View file

@ -3,3 +3,4 @@
# pip install -r requirements.txt
#---------------------------------------------------------
requests
backports.cached-property; python_version<="3.7"

View file

@ -2,6 +2,7 @@
# PlexAPI requirements to run py.test.
# pip install -r requirements_dev.txt
#---------------------------------------------------------
backports.cached-property==1.0.2; python_version<="3.7"
coveralls==3.3.1
flake8==5.0.4
pillow==9.3.0

View file

@ -13,7 +13,7 @@ def test_settings_set(plex):
new_value = not old_value
cd.set(new_value)
plex.settings.save()
plex._settings = None
del plex.__dict__['settings']
assert plex.settings.get("autoEmptyTrash").value == new_value
@ -22,5 +22,5 @@ def test_settings_set_str(plex):
new_value = 99
cd.set(new_value)
plex.settings.save()
plex._settings = None
del plex.__dict__['settings']
assert plex.settings.get("OnDeckWindow").value == 99