当前位置: 首页>>代码示例>>Python>>正文


Python SimpleCache.close方法代码示例

本文整理汇总了Python中simplecache.SimpleCache.close方法的典型用法代码示例。如果您正苦于以下问题:Python SimpleCache.close方法的具体用法?Python SimpleCache.close怎么用?Python SimpleCache.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在simplecache.SimpleCache的用法示例。


在下文中一共展示了SimpleCache.close方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_repo_resourceaddons

# 需要导入模块: from simplecache import SimpleCache [as 别名]
# 或者: from simplecache.SimpleCache import close [as 别名]
def get_repo_resourceaddons(filterstr=""):
    '''helper to retrieve all available resource addons on the kodi repo'''
    result = []
    simplecache = SimpleCache()
    for item in xbmcvfs.listdir("addons://all/kodi.resource.images/")[1]:
        if not filterstr or item.lower().startswith(filterstr.lower()):
            addoninfo = get_repo_addoninfo(item, simplecache)
            if not addoninfo.get("name"):
                addoninfo = {"addonid": item, "name": item, "author": ""}
                addoninfo["thumbnail"] = "http://mirrors.kodi.tv/addons/krypton/%s/icon.png" % item
            addoninfo["path"] = "resource://%s/" % item
            result.append(addoninfo)
    simplecache.close()
    return result
开发者ID:marcelveldt,项目名称:script.skin.helper.service,代码行数:16,代码来源:resourceaddons.py

示例2: __init__

# 需要导入模块: from simplecache import SimpleCache [as 别名]
# 或者: from simplecache.SimpleCache import close [as 别名]
class PluginContent:
    """Hidden plugin entry point providing some helper features"""

    params = {}
    win = None

    def __init__(self):
        self.cache = SimpleCache()
        self.kodi_db = KodiDb()
        self.win = xbmcgui.Window(10000)
        try:
            self.params = dict(urlparse.parse_qsl(sys.argv[2].replace("?", "").lower().decode("utf-8")))
            log_msg("plugin called with parameters: %s" % self.params)
            self.main()
        except Exception as exc:
            log_exception(__name__, exc)
            xbmcplugin.endOfDirectory(handle=int(sys.argv[1]))

        # cleanup when done processing
        self.close()

    def close(self):
        """Cleanup Kodi Cpython instances"""
        self.cache.close()
        del self.win

    def main(self):
        """main action, load correct function"""
        action = self.params.get("action", "")
        if self.win.getProperty("SkinHelperShutdownRequested"):
            # do not proceed if kodi wants to exit
            log_msg("%s --> Not forfilling request: Kodi is exiting" % __name__, xbmc.LOGWARNING)
            xbmcplugin.endOfDirectory(handle=int(sys.argv[1]))
        else:
            try:
                if hasattr(self.__class__, action):
                    # launch module for action provided by this plugin
                    getattr(self, action)()
                else:
                    # legacy (widget) path called !!!
                    self.load_widget()
            except Exception as exc:
                log_exception(__name__, exc)

    def load_widget(self):
        """legacy entrypoint called (widgets are moved to seperate addon), start redirect..."""
        action = self.params.get("action", "")
        newaddon = "script.skin.helper.widgets"
        log_msg(
            "Deprecated method: %s. Please reassign your widgets to get rid of this message. -"
            "This automatic redirect will be removed in the future" % (action),
            xbmc.LOGWARNING,
        )
        paramstring = ""
        for key, value in self.params.iteritems():
            paramstring += ",%s=%s" % (key, value)
        if xbmc.getCondVisibility("System.HasAddon(%s)" % newaddon):
            # TEMP !!! for backwards compatability reasons only - to be removed in the near future!!
            import imp

            addon = xbmcaddon.Addon(newaddon)
            addon_path = addon.getAddonInfo("path").decode("utf-8")
            imp.load_source("plugin", os.path.join(addon_path, "plugin.py"))
            from plugin import main

            main.Main()
            del addon
        else:
            # trigger install of the addon
            if KODI_VERSION >= 17:
                xbmc.executebuiltin("InstallAddon(%s)" % newaddon)
            else:
                xbmc.executebuiltin("RunPlugin(plugin://%s)" % newaddon)

    def playchannel(self):
        """play channel from widget helper"""
        params = {"item": {"channelid": int(self.params["channelid"])}}
        self.kodi_db.set_json("Player.Open", params)

    def playrecording(self):
        """retrieve the recording and play to get resume working"""
        recording = self.kodi_db.recording(self.params["recordingid"])
        params = {"item": {"recordingid": recording["recordingid"]}}
        self.kodi_db.set_json("Player.Open", params)
        # manually seek because passing resume to the player json cmd doesn't seem to work
        if recording["resume"].get("position"):
            for i in range(50):
                if xbmc.getCondVisibility("Player.HasVideo"):
                    break
                xbmc.sleep(50)
            xbmc.Player().seekTime(recording["resume"].get("position"))

    def launch(self):
        """launch any builtin action using a plugin listitem"""
        if "runscript" in self.params["path"]:
            self.params["path"] = self.params["path"].replace("?", ",")
        xbmc.executebuiltin(self.params["path"])

    def playalbum(self):
        """helper to play an entire album"""
#.........这里部分代码省略.........
开发者ID:marcelveldt,项目名称:script.skin.helper.service,代码行数:103,代码来源:plugin_content.py

示例3: TheTvDb

# 需要导入模块: from simplecache import SimpleCache [as 别名]
# 或者: from simplecache.SimpleCache import close [as 别名]
class TheTvDb(object):
    '''Our main class'''
    _win = None
    _addon = None
    _token = None
    cache = None
    api_key = 'A7613F5C1482A540'  # default api key
    days_ahead = 120
    ignore_cache = False
    _close_called = False

    def __init__(self, api_key=None):
        '''Initialize our Module'''
        if api_key:
            self.api_key = api_key
        self.cache = SimpleCache()
        self._win = xbmcgui.Window(10000)
        self._addon = xbmcaddon.Addon(ADDON_ID)
        addonversion = self._addon.getAddonInfo('version').decode("utf-8")
        self.cache.global_checksum = "%s%s" % (addonversion, KODI_LANGUAGE)
        self._log_msg("Initialized")

    def close(self):
        '''Cleanup Kodi cpython classes'''
        self._close_called = True
        self.cache.close()
        del self._win
        del self._addon
        self._log_msg("Exited")

    def __del__(self):
        '''make sure close is called'''
        if not self._close_called:
            self.close()

    def get_data(self, endpoint, prefer_localized=False):
        '''grab the results from the api'''
        data = {}
        url = 'https://api.thetvdb.com/' + endpoint
        headers = {'Content-Type': 'application/json',
                   'Accept': 'application/json',
                   'User-agent': 'Mozilla/5.0', 'Authorization': 'Bearer %s' % self._get_token()}
        if prefer_localized:
            headers["Accept-Language"] = KODI_LANGUAGE
        try:
            response = requests.get(url, headers=headers, timeout=20)
            if response and response.content and response.status_code == 200:
                data = json.loads(response.content.decode('utf-8', 'replace'))
            elif response.status_code == 401:
                # token expired, refresh it and repeat our request
                self._log_msg("Token expired, refreshing...")
                headers['Bearer'] = self._get_token(True)
                response = requests.get(url, headers=headers, timeout=5)
                if response and response.content and response.status_code == 200:
                    data = json.loads(response.content.decode('utf-8', 'replace'))
            if data.get("data"):
                data = data["data"]
        except Exception as exc:
            self._log_msg("Exception in get_data --> %s" % repr(exc), xbmc.LOGERROR)
        return data

    @use_cache(60)
    def get_series_posters(self, seriesid, season=None):
        '''retrieves the URL for the series poster, prefer season poster if season number provided'''
        if season:
            images = self.get_data("series/%s/images/query?keyType=season&subKey=%s" % (seriesid, season))
        else:
            images = self.get_data("series/%s/images/query?keyType=poster" % (seriesid))
        return self.process_images(images)

    @use_cache(60)
    def get_series_fanarts(self, seriesid, landscape=False):
        '''retrieves the URL for the series fanart image'''
        if landscape:
            images = self.get_data("series/%s/images/query?keyType=fanart&subKey=text" % (seriesid))
        else:
            images = self.get_data("series/%s/images/query?keyType=fanart&subKey=graphical" % (seriesid))
        return self.process_images(images)

    @staticmethod
    def process_images(images):
        '''helper to sort and correct the images as the api output is rather messy'''
        result = []
        if images:
            for image in images:
                if image["fileName"] and not image["fileName"].endswith("/"):
                    if image["fileName"].startswith("http://"): 
                        image["fileName"] = image["fileName"].replace("http://", "https://")
                    elif not image["fileName"].startswith("https://"):
                        image["fileName"] = "https://thetvdb.com/banners/" + image["fileName"]
                    image_score = image["ratingsInfo"]["average"] * image["ratingsInfo"]["count"]
                    image["score"] = image_score
                    result.append(image)
        return [item["fileName"] for item in sorted(result, key=itemgetter("score"), reverse=True)]

    @use_cache(7)
    def get_episode(self, episodeid, seriesdetails=None):
        '''
            Returns the full information for a given episode id.
            Usage: specify the episode ID: TheTvDb().get_episode(episodeid)
#.........这里部分代码省略.........
开发者ID:marcelveldt,项目名称:script.module.thetvdb,代码行数:103,代码来源:thetvdb.py


注:本文中的simplecache.SimpleCache.close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。