我一直在探索YouTube数据API。我的项目的前提很简单:使用API、身份验证(是的,我拥有帐户的凭据),然后简单地检索所有视频的列表,包括公共视频和私有视频。
我已经成功地完成了这一点,除了完全自动化的部分。我使用了来自不同来源的代码,当我在命令行上运行它时,它为我提供了一个在浏览器中使用的链接,以便进行授权。
看起来是这样的:
……
下面是我的python代码片段:
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
...
...
# Get credentials and create an API client
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
client_secrets_file, scopes)
credentials = flow.run_console()
youtube = googleapiclient.discovery.build(
api_service_name, api_version, credentials=credentials)
## MAKE youtube SEARCH REQUEST
last_date = '2018-10-01T00:00:00Z'
request = youtube.search().list(
part="snippet",
forMine=True,
maxResults=50,
order="date",
type="video"
)
all_items = []
response = request.execute()我在这里的问题是:是否可以以编程方式执行授权,以便应用程序可以独立运行,而不必等待用户操作(从CMD字面上复制URL、访问获取令牌以及复制和粘贴令牌)?我想安排这一点,因此希望它在没有人为干预的情况下运行和验证。这有可能吗?如果是这样的话,能给我指出一些有用的例子和/或其他资源来帮助我达到这个目标吗?谢谢百万,
发布于 2020-02-27 02:32:02
来自Credentials的credentials = flow.run_console()实例具有内置的刷新令牌的功能。如果需要,它将在执行请求时刷新令牌。
因此,您可以将credentials对象保存到泡菜中,并在需要时读取它。
对Google示例代码做一些修改:
def get_authenticated_service():
if os.path.exists(CREDENTIALS_PICKLE_FILE):
with open(CREDENTIALS_PICKLE_FILE, 'rb') as f:
credentials = pickle.load(f)
else:
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
credentials = flow.run_console()
with open(CREDENTIALS_PICKLE_FILE, 'wb') as f:
pickle.dump(credentials, f)
return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)https://stackoverflow.com/questions/58073119
复制相似问题