- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
编辑:我安装了运行第二个脚本的标志,但对于与第三方 MCN 合作的 YouTube 用户来说,运气不佳,无法使用 API 为他们启用获利功能。
我找到了这个旧版本的 YouTube 上传脚本:
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Simple command-line sample for Youtube Partner API.
Command-line application that creates an asset, uploads and claims a video for that asset.
Usage:
$ python upload_monetize_video_example.py --file=VIDEO_FILE --channelID=CHANNEL_ID \
[--title=VIDEO_TITLE] [--description=VIDEO_DESCRIPTION] [--category=CATEGORY_ID] \
[--keywords=KEYWORDS] [--privacyStatus=PRIVACY_STATUS] [--policyId=POLICY_ID]
You can also get help on all the command-line flags the program understands
by running:
$ python upload_monetize_video_example.py --help
"""
__author__ = 'jeffy+pub@google.com (Jeffrey Posnick)'
import httplib
import httplib2
import logging
import os
import random
import sys
import time
from apiclient.discovery import build
from apiclient.errors import HttpError
from apiclient.http import MediaFileUpload
from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run
from optparse import OptionParser
# Explicitly tell the underlying HTTP transport library not to retry, since
# we are handling retry logic ourselves.
httplib2.RETRIES = 1
# Maximum number of times to retry before giving up.
MAX_RETRIES = 10
# Always retry when these exceptions are raised.
RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError, httplib.NotConnected,
httplib.IncompleteRead, httplib.ImproperConnectionState,
httplib.CannotSendRequest, httplib.CannotSendHeader,
httplib.ResponseNotReady, httplib.BadStatusLine,)
# Always retry when an apiclient.errors.HttpError with one of these status
# codes is raised.
RETRIABLE_STATUS_CODES = (500, 502, 503, 504,)
# The message associated with the HTTP 401 error that's returned when a request
# is authorized by a user whose account is not associated with a YouTube
# content owner.
INVALID_CREDENTIALS = "Invalid Credentials"
# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains
# the OAuth 2.0 information for this application, including its client_id and
# client_secret. You can acquire an OAuth 2.0 client ID and client secret from
# the Google Developers Console at
# https://console.developers.google.com/.
# See the "Registering your application" instructions for an explanation
# of how to find these values:
# https://developers.google.com/youtube/partner/guides/registering_an_application
# For more information about using OAuth2 to access Google APIs, please visit:
# https://developers.google.com/accounts/docs/OAuth2
# For more information about the client_secrets.json file format, please visit:
# https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
CLIENT_SECRETS_FILE = "client_secrets.json"
# The local file used to store the cached OAuth 2 credentials after going
# through a one-time browser-based login.
CACHED_CREDENTIALS_FILE = "%s-oauth2.json" % sys.argv[0]
YOUTUBE_SCOPES = (
# An OAuth 2 access scope that allows for full read/write access.
"https://www.googleapis.com/auth/youtube",
# A scope that grants access to YouTube Partner API functionality.
"https://www.googleapis.com/auth/youtubepartner",)
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
YOUTUBE_CONTENT_ID_API_SERVICE_NAME = "youtubePartner"
YOUTUBE_CONTENT_ID_API_VERSION = "v1"
# Helpful message to display if the CLIENT_SECRETS_FILE is missing.
MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0
To make this sample run you need to populate the client_secrets.json file at:
%s
with information from the Developers Console
https://console.developers.google.com/
For more information about the client_secrets.json file format, please visit:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
CLIENT_SECRETS_FILE))
def parse_options():
parser = OptionParser()
parser.add_option("--file", dest="file", help="Video file to upload")
parser.add_option("--title", dest="title", help="Video title",
default="Test Title")
parser.add_option("--description", dest="description",
help="Video description",
default="Test Description")
parser.add_option("--category", dest="category",
help="Numeric video category. " +
"See https://developers.google.com/youtube/v3/docs/videoCategories/list",
default="22")
parser.add_option("--keywords", dest="keywords",
help="Video keywords, comma separated", default="")
parser.add_option("--privacyStatus", dest="privacyStatus",
help="Video privacy status: public, private or unlisted",
default="public")
parser.add_option("--policyId", dest="policyId",
help="Optional id of a saved claim policy")
parser.add_option("--channelId", dest="channelId",
help="Id of the channel to upload to. Must be managed by your CMS account")
(options, args) = parser.parse_args()
return options
def get_authenticated_services():
flow = flow_from_clientsecrets(
CLIENT_SECRETS_FILE,
scope=" ".join(YOUTUBE_SCOPES),
message=MISSING_CLIENT_SECRETS_MESSAGE
)
storage = Storage(CACHED_CREDENTIALS_FILE)
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = run(flow, storage)
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
http=credentials.authorize(httplib2.Http()))
youtube_partner = build(YOUTUBE_CONTENT_ID_API_SERVICE_NAME,
YOUTUBE_CONTENT_ID_API_VERSION, http=credentials.authorize(httplib2.Http()))
return (youtube, youtube_partner)
def get_content_owner_id(youtube_partner):
try:
content_owners_list_response = youtube_partner.contentOwners().list(
fetchMine=True
).execute()
except HttpError, e:
if INVALID_CREDENTIALS in e.content:
logging.error("Your request is not authorized by a Google Account that "
"is associated with a YouTube content owner. Please delete '%s' and "
"re-authenticate with an account that is associated "
"with a content owner." % CACHED_CREDENTIALS_FILE)
exit(1)
else:
raise
# This returns the CMS user id of the first entry returned
# by youtubePartner.contentOwners.list()
# See https://developers.google.com/youtube/partner/docs/v1/contentOwners/list
# Normally this is what you want, but if you authorize with a Google Account
# that has access to multiple YouTube content owner accounts, you need to
# iterate through the results.
return content_owners_list_response["items"][0]["id"]
def upload(youtube, content_owner_id, options):
if options.keywords:
tags = options.keywords.split(",")
else:
tags = None
insert_request = youtube.videos().insert(
onBehalfOfContentOwner=content_owner_id,
onBehalfOfContentOwnerChannel=options.channelId,
part="snippet,status",
body=dict(
snippet=dict(
title=options.title,
description=options.description,
tags=tags,
categoryId=options.category
),
status=dict(
privacyStatus=options.privacyStatus
)
),
# chunksize=-1 means that the entire file will be uploaded in a single
# HTTP request. (If the upload fails, it will still be retried where it
# left off.) This is usually a best practice, but if you're using Python
# older than 2.6 or if you're running on App Engine, you should set the
# chunksize to something like 1024 * 1024 (1 megabyte).
media_body=MediaFileUpload(options.file, chunksize=-1, resumable=True)
)
response = None
error = None
retry = 0
duration_seconds=0
while response is None:
try:
logging.debug("Uploading file...")
start_seconds = time.time()
status, response = insert_request.next_chunk()
delta_seconds = time.time() - start_seconds
duration_seconds += delta_seconds
if "id" in response:
return (response["id"], duration_seconds)
else:
logging.error("The upload failed with an unexpected response: %s" %
response)
exit(1)
except HttpError, e:
if e.resp.status in RETRIABLE_STATUS_CODES:
error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status,
e.content)
else:
raise
except RETRIABLE_EXCEPTIONS, e:
error = "A retriable error occurred: %s" % e
if error is not None:
logging.error(error)
retry += 1
if retry > MAX_RETRIES:
logging.error("No longer attempting to retry.")
exit(1)
max_sleep = 2 ** retry
sleep_seconds = random.random() * max_sleep
logging.debug("Sleeping %f seconds and then retrying..." % sleep_seconds)
time.sleep(sleep_seconds)
def create_asset(youtube_partner, content_owner_id, title, description):
# This creates a new asset corresponding to a video on the web.
# The asset is linked to the corresponding YouTube video via a
# claim that will be created later.
body = dict(
type="web",
metadata=dict(
title=title,
description=description
)
)
assets_insert_response = youtube_partner.assets().insert(
onBehalfOfContentOwner=content_owner_id,
body=body
).execute()
return assets_insert_response["id"]
def set_asset_ownership(youtube_partner, content_owner_id, asset_id):
# This specifies that content_owner_id owns 100% of the asset worldwide.
# Adjust as needed.
body = dict(
general=[dict(
owner=content_owner_id,
ratio=100,
type="exclude",
territories=[]
)]
)
youtube_partner.ownership().update(
onBehalfOfContentOwner=content_owner_id,
assetId=asset_id,
body=body
).execute()
def claim_video(youtube_partner, content_owner_id, asset_id, video_id,
policy_id):
# policy_id can be set to the id of an existing policy, which can be obtained
# via youtubePartner.policies.list()
# See https://developers.google.com/youtube/partner/docs/v1/policies/list
# If you later update that existing policy, the claim will also be updated.
if policy_id:
policy = dict(
id=policy_id
)
# If policy_id is not provided, a new inline policy is created.
else:
policy = dict(
rules=[dict(
action="monetize"
)]
)
body = dict(
assetId=asset_id,
videoId=video_id,
policy=policy,
contentType="audiovisual"
)
claims_insert_response = youtube_partner.claims().insert(
onBehalfOfContentOwner=content_owner_id,
body=body
).execute()
return claims_insert_response["id"]
def set_advertising_options(youtube_partner, content_owner_id, video_id):
# This enables the true view ad format for the given video.
# Adjust as needed.
body = dict(
adFormats=["trueview_instream"]
)
youtube_partner.videoAdvertisingOptions().update(
videoId=video_id,
onBehalfOfContentOwner=content_owner_id,
body=body
).execute()
if __name__ == '__main__':
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
options = parse_options()
if options.file is None or not os.path.exists(options.file):
logging.error("Please specify a valid file using the --file= parameter.")
exit(1)
# The channel ID looks something like "UC..." and needs to correspond to a
# channel managed by the YouTube content owner authorizing the request.
# youtube.channels.list(part="snippet", managedByMe=true,
# onBehalfOfContentOwner=*CONTENT_OWNER_ID*)
# can be used to retrieve a list of managed channels and their channel IDs.
# See https://developers.google.com/youtube/v3/docs/channels/list
if options.channelId is None:
logging.error("Please specify a channel ID via the --channelId= parameter.")
exit(1)
(youtube, youtube_partner) = get_authenticated_services()
content_owner_id = get_content_owner_id(youtube_partner)
logging.info("Authorized by content owner ID '%s'." % content_owner_id)
(video_id, duration_seconds) = upload(youtube, content_owner_id, options)
logging.info("Successfully uploaded video ID '%s'." % video_id)
file_size_bytes = os.path.getsize(options.file)
logging.debug("Uploaded %d bytes in %0.2f seconds (%0.2f megabytes/second)." %
(file_size_bytes, duration_seconds,
(file_size_bytes / (1024 * 1024)) / duration_seconds))
asset_id = create_asset(youtube_partner, content_owner_id,
options.title, options.description)
logging.info("Created new asset ID '%s'." % asset_id)
set_asset_ownership(youtube_partner, content_owner_id, asset_id)
logging.info("Successfully set asset ownership.")
claim_id = claim_video(youtube_partner, content_owner_id, asset_id,
video_id, options.policyId)
logging.info("Successfully claimed video.")
set_advertising_options(youtube_partner, content_owner_id, video_id)
logging.info("Successfully set advertising options.")
logging.info("All done!")
还有一个更新的脚本
#!/usr/bin/python
import httplib
import httplib2
import os
import random
import sys
import time
from apiclient.discovery import build
from apiclient.errors import HttpError
from apiclient.http import MediaFileUpload
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow
# Explicitly tell the underlying HTTP transport library not to retry, since
# we are handling retry logic ourselves.
httplib2.RETRIES = 1
# Maximum number of times to retry before giving up.
MAX_RETRIES = 10
# Always retry when these exceptions are raised.
RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError, httplib.NotConnected,
httplib.IncompleteRead, httplib.ImproperConnectionState,
httplib.CannotSendRequest, httplib.CannotSendHeader,
httplib.ResponseNotReady, httplib.BadStatusLine)
# Always retry when an apiclient.errors.HttpError with one of these status
# codes is raised.
RETRIABLE_STATUS_CODES = [500, 502, 503, 504]
# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains
# the OAuth 2.0 information for this application, including its client_id and
# client_secret. You can acquire an OAuth 2.0 client ID and client secret from
# the Google Developers Console at
# https://console.developers.google.com/.
# Please ensure that you have enabled the YouTube Data API for your project.
# For more information about using OAuth2 to access the YouTube Data API, see:
# https://developers.google.com/youtube/v3/guides/authentication
# For more information about the client_secrets.json file format, see:
# https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
CLIENT_SECRETS_FILE = "client_secrets.json"
# This OAuth 2.0 access scope allows an application to upload files to the
# authenticated user's YouTube channel, but doesn't allow other types of access.
YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube.upload"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
# This variable defines a message to display if the CLIENT_SECRETS_FILE is
# missing.
MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0
To make this sample run you will need to populate the client_secrets.json file
found at:
%s
with information from the Developers Console
https://console.developers.google.com/
For more information about the client_secrets.json file format, please visit:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
CLIENT_SECRETS_FILE))
VALID_PRIVACY_STATUSES = ("public", "private", "unlisted")
def get_authenticated_service(args):
flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
scope=YOUTUBE_UPLOAD_SCOPE,
message=MISSING_CLIENT_SECRETS_MESSAGE)
storage = Storage("%s-oauth2.json" % sys.argv[0])
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = run_flow(flow, storage, args)
return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
http=credentials.authorize(httplib2.Http()))
def initialize_upload(youtube, options):
tags = None
if options.keywords:
tags = options.keywords.split(",")
body=dict(
snippet=dict(
title=options.title,
description=options.description,
tags=tags,
categoryId=options.category
),
status=dict(
privacyStatus=options.privacyStatus
)
)
# Call the API's videos.insert method to create and upload the video.
insert_request = youtube.videos().insert(
part=",".join(body.keys()),
body=body,
# The chunksize parameter specifies the size of each chunk of data, in
# bytes, that will be uploaded at a time. Set a higher value for
# reliable connections as fewer chunks lead to faster uploads. Set a lower
# value for better recovery on less reliable connections.
#
# Setting "chunksize" equal to -1 in the code below means that the entire
# file will be uploaded in a single HTTP request. (If the upload fails,
# it will still be retried where it left off.) This is usually a best
# practice, but if you're using Python older than 2.6 or if you're
# running on App Engine, you should set the chunksize to something like
# 1024 * 1024 (1 megabyte).
media_body=MediaFileUpload(options.file, chunksize=-1, resumable=True)
)
resumable_upload(insert_request)
# This method implements an exponential backoff strategy to resume a
# failed upload.
def resumable_upload(insert_request):
response = None
error = None
retry = 0
while response is None:
try:
print "Uploading file..."
status, response = insert_request.next_chunk()
if 'id' in response:
print "Video id '%s' was successfully uploaded." % response['id']
else:
exit("The upload failed with an unexpected response: %s" % response)
except HttpError, e:
if e.resp.status in RETRIABLE_STATUS_CODES:
error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status,
e.content)
else:
raise
except RETRIABLE_EXCEPTIONS, e:
error = "A retriable error occurred: %s" % e
if error is not None:
print error
retry += 1
if retry > MAX_RETRIES:
exit("No longer attempting to retry.")
max_sleep = 2 ** retry
sleep_seconds = random.random() * max_sleep
print "Sleeping %f seconds and then retrying..." % sleep_seconds
time.sleep(sleep_seconds)
if __name__ == '__main__':
argparser.add_argument("--file", required=True, help="Video file to upload")
argparser.add_argument("--title", help="Video title", default="Test Title")
argparser.add_argument("--description", help="Video description",
default="Test Description")
argparser.add_argument("--category", default="22",
help="Numeric video category. " +
"See https://developers.google.com/youtube/v3/docs/videoCategories/list")
argparser.add_argument("--keywords", help="Video keywords, comma separated",
default="")
argparser.add_argument("--privacyStatus", choices=VALID_PRIVACY_STATUSES,
default=VALID_PRIVACY_STATUSES[0], help="Video privacy status.")
args = argparser.parse_args()
if not os.path.exists(args.file):
exit("Please specify a valid file using the --file= parameter.")
youtube = get_authenticated_service(args)
try:
initialize_upload(youtube, args)
except HttpError, e:
print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
我想将 claim 和货币化功能从旧脚本转换为新脚本,但尚未弄清楚如何执行此操作。我认为对于经验丰富的 Python/Google API 程序员来说这将是一件轻而易举的事。你能帮忙吗?
我尝试了一些基于改进功能和重写流程的合并,但到目前为止还没有奏效
最佳答案
除非您是直接的 YouTube 合作伙伴,否则无法使用 API 获利功能,多 channel 网络不受支持。
关于python - 合并两个 YouTube API 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34865683/
我正在处理一组标记为 160 个组的 173k 点。我想通过合并最接近的(到 9 或 10 个组)来减少组/集群的数量。我搜索过 sklearn 或类似的库,但没有成功。 我猜它只是通过 knn 聚类
我有一个扁平数字列表,这些数字逻辑上以 3 为一组,其中每个三元组是 (number, __ignored, flag[0 or 1]),例如: [7,56,1, 8,0,0, 2,0,0, 6,1,
我正在使用 pipenv 来管理我的包。我想编写一个 python 脚本来调用另一个使用不同虚拟环境(VE)的 python 脚本。 如何运行使用 VE1 的 python 脚本 1 并调用另一个 p
假设我有一个文件 script.py 位于 path = "foo/bar/script.py"。我正在寻找一种在 Python 中通过函数 execute_script() 从我的主要 Python
这听起来像是谜语或笑话,但实际上我还没有找到这个问题的答案。 问题到底是什么? 我想运行 2 个脚本。在第一个脚本中,我调用另一个脚本,但我希望它们继续并行,而不是在两个单独的线程中。主要是我不希望第
我有一个带有 python 2.5.5 的软件。我想发送一个命令,该命令将在 python 2.7.5 中启动一个脚本,然后继续执行该脚本。 我试过用 #!python2.7.5 和http://re
我在 python 命令行(使用 python 2.7)中,并尝试运行 Python 脚本。我的操作系统是 Windows 7。我已将我的目录设置为包含我所有脚本的文件夹,使用: os.chdir("
剧透:部分解决(见最后)。 以下是使用 Python 嵌入的代码示例: #include int main(int argc, char** argv) { Py_SetPythonHome
假设我有以下列表,对应于及时的股票价格: prices = [1, 3, 7, 10, 9, 8, 5, 3, 6, 8, 12, 9, 6, 10, 13, 8, 4, 11] 我想确定以下总体上最
所以我试图在选择某个单选按钮时更改此框架的背景。 我的框架位于一个类中,并且单选按钮的功能位于该类之外。 (这样我就可以在所有其他框架上调用它们。) 问题是每当我选择单选按钮时都会出现以下错误: co
我正在尝试将字符串与 python 中的正则表达式进行比较,如下所示, #!/usr/bin/env python3 import re str1 = "Expecting property name
考虑以下原型(prototype) Boost.Python 模块,该模块从单独的 C++ 头文件中引入类“D”。 /* file: a/b.cpp */ BOOST_PYTHON_MODULE(c)
如何编写一个程序来“识别函数调用的行号?” python 检查模块提供了定位行号的选项,但是, def di(): return inspect.currentframe().f_back.f_l
我已经使用 macports 安装了 Python 2.7,并且由于我的 $PATH 变量,这就是我输入 $ python 时得到的变量。然而,virtualenv 默认使用 Python 2.6,除
我只想问如何加快 python 上的 re.search 速度。 我有一个很长的字符串行,长度为 176861(即带有一些符号的字母数字字符),我使用此函数测试了该行以进行研究: def getExe
list1= [u'%app%%General%%Council%', u'%people%', u'%people%%Regional%%Council%%Mandate%', u'%ppp%%Ge
这个问题在这里已经有了答案: Is it Pythonic to use list comprehensions for just side effects? (7 个答案) 关闭 4 个月前。 告
我想用 Python 将两个列表组合成一个列表,方法如下: a = [1,1,1,2,2,2,3,3,3,3] b= ["Sun", "is", "bright", "June","and" ,"Ju
我正在运行带有最新 Boost 发行版 (1.55.0) 的 Mac OS X 10.8.4 (Darwin 12.4.0)。我正在按照说明 here构建包含在我的发行版中的教程 Boost-Pyth
学习 Python,我正在尝试制作一个没有任何第 3 方库的网络抓取工具,这样过程对我来说并没有简化,而且我知道我在做什么。我浏览了一些在线资源,但所有这些都让我对某些事情感到困惑。 html 看起来
我是一名优秀的程序员,十分优秀!