首页 > 解决方案 > 我正在尝试使用带有 python 的 Youtube API 上传 youtube 视频

问题描述

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% 并且不完整。我剪掉了错误信息以便发布这个。

标签: pythonpython-3.xanacondayoutube-data-api

解决方案


正如我在上面的一条评论中已经提到的那样,我怀疑您正在一台至少安装了两个 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

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

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


上面的功能警告get_googleapiclient_version:使用pkg_resources不是获得包版本的百分百可靠的方法。在任何情况下,以下代码都会打印 的路径googleapiclient

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

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


推荐阅读