【问题标题】:I am trying to upload a youtube video using the Youtube API with python我正在尝试使用带有 python 的 Youtube API 上传 youtube 视频
【发布时间】:2020-11-23 11:47:48
【问题描述】:
def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = "C:/Users/virto/Desktop/Projekt/client_Secrets.json"

    # 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)

    request = youtube.videos().insert(
        part="snippet,status",
        body={
          "snippet": {
            "categoryId": "22",
            "description": "",
            "title": "Memes Compilation."
          },
          "status": {
            "privacyStatus": "public"
          }
        },
        
        # TODO: For this request to work, you must replace "YOUR_FILE"
        #       with a pointer to the actual file you are uploading.
        media_body=MediaFileUpload("C:/Users/virto/Desktop/Projekt/Memes Compilation.mp4")
    )
    response = request.execute()

    print(response)

这是我的代码。我收到如下错误消息。


SSLWantWriteError                         Traceback (most recent call last)
<ipython-input-1-d6d6f2ce7763> in <module>
    102         os.remove('C:/Users/virto/Desktop/Projekt/' + str(i))
    103 
--> 104 Final()
    105 

<ipython-input-1-d6d6f2ce7763> in Final()
     97     Schnitt()
     98     print('Upload starting')
---> 99     main()
    100     print('Löschen...')
    101     for i in Memes:

<ipython-input-1-d6d6f2ce7763> in main()
     87         media_body=MediaFileUpload("C:/Users/virto/Desktop/Projekt/Memes Compilation.mp4")
     88     )
---> 89     response = request.execute()
     90 
     91     print(response)

~\AppData\Roaming\Python\Python38\site-packages\googleapiclient\_helpers.py in positional_wrapper(*args, **kwargs)
    132                 elif positional_parameters_enforcement == POSITIONAL_WARNING:
    133                     logger.warning(message)
--> 134             return wrapped(*args, **kwargs)
    135 
    136         return positional_wrapper

~\AppData\Roaming\Python\Python38\site-packages\googleapiclient\http.py in execute(self, http, num_retries)
    890 
    891         # Handle retries for server-side errors.
--> 892         resp, content = _retry_request(
    893             http,
    894             num_retries,

~\AppData\Roaming\Python\Python38\site-packages\googleapiclient\http.py in _retry_request(http, num_retries, req_type, sleep, rand, uri, method, *args, **kwargs)
    202         if exception:
    203             if retry_num == num_retries:
--> 204                 raise exception
    205             else:
    206                 continue

~\AppData\Roaming\Python\Python38\site-packages\googleapiclient\http.py in _retry_request(http, num_retries, req_type, sleep, rand, uri, method, *args, **kwargs)
    175         try:
    176             exception = None
--> 177             resp, content = http.request(uri, method, *args, **kwargs)
    178         # Retry on SSL errors and socket timeout errors.
    179         except _ssl_SSLError as ssl_error:

~\anaconda3\lib\site-packages\google_auth_httplib2.py in request(self, uri, method, body, headers, **kwargs)
    198 
    199         # Make the request.
--> 200         response, content = self.http.request(
    201             uri, method, body=body, headers=request_headers, **kwargs)
    202 

~\AppData\Roaming\Python\Python38\site-packages\httplib2\__init__.py in request(self, uri, method, body, headers, redirections, connection_type)
   1983                     content = b""
   1984                 else:
-> 1985                     (response, content) = self._request(
   1986                         conn,
   1987                         authority,

~\AppData\Roaming\Python\Python38\site-packages\httplib2\__init__.py in _request(self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey)
   1648             auth.request(method, request_uri, headers, body)
   1649 
-> 1650         (response, content) = self._conn_request(
   1651             conn, request_uri, method, body, headers
   1652         )

~\AppData\Roaming\Python\Python38\site-packages\httplib2\__init__.py in _conn_request(self, conn, request_uri, method, body, headers)
   1556                 if conn.sock is None:
   1557                     conn.connect()
-> 1558                 conn.request(method, request_uri, body, headers)
   1559             except socket.timeout:
   1560                 conn.close()

~\anaconda3\lib\http\client.py in request(self, method, url, body, headers, encode_chunked)
   1238                 encode_chunked=False):
   1239         """Send a complete request to the server."""
-> 1240         self._send_request(method, url, body, headers, encode_chunked)
   1241 
   1242     def _send_request(self, method, url, body, headers, encode_chunked):

~\anaconda3\lib\http\client.py in _send_request(self, method, url, body, headers, encode_chunked)
   1284             # default charset of iso-8859-1.
   1285             body = _encode(body, 'body')
-> 1286         self.endheaders(body, encode_chunked=encode_chunked)
   1287 
   1288     def getresponse(self):

~\anaconda3\lib\http\client.py in endheaders(self, message_body, encode_chunked)
   1233         else:
   1234             raise CannotSendHeader()
-> 1235         self._send_output(message_body, encode_chunked=encode_chunked)
   1236 
   1237     def request(self, method, url, body=None, headers={}, *,

~\anaconda3\lib\http\client.py in _send_output(self, message_body, encode_chunked)
   1043                     chunk = f'{len(chunk):X}\r\n'.encode('ascii') + chunk \
   1044                         + b'\r\n'
-> 1045                 self.send(chunk)
   1046 
   1047             if encode_chunked and self._http_vsn == 11:

~\anaconda3\lib\http\client.py in send(self, data)
    965             return
    966         try:
--> 967             self.sock.sendall(data)
    968         except TypeError:
    969             if isinstance(data, collections.abc.Iterable):

~\anaconda3\lib\ssl.py in sendall(self, data, flags)
   1202                 amount = len(byte_view)
   1203                 while count < amount:
-> 1204                     v = self.send(byte_view[count:])
   1205                     count += v
   1206         else:

~\anaconda3\lib\ssl.py in send(self, data, flags)
   1171                     "non-zero flags not allowed in calls to send() on %s" %
   1172                     self.__class__)
-> 1173             return self._sslobj.write(data)
   1174         else:
   1175             return super().send(data, flags)

SSLWantWriteError: The operation did not complete (write) (_ssl.c:2457)

非常感谢您的帮助。在我的 youtube 帐户中,有一个 youtube 视频帖子是在运行此代码后制作的。可悲的是,它的上传率为 0% 且不完整。为了发布这个,我剪掉了错误信息。

【问题讨论】:

  • 能否发布您正在使用的 Google API Client Library for Python 版本? (例如通过发出以下命令:pip show google-api-python-client。)
  • 我正在使用版本 1.10.0(完整消息:名称:google-api-python-client 版本:1.10.0 摘要:Python 主页的 Google API 客户端库:github.com/googleapis/google-api-python-client 作者: Google LLC 作者电子邮件:googleapis-packages@google.com 许可证:Apache 2.0 位置:c:\users\virto\appdata\roaming\python\python38\site-packages 要求:httplib2、google-auth、google-auth-httplib2 , google-api-core, 六, uritemplate 要求:youtube-video-upload 注意:你可能需要重启内核才能使用更新的包。
  • 这是最新的。
  • 是否有可能您有两个不同版本的 Python 安装(和两个客户端库),而您的应用实际上运行的是较旧的客户端库?
  • 请注意,错误消息是从~/anaconda3/lib 弹出的,而不是从c:\users\virto\appdata\roaming 下的某处弹出。完整的异常堆栈跟踪会很有帮助。

标签: python python-3.x anaconda youtube-data-api


【解决方案1】:

正如我在上面的一个 cmets 中已经提到的,我怀疑您正在一台至少安装了两个 Python 的计算机上运行您的程序 - 每个都设置了自己的(单独的)用于 Python 包的 Google API 客户端库 - - 并且您的程序实际上正在运行旧版本的客户端库。

我建议在运行时验证客户端库的版本。通过在 main 函数的开头插入以下代码来做到这一点:

print('google-api-python-client version:',
       get_googleapiclient_version())

函数get_googleapiclient_version在哪里:

def get_googleapiclient_version():
    try:
        import googleapiclient
        return googleapiclient.__version__
    except AttributeError:
        import pkg_resources
        return pkg_resources.get_distribution(
              "google-api-python-client").version

显示的版本号应比 2018 年 4 月 27 日起的 1.6.7 更新。

最好始终确保您运行的是最新版本。 (在撰写本文时,1.10.0 从 7 月 15 日开始。)


上述函数get_googleapiclient_version 的警告:使用pkg_resources 并不是百分百可靠的获取包版本的方法。不管怎样,下面这段代码打印出googleapiclient的路径:

print('google-api-python-client path:',
       googleapiclient.__path__)

这可能有助于解决程序实际运行的客户端库的真正来源问题。

【讨论】:

  • 非常感谢,我会尝试一下,然后发送反馈。它指出:google-api-python-client 版本:1.10.0 这是它正在使用的路径:google-api-python-client 路径:['C:\\Users\\virto\\AppData\\Roaming\\ Python\\Python38\\site-packages\\googleapiclient']
  • 好的。下一篇:为什么错误消息是从~/anaconda3/lib 弹出而不是从C:\Users\virto\AppData\Roaming\Python\Python38 下的某个地方弹出?有些事情还是不行。请编辑您的帖子,向其中添加完整的堆栈跟踪 w.r.t。那个例外。
  • 我在这个链接上添加了完整的错误信息:appp.me/iYntfa
  • 我将 Jupyter 与 Anaconda 一起使用,因为 Numpy 无法安装在我的“经典 Python”版本上
  • 确保您安装了最新的httplib2 软件包:使用与上述相同的过程,pip show,然后是pip install --update,然后,可能是为httplib2 改编的get_googleapiclient_version 函数.我怀疑后一个包是你问题的罪魁祸首。
猜你喜欢
  • 2017-05-16
  • 2013-11-21
  • 1970-01-01
  • 1970-01-01
  • 2015-08-23
  • 2011-07-10
  • 1970-01-01
  • 1970-01-01
  • 2011-11-19
相关资源
最近更新 更多