权限没有,则隐藏 function forum_list_access_filter($forumlist, $gid, $allow = 'allowread') { global $grouplist; if (empty($forumlist)) return array(); if (1 == $gid) return $forumlist; $forumlist_filter = $forumlist; $group = $grouplist[$gid]; foreach ($forumlist_filter as $fid => $forum) { if (empty($forum['accesson']) && empty($group[$allow]) || !empty($forum['accesson']) && empty($forum['accesslist'][$gid][$allow])) { unset($forumlist_filter[$fid]); } unset($forumlist_filter[$fid]['accesslist']); } return $forumlist_filter; } function forum_filter_moduid($moduids) { $moduids = trim($moduids); if (empty($moduids)) return ''; $arr = explode(',', $moduids); $r = array(); foreach ($arr as $_uid) { $_uid = intval($_uid); $_user = user_read($_uid); if (empty($_user)) continue; if ($_user['gid'] > 4) continue; $r[] = $_uid; } return implode(',', $r); } function forum_safe_info($forum) { //unset($forum['moduids']); return $forum; } function forum_filter($forumlist) { foreach ($forumlist as &$val) { unset($val['brief'], $val['announcement'], $val['seo_title'], $val['seo_keywords'], $val['create_date_fmt'], $val['icon_url'], $val['modlist']); } return $forumlist; } function forum_format_url($forum) { global $conf; if (0 == $forum['category']) { // 列表URL $url = url('list-' . $forum['fid'], '', FALSE); } elseif (1 == $forum['category']) { // 频道 $url = url('category-' . $forum['fid'], '', FALSE); } elseif (2 == $forum['category']) { // 单页 $url = url('read-' . trim($forum['brief']), '', FALSE); } if ($conf['url_rewrite_on'] > 1 && $forum['well_alias']) { if (0 == $forum['category'] || 1 == $forum['category']) { $url = url($forum['well_alias'], '', FALSE); } elseif (2 == $forum['category']) { // 单页 $url = ($forum['threads'] && $forum['brief']) ? url($forum['well_alias'] . '-' . trim($forum['brief']), '', FALSE) : url($forum['well_alias'], '', FALSE); } } return $url; } function well_forum_alias() { $forumlist = forum_list_cache(); if (empty($forumlist)) return ''; $key = 'forum-alias'; static $cache = array(); if (isset($cache[$key])) return $cache[$key]; $cache[$key] = array(); foreach ($forumlist as $val) { if ($val['well_alias']) $cache[$key][$val['fid']] = $val['well_alias']; } return array_flip($cache[$key]); } function well_forum_alias_cache() { global $conf; $key = 'forum-alias-cache'; static $cache = array(); // 用静态变量只能在当前 request 生命周期缓存,跨进程需要再加一层缓存:redis/memcached/xcache/apc if (isset($cache[$key])) return $cache[$key]; if ('mysql' == $conf['cache']['type']) { $arr = well_forum_alias(); } else { $arr = cache_get($key); if (NULL === $arr) { $arr = well_forum_alias(); !empty($arr) AND cache_set($key, $arr); } } $cache[$key] = empty($arr) ? '' : $arr; return $cache[$key]; } ?>python - Youtube API token expires after a few days - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Youtube API token expires after a few days - Stack Overflow

programmeradmin10浏览0评论

I wrote a little python app which will stop and create broadcast via the Youtube API at defined times.

It works all fine but the token created at the first start or when a token does not exists when the app is started gets expired after a few days.

A refresh token is included but after a few days it fails to refresh the token.

I would like to only have to login once and just allow a refresh of the token.

Here is my login function

SCOPES = [";]

...
...


    def _authenticate(self, create_new_token: bool = False):
        try:
            credentials = None
            dirname = os.path.dirname(__file__)
            token_filename = os.path.join(dirname, self.TOKEN_FILE)
            if os.path.exists(token_filename):  # do we have a token file already?
                credentials = Credentials.from_authorized_user_file(
                    token_filename, self.SCOPES
                )

            if create_new_token:
                credentials = None  # will force to have to login again and create a new token file

            if (
                not credentials or not credentials.valid
            ):  # do we have no token or is the token no longer valid?
                if (
                    credentials and credentials.expired and credentials.refresh_token
                ):  # is the token expired?
                    try:
                        self.logger.debug("Token expired. Attempting to refresh...")
                        credentials.refresh(Request())
                        self.logger.debug("Token successfully refreshed.")
                    except Exception as e:
                        self.logger.error(f"Error renewing token: {e}")
                        raise e
                else:
                    try:
                        dirname = os.path.dirname(__file__)
                        filename = os.path.join(
                            dirname,
                            self.config[self.CONF_YOUTUBE_SETTINGS][
                                self.CONF_CREDENTIALS_FILE
                            ],
                        )
                        flow = InstalledAppFlow.from_client_secrets_file(
                            filename,
                            self.SCOPES,
                        )
                        credentials = flow.run_local_server(
                            port=0, access_type="offline", prompt="consent"
                        )
                    except Exception as e:
                        self.logger.error(
                            f"Failed to login, maybe the credentials file does not exist? `{filename}` Error was: {e}"
                        )
                        raise e
                try:
                    with open(token_filename, "w") as token:
                        token.write(credentials.to_json())
                        self.logger.info(
                            f"Token was successfully written to token file `{token_filename}`"
                        )
                except Exception as e:
                    self.logger.error(
                        f"Failed to login, maybe the credentials file does not exist? `{token_filename}` Error was: {e}"
                    )
                    raise e

            self.youtube = build("youtube", "v3", credentials=credentials)
            return self.youtube
        except Exception as e:
            self.logger.error(f"Failed to authenticate: {str(e)}")
            return None

Here are some logs of my python script:

Successful refresh of the token

2025-01-13 23:59:02,157 - DEBUG - Token expired. Attempting to refresh...
2025-01-13 23:59:02,157 - DEBUG - Making request: POST 
2025-01-13 23:59:02,159 - DEBUG - Starting new HTTPS connection (1): oauth2.googleapis:443
2025-01-13 23:59:02,584 - DEBUG - :443 "POST /token HTTP/1.1" 200 None
2025-01-13 23:59:02,584 - DEBUG - Token successfully refreshed.
2025-01-13 23:59:02,585 - INFO - Token was successfully written to token file `/home/My/youtube-manager/token.secret`
2025-01-13 23:59:02,587 - INFO - file_cache is only supported with oauth2client<4.0.0
2025-01-13 23:59:02,598 - DEBUG - URL being requested: POST ;broadcastStatus=complete&id=11111&alt=json
2025-01-13 23:59:04,189 - INFO - Broadcast with  the id `11111` was stopped successfully

And here it failed

2025-01-14 11:59:02,161 - DEBUG - Token expired. Attempting to refresh...
2025-01-14 11:59:02,162 - DEBUG - Making request: POST 
2025-01-14 11:59:02,164 - DEBUG - Starting new HTTPS connection (1): oauth2.googleapis:443
2025-01-14 11:59:02,398 - DEBUG - :443 "POST /token HTTP/1.1" 400 None
2025-01-14 11:59:02,399 - ERROR - Error renewing token: ('invalid_grant: Token has been expired or revoked.', {'error': 'invalid_grant', 'error_description': 'Token has been expired or revoked.'})
2025-01-14 11:59:02,399 - ERROR - Failed to authenticate: ('invalid_grant: Token has been expired or revoked.', {'error': 'invalid_grant', 'error_description': 'Token has been expired or revoked.'})
2025-01-14 11:59:02,399 - ERROR - Failed to stop broadcast: 'YouTubeStreamManager' object has no attribute 'youtube'
发布评论

评论列表(0)

  1. 暂无评论