python类LOGERROR的实例源码

screensaverutils.py 文件源码 项目:screensaver.kaster 作者: enen92 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_own_pictures(path):
    _, files = xbmcvfs.listdir(xbmc.translatePath(path))
    images_dict = {}
    image_file = os.path.join(xbmc.translatePath(path), "images.json")
    if xbmcvfs.exists(image_file):
        with open(image_file, "r") as f:
            try:
                images_dict = json.loads(f.read())
            except ValueError:
                kodiutils.log(kodiutils.get_string(32010), xbmc.LOGERROR)
    for _file in files:
        if _file.endswith(('.png', '.jpg', '.jpeg')):
            returned_dict = {
                "url": os.path.join(xbmc.translatePath(path), _file),
                "private": True
            }
            if images_dict:
                for image in images_dict:
                    if "image" in image.keys() and image["image"] == _file:
                        if "line1" in image.keys():
                            returned_dict["line1"] = image["line1"]
                        if "line2" in image.keys():
                            returned_dict["line2"] = image["line2"]
            yield returned_dict
common.py 文件源码 项目:konsodi 作者: kharts 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def log(msg, level=xbmc.LOGNOTICE):
    """
    Outputs message to log file
    :param msg: message to output
    :param level: debug levelxbmc. Values:
    xbmc.LOGDEBUG = 0
    xbmc.LOGERROR = 4
    xbmc.LOGFATAL = 6
    xbmc.LOGINFO = 1
    xbmc.LOGNONE = 7
    xbmc.LOGNOTICE = 2
    xbmc.LOGSEVERE = 5
    xbmc.LOGWARNING = 3
    """

    log_message = u'{0}: {1}'.format(addonID, msg)
    xbmc.log(log_message.encode("utf-8"), level)
thetvdb.py 文件源码 项目:script.module.thetvdb 作者: marcelveldt 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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
koditidal2.py 文件源码 项目:plugin.audio.tidal2 作者: arnesongit 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get_album_json_thread(self):
        try:
            while not xbmc.abortRequested and not self.abortAlbumThreads:
                try:
                    album_id = self.albumQueue.get_nowait()
                except:
                    break
                try:
                    self.get_album(album_id, withCache=False)
                except requests.HTTPError as e:
                    r = e.response
                    msg = _T(30505)
                    try:
                        msg = r.reason
                        msg = r.json().get('userMessage')
                    except:
                        pass
                    log('Error getting Album ID %s' % album_id, xbmc.LOGERROR)
                    if r.status_code == 429 and not self.abortAlbumThreads:
                        self.abortAlbumThreads = True
                        log('Too many requests. Aborting Workers ...', xbmc.LOGERROR)
                        self.albumQueue._init(9999)
                        xbmcgui.Dialog().notification(plugin.name, msg, xbmcgui.NOTIFICATION_ERROR)
        except Exception, e:
            traceback.print_exc()
koditidal.py 文件源码 项目:plugin.audio.tidal2 作者: arnesongit 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def selectPlaylistDialog(self, headline=None, allowNew=False):
        if not self._session.is_logged_in:
            return None
        xbmc.executebuiltin("ActivateWindow(busydialog)")
        try:
            if not headline:
                headline = _T(30238)
            items = self.playlists()
            dialog = xbmcgui.Dialog()
            item_list = [item.title for item in items]
            if allowNew:
                item_list.append(_T(30237))
        except Exception, e:
            log(str(e), level=xbmc.LOGERROR)
            xbmc.executebuiltin("Dialog.Close(busydialog)")
            return None
        xbmc.executebuiltin("Dialog.Close(busydialog)")
        selected = dialog.select(headline, item_list)
        if selected >= len(items):
            item = self.newPlaylistDialog()
            return item
        elif selected >= 0:
            return items[selected]
        return None
debug.py 文件源码 项目:plugin.audio.tidal2 作者: arnesongit 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def log(self, txt = '', level=xbmc.LOGDEBUG):
        ''' Log a text into the Kodi-Logfile '''
        try:
            if self.detailLevel > 0 or level == xbmc.LOGERROR:
                if self.detailLevel == 2 and level == xbmc.LOGDEBUG:
                    # More Logging
                    level = xbmc.LOGNOTICE
                elif self.detailLevel == 3 and (level == xbmc.LOGDEBUG or level == xbmc.LOGSEVERE):
                    # Complex Logging
                    level = xbmc.LOGNOTICE
                if level != xbmc.LOGSEVERE:
                    if isinstance(txt, unicode):
                        txt = unidecode(txt)
                    xbmc.log(b"[%s] %s" % (self.pluginName, txt), level) 
        except:
            xbmc.log(b"[%s] Unicode Error in message text" % self.pluginName, xbmc.LOGERROR)
debug.py 文件源码 项目:plugin.audio.tidal2 作者: arnesongit 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def emit(self, record):
        if record.levelno < logging.WARNING and self._modules and not record.name in self._modules:
            # Log INFO and DEBUG only with enabled modules
            return
        levels = {
            logging.CRITICAL: xbmc.LOGFATAL,
            logging.ERROR: xbmc.LOGERROR,
            logging.WARNING: xbmc.LOGWARNING,
            logging.INFO: xbmc.LOGNOTICE,
            logging.DEBUG: xbmc.LOGSEVERE,
            logging.NOTSET: xbmc.LOGNONE,
        }
        try:
            xbmc.log(self.format(record), levels[record.levelno])
        except:
            try:
                xbmc.log(self.format(record).encode('utf-8', 'ignore'), levels[record.levelno])
            except:
                xbmc.log(b"[%s] Unicode Error in message text" % self.pluginName, levels[record.levelno])
addon.py 文件源码 项目:plugin.audio.tidal2 作者: arnesongit 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def user_playlist_remove_album(playlist_id, item_id, dialog=True):
    playlist = session.get_playlist(playlist_id)
    ok = True
    if dialog:
        ok = xbmcgui.Dialog().yesno(_T(30247) % playlist.title, _T(30246))
    if ok:
        xbmc.executebuiltin('ActivateWindow(busydialog)')
        try:
            items = session.get_playlist_tracks(playlist)
            for item in items:
                if '%s' % item.album.id == '%s' % item_id:
                    session.user.remove_playlist_entry(playlist, entry_no=item._playlist_pos)
                    break # Remove only one Item
        except Exception, e:
            log(str(e), level=xbmc.LOGERROR)
            traceback.print_exc()
        xbmc.executebuiltin('Dialog.Close(busydialog)')
        xbmc.executebuiltin('Container.Refresh()')
addon.py 文件源码 项目:plugin.audio.tidal2 作者: arnesongit 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def user_playlist_move_entry(playlist_id, entry_no, item_id):
    dialog = xbmcgui.Dialog()
    playlist = session.user.selectPlaylistDialog(headline=_T(30248), allowNew=True)
    if playlist and playlist.id <> playlist_id:
        xbmc.executebuiltin( "ActivateWindow(busydialog)" )
        try:
            ok = session.user.add_playlist_entries(playlist=playlist, item_ids=[item_id])
            if ok:
                ok = session.user.remove_playlist_entry(playlist_id, entry_no=entry_no)
            else:
                dialog.notification(plugin.name, _T('API Call Failed'), xbmcgui.NOTIFICATION_ERROR)
        except Exception, e:
            log(str(e), level=xbmc.LOGERROR)
            traceback.print_exc()
        xbmc.executebuiltin( "Dialog.Close(busydialog)" )
        xbmc.executebuiltin('Container.Refresh()')
vpnapi.py 文件源码 项目:script.tvguide.fullscreen 作者: primaeval 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def __init__(self):
        # Class initialisation.  Fails with a RuntimeError exception if VPN Manager add-on is not available, or too old
        self.filtered_addons = []
        self.filtered_windows = []
        self.primary_vpns = []
        self.last_updated = 0
        self.refreshLists()
        self.default = self.getConnected()
        xbmc.log("VPN Mgr API : Default is " + self.default, level=xbmc.LOGDEBUG)
        self.timeout = 30
        if not xbmc.getCondVisibility("System.HasAddon(service.vpn.manager)"):
            xbmc.log("VPN Mgr API : VPN Manager is not installed, cannot use filtering", level=xbmc.LOGERROR)
            raise RuntimeError("VPN Manager is not installed")
        else:
            v = int((xbmcaddon.Addon("service.vpn.manager").getAddonInfo("version").strip()).replace(".",""))
            if v < 310:
                raise RuntimeError("VPN Manager " + str(v) + " installed, but needs to be v3.1.0 or later")
common.py 文件源码 项目:plugin.video.amazon65 作者: phil65 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def getURL(url, host=BASE_URL.split('//')[1], useCookie=False, silent=False, headers=None):
    cj = cookielib.LWPCookieJar()
    if useCookie:
        if isinstance(useCookie, bool):
            cj = mechanizeLogin()
        else:
            cj = useCookie
        if isinstance(cj, bool):
            return False
    dispurl = re.sub('(?i)%s|%s|&token=\w+' % (tvdb, tmdb), '', url).strip()
    if not silent:
        Log('getURL: ' + dispurl)
    if not headers:
        headers = [('User-Agent', UserAgent), ('Host', host)]
    try:
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), urllib2.HTTPRedirectHandler)
        opener.addheaders = headers
        usock = opener.open(url)
        response = usock.read()
        usock.close()
    except urllib2.URLError, e:
        Log('Error reason: %s' % e, xbmc.LOGERROR)
        return False
    return response
common.py 文件源码 项目:plugin.video.amazon65 作者: phil65 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def getATVURL(url):
    try:
        opener = urllib2.build_opener()
        Log('ATVURL --> url = ' + url)
        hmac_key = binascii.unhexlify('f5b0a28b415e443810130a4bcb86e50d800508cc')
        sig = hmac.new(hmac_key, url, hashlib.sha1)
        androidsig = base64.encodestring(sig.digest()).replace('\n', '')
        opener.addheaders = [('x-android-sign', androidsig)]
        usock = opener.open(url)
        response = usock.read()
        usock.close()
    except urllib2.URLError, e:
        Log('Error reason: %s' % e, xbmc.LOGERROR)
        return False
    else:
        return response
KodiScriptImporter.py 文件源码 项目:xbmctopython 作者: pybquillast 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def enableService(self, serviceId, addonFile):
        import xbmc
        try:
            srvThread = execfile(addonFile, sys.modules['__main__'].__dict__)
        except Exception as e:
            srvThread = None
            msg, loglevel = str(e), xbmc.LOGERROR
        else:
            msg = 'Service %s, succesfully loaded from %s'
            msg, loglevel = msg % (serviceId, addonFile), xbmc.LOGDEBUG
        finally:
            xbmc.log(msg, loglevel)
            if loglevel == xbmc.LOGERROR:
                msg = traceback.format_exc()
                xbmc.log(msg, xbmc.LOGERROR)
        return srvThread
KodiScriptImporter.py 文件源码 项目:xbmctopython 作者: pybquillast 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def run(self, url):
        xbmc = self.theGlobals['xbmc']
        urlScheme = urlparse.urlparse(url)
        if urlScheme.scheme != 'plugin': return             # Plugin diferente
        pluginId, urlArgs = urllib.splitquery(url)
        self.theGlobals['sys'].argv = [pluginId, self.theGlobals['sys'].argv[1] + 1, '?' + (urlArgs or '')]
        self.addonID = actualID = urlScheme.netloc
        addonDir = xbmc.translatePath('special://home/addons/' + actualID)
        if addonDir.startswith('vrt:%s' % os.path.sep):
            self.vrtDisk.installPathHook()
            sys.path.insert(0, addonDir)
            sourceCode = self.getVrtDiskAddonSource()
        else:
            sourceCode = self.getCompiledAddonSource(actualID)
            self.importer.setAddonDir(addonDir)
        try:
            exec(sourceCode, self.theGlobals)
        except Exception as e:
            xbmc.log(str(e), xbmc.LOGERROR)
            msg = traceback.format_exc()
            xbmc.log(msg, xbmc.LOGERROR)
            self.answ = None
        return self.answ
util.py 文件源码 项目:plex-for-kodi-mod 作者: mrclemds 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def ERROR(txt='', hide_tb=False, notify=False):
    if isinstance(txt, str):
        txt = txt.decode("utf-8")
    short = str(sys.exc_info()[1])
    if hide_tb:
        xbmc.log('script.plex: ERROR: {0} - {1}'.format(txt, short), xbmc.LOGERROR)
        return short

    import traceback
    tb = traceback.format_exc()
    xbmc.log("_________________________________________________________________________________", xbmc.LOGERROR)
    xbmc.log('script.plex: ERROR: ' + txt, xbmc.LOGERROR)
    for l in tb.splitlines():
        xbmc.log('    ' + l, xbmc.LOGERROR)
    xbmc.log("_________________________________________________________________________________", xbmc.LOGERROR)
    xbmc.log("`", xbmc.LOGERROR)
    if notify:
        showNotification('ERROR: {0}'.format(short))
    return short
service.py 文件源码 项目:soap4me-proxy 作者: eschava 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __init__(self):
        watched_status = WatchedStatus()

        api = SoapApi(watched_status)
        watched_status.soap_api = api
        api.main()

        try:
            httpd = SocketServer.TCPServer(("", KodiConfig.get_web_port()), WebHandler)
            httpd.api = api
            kodi_waiter = threading.Thread(target=self.kodi_waiter_thread, args=(httpd, watched_status,))
            kodi_waiter.start()
            httpd.serve_forever()
        except:
            message_error("Cannot create web-server, port is busy")
            xbmc.log('%s: %s' % (ADDONID, format_exc()), xbmc.LOGERROR)
            #raise
vpnapi.py 文件源码 项目:service.vpn.manager 作者: Zomboided 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def __init__(self):
        # Class initialisation.  Fails with a RuntimeError exception if VPN Manager add-on is not available, or too old
        self.filtered_addons = []
        self.filtered_windows = []
        self.primary_vpns = []
        self.last_updated = 0
        self.refreshLists()
        self.default = self.getConnected()
        xbmc.log("VPN Mgr API : Default is " + self.default, level=xbmc.LOGDEBUG)
        self.timeout = 30
        if not xbmc.getCondVisibility("System.HasAddon(service.vpn.manager)"):
            xbmc.log("VPN Mgr API : VPN Manager is not installed, cannot use filtering", level=xbmc.LOGERROR)
            raise RuntimeError("VPN Manager is not installed")
        else:
            v = int((xbmcaddon.Addon("service.vpn.manager").getAddonInfo("version").strip()).replace(".",""))
            if v < 310:
                raise RuntimeError("VPN Manager " + str(v) + " installed, but needs to be v3.1.0 or later")
utils.py 文件源码 项目:script.skin.helper.skinbackup 作者: marcelveldt 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def log_exception(modulename, exceptiondetails):
    '''helper to properly log exception details'''
    log_msg(format_exc(sys.exc_info()), xbmc.LOGNOTICE)
    log_msg("ERROR in %s ! --> %s" % (modulename, exceptiondetails), xbmc.LOGERROR)
    dialog = xbmcgui.Dialog()
    dialog.notification(
        "Skin Helper Backup",
        "Error while executing, please check your kodi logfile.",
        xbmcgui.NOTIFICATION_ERROR)
    del dialog
utils.py 文件源码 项目:plugin.video.bdyun 作者: caasiu 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def log(message,loglevel=xbmc.LOGNOTICE):
    """"save message to kodi.log.

    Args:
        message: has to be unicode, http://wiki.xbmc.org/index.php?title=Add-on_unicode_paths#Logging
        loglevel: xbmc.LOGDEBUG, xbmc.LOGINFO, xbmc.LOGNOTICE, xbmc.LOGWARNING, xbmc.LOGERROR, xbmc.LOGFATAL
    """
    xbmc.log(encode(__addon_id__ + u": " + message), level=loglevel)
common.py 文件源码 项目:konsodi 作者: kharts 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def log_exception(content):
    """
    Outputs content to log file
    :param content: content which should be output
    :return: None
    """

    if type(content) is str:
        message = unicode(content, "utf-8")
    else:
        message = content
    log(message, xbmc.LOGERROR)
utils.py 文件源码 项目:plugin.audio.spotify 作者: marcelveldt 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_spotty(self, binary_path):
        '''self-test spotty binary'''
        try:
            st = os.stat(binary_path)
            os.chmod(binary_path, st.st_mode | stat.S_IEXEC)
            args = [
                binary_path,
                "-n", "selftest",
                "-x", "--disable-discovery"
            ]
            startupinfo = None
            if os.name == 'nt':
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
            spotty = subprocess.Popen(
                args,
                startupinfo=startupinfo,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                bufsize=0)
            stdout, stderr = spotty.communicate()
            log_msg(stdout)
            if "ok spotty" in stdout:
                return True
            elif xbmc.getCondVisibility("System.Platform.Windows"):
                log_msg("Unable to initialize spotty binary for playback."
                        "Make sure you have the VC++ 2015 runtime installed.", xbmc.LOGERROR)
        except Exception as exc:
            log_exception(__name__, exc)
        return False
engine.py 文件源码 项目:Python-GoogleDrive-VideoStream 作者: ddurdle 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def debugger(self):
        try:

            remote_debugger = settings.getSetting('remote_debugger')
            remote_debugger_host = settings.getSetting('remote_debugger_host')

            # append pydev remote debugger
            if remote_debugger == 'true':
                # Make pydev debugger works for auto reload.
                # Note pydevd module need to be copied in XBMC\system\python\Lib\pysrc
                import pysrc.pydevd as pydevd
                # stdoutToServer and stderrToServer redirect stdout and stderr to eclipse console
                pydevd.settrace(remote_debugger_host, stdoutToServer=True, stderrToServer=True)
        except ImportError:
            xbmc.log(self.addon.getLocalizedString(30016), xbmc.LOGERROR)
            sys.exit(1)
        except :
            return




    ##
    # add a menu to a directory screen
    #   parameters: url to resolve, title to display, optional: icon, fanart, total_items, instance name
    ##
cloudservice.py 文件源码 项目:Python-GoogleDrive-VideoStream 作者: ddurdle 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def downloadGeneralFile(self, url, file, force=False):

        req = urllib2.Request(url, None, self.getHeadersList())

        # already downloaded
        if not force and xbmcvfs.exists(file) and xbmcvfs.File(file).size() > 0:
            return

        f = xbmcvfs.File(file, 'w')

        # if action fails, validate login
        try:
            f.write(urllib2.urlopen(req).read())
            f.close()

        except urllib2.URLError, e:
                self.refreshToken()
                req = urllib2.Request(url, None, self.getHeadersList())
                try:
                  f.write(urllib2.urlopen(req).read())
                  f.close()
                except urllib2.URLError, e:
                  xbmc.log(self.addon.getAddonInfo('name') + ': downloadGeneralFle ' + str(e), xbmc.LOGERROR)
                  return None
        #can't write to cache for some reason
        except IOError:
                return None
        return file
    ##
    # retrieve/download a general file
    #   parameters: title of video, whether to prompt for quality/format (optional), medial url object, package object, whether to force download (overwrite), whether folder is encrypted, folder name
    ##
cloudservice.py 文件源码 项目:Python-GoogleDrive-VideoStream 作者: ddurdle 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def downloadPicture(self, url, file):

        req = urllib2.Request(url, None, self.getHeadersList())

        # already downloaded
        if xbmcvfs.exists(file) and xbmcvfs.File(file).size() > 0:
            return

        f = xbmcvfs.File(file, 'w')

        # if action fails, validate login
        try:
            f.write(urllib2.urlopen(req).read())
            f.close()

        except urllib2.URLError, e:
                self.refreshToken()
                req = urllib2.Request(url, None, self.getHeadersList())
                try:
                  f.write(urllib2.urlopen(req).read())
                  f.close()
                except urllib2.URLError, e:
                  xbmc.log(self.addon.getAddonInfo('name') + ': downloadPicture ' + str(e), xbmc.LOGERROR)
                  return None
        #can't write to cache for some reason
        except IOError:
                return None
        return file
gSpreadsheets.py 文件源码 项目:Python-GoogleDrive-VideoStream 作者: ddurdle 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def createWorksheet(self,url,title,cols,rows):

        header = { 'User-Agent' : self.user_agent, 'Authorization' : 'GoogleLogin auth=%s' % self.authorization.getToken('wise'), 'GData-Version' : '3.0',  'Content-Type': 'application/atom+xml' }

        entry = '<?xml version=\'1.0\' encoding=\'UTF-8\'?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:gs="http://schemas.google.com/spreadsheets/2006"><title>A worksheetdadf</title><gs:rowCount>100</gs:rowCount><gs:colCount>20</gs:colCount></entry>'

        req = urllib2.Request(url, entry, header)

        try:
            response = urllib2.urlopen(req)
        except urllib2.URLError, e:
          if e.code == 403 or e.code == 401:
            self.service.refreshToken()
            req = urllib2.Request(url, None, self.service.getHeadersList())
            try:
                response = urllib2.urlopen(req)
            except urllib2.URLError, e:
                xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
                return False
          else:
            xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
            return False


        response.read()
        response.close()

        return True

    #
    # returns a list of spreadsheets contained in the Google Docs account
    #
gSpreadsheets.py 文件源码 项目:Python-GoogleDrive-VideoStream 作者: ddurdle 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def createHeaderRow(self,url):

        header = { 'User-Agent' : self.user_agent, 'Authorization' : 'GoogleLogin auth=%s' % self.authorization.getToken('wise'), 'GData-Version' : '3.0',  "If-Match" : '*', 'Content-Type': 'application/atom+xml'}

        entry = '<?xml version=\'1.0\' encoding=\'UTF-8\'?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended"> <gsx:hours>1</gsx:hours></entry>'

        req = urllib2.Request(url, entry, header)

        try:
            response = urllib2.urlopen(req)
        except urllib2.URLError, e:
          if e.code == 403 or e.code == 401:
            self.service.refreshToken()
            header = { 'User-Agent' : self.user_agent, 'Authorization' : 'GoogleLogin auth=%s' % self.authorization.getToken('wise'), 'GData-Version' : '3.0',  "If-Match" : '*', 'Content-Type': 'application/atom+xml'}
            req = urllib2.Request(url, entry, header)
            try:
                response = urllib2.urlopen(req)
            except urllib2.URLError, e:
                xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
                return False
          else:
            xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
            return False

        response.read()
        response.close()

        return True




    #
    # returns a list of worksheets with a link to their listfeeds
    #
gSheets_api4.py 文件源码 项目:Python-GoogleDrive-VideoStream 作者: ddurdle 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def createSpreadsheet(self):

        #header = { 'User-Agent' : self.user_agent, 'Authorization' : 'GoogleLogin auth=%s' % self.authorization.getToken('wise'), 'GData-Version' : '3.0',  'Content-Type': 'application/atom+xml' }

        entry = '{"properties": { "title": "TEST123" }}'
 #       entry = { 'properties' : {'title': 'TEST1234'}}

        url = self.API_URL #+ '?key=AIzaSyD-a9IF8KKYgoC3cpgS-Al7hLQDbugrDcw&alt=json'
#        url = 'https://sheets.googleapis.com/v4/spreadsheets/1lrARPXpjLAO-edm5J9p0UK7nmkukST6bv07u8ai1MY8'
        req = urllib2.Request(url, entry, self.service.getHeadersList(isPOST=True))

        #req = urllib2.Request(url,  json.dumps(entry), self.service.getHeadersList(isPOST=True, isJSON=True))
 #       req = urllib2.Request(url, None, self.service.getHeadersList())

        try:
            response = urllib2.urlopen(req)
        except urllib2.URLError, e:
          if e.code == 403 or e.code == 401:
            self.service.refreshToken()
            req = urllib2.Request(url, entry, self.service.getHeadersList(isPOST=True))
            try:
                response = urllib2.urlopen(req)
            except urllib2.URLError, e:
                xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
                return False
          else:
            xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
            return False


        response.read()
        response.close()

        return True

    #
    # append data to spreadsheet
    #
gSheets_api4.py 文件源码 项目:Python-GoogleDrive-VideoStream 作者: ddurdle 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def addRows(self, spreadsheetID):



        entry = '{"values": [[ "title", "TEST123" ]]}'

        url = self.API_URL + '/'+spreadsheetID+'/values/A1:append?valueInputOption=USER_ENTERED'#values/Sheet1!A1:A3?valueInputOption=USER_ENTERED'
#        url = 'https://sheets.googleapis.com/v4/spreadsheets/1lrARPXpjLAO-edm5J9p0UK7nmkukST6bv07u8ai1MY8'
        req = urllib2.Request(url, entry, self.service.getHeadersList(isPOST=True))

        #req = urllib2.Request(url,  json.dumps(entry), self.service.getHeadersList(isPOST=True, isJSON=True))
 #       req = urllib2.Request(url, None, self.service.getHeadersList())

        try:
            response = urllib2.urlopen(req)
        except urllib2.URLError, e:
          if e.code == 403 or e.code == 401:
            self.service.refreshToken()
            req = urllib2.Request(url, entry, self.service.getHeadersList(isPOST=True))
            try:
                response = urllib2.urlopen(req)
            except urllib2.URLError, e:
                xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
                return False
          else:
            xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
            return False


        response.read()
        response.close()

        return True



    #
    # returns a list of spreadsheets and a link to their worksheets
    #
gSheets_api4.py 文件源码 项目:Python-GoogleDrive-VideoStream 作者: ddurdle 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def createWorksheet(self,url,title,cols,rows):

        header = { 'User-Agent' : self.user_agent, 'Authorization' : 'GoogleLogin auth=%s' % self.authorization.getToken('wise'), 'GData-Version' : '3.0',  'Content-Type': 'application/atom+xml' }

        entry = '<?xml version=\'1.0\' encoding=\'UTF-8\'?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:gs="http://schemas.google.com/spreadsheets/2006"><title>A worksheetdadf</title><gs:rowCount>100</gs:rowCount><gs:colCount>20</gs:colCount></entry>'

        req = urllib2.Request(url, entry, header)

        try:
            response = urllib2.urlopen(req)
        except urllib2.URLError, e:
          if e.code == 403 or e.code == 401:
            self.service.refreshToken()
            req = urllib2.Request(url, None, self.service.getHeadersList())
            try:
                response = urllib2.urlopen(req)
            except urllib2.URLError, e:
                xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
                return False
          else:
            xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
            return False


        response.read()
        response.close()

        return True

    #
    # returns a list of spreadsheets contained in the Google Docs account
    #
gSheets_api4.py 文件源码 项目:Python-GoogleDrive-VideoStream 作者: ddurdle 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def createHeaderRow(self,url):

        header = { 'User-Agent' : self.user_agent, 'Authorization' : 'GoogleLogin auth=%s' % self.authorization.getToken('wise'), 'GData-Version' : '3.0',  "If-Match" : '*', 'Content-Type': 'application/atom+xml'}

        entry = '<?xml version=\'1.0\' encoding=\'UTF-8\'?><entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended"> <gsx:hours>1</gsx:hours></entry>'

        req = urllib2.Request(url, entry, header)

        try:
            response = urllib2.urlopen(req)
        except urllib2.URLError, e:
          if e.code == 403 or e.code == 401:
            self.service.refreshToken()
            header = { 'User-Agent' : self.user_agent, 'Authorization' : 'GoogleLogin auth=%s' % self.authorization.getToken('wise'), 'GData-Version' : '3.0',  "If-Match" : '*', 'Content-Type': 'application/atom+xml'}
            req = urllib2.Request(url, entry, header)
            try:
                response = urllib2.urlopen(req)
            except urllib2.URLError, e:
                xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
                return False
          else:
            xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
            return False

        response.read()
        response.close()

        return True

    #
    # returns a list of worksheets with a link to their listfeeds
    #


问题


面经


文章

微信
公众号

扫码关注公众号