但我被卡住了,尽管我在Google上搜索过,但我仍然无法理解代码的一个特定部分是如何工作的。
我编写了一个小程序来演示该部分:
upload.py
from __future__ import print_function
import os
import httplib2
import apiclient
import oauth2client
try:
import argparse
flags = argparse.ArgumentParser(
parents=[oauth2client.tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://www.googleapis.com/auth/drive'
CLIENT_SECRET_FILE = 'client_secret.json'
# Enter your project name here!!
APPLICATION_NAME = 'API Project'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'drive-credentials.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = oauth2client.client.flow_from_clientsecrets(
CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = oauth2client.tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = oauth2client.tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def main():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
file_service = apiclient.discovery.build('drive', 'v3', http=http).files()
results = file_service.get(
fileId="0Bw239KLrN7zoWl95Nml2ZUpsNnc").execute()
print(results)
results = file_service.list(
pageSize=10, fields="files(id, name)").execute()
print(results)
if __name__ == '__main__':
main()
在这行代码
file_service = apiclient.discovery.build('drive', 'v3', http=http).files()
中,我无法在库的源代码中找到files()
方法的定义。我也无法找到任何被称为get()
或list()
的方法。我已经阅读了库的Github存储库以及其代码文档,但没有找到任何有用的信息。
以下是我迄今为止尝试过的内容:
通过查看文件
discovery.py
,函数build()
返回build_from_document()
函数的结果,后者又返回Resource()
类的一个实例。但现在遇到了死路,因为类
Resource()
中没有任何名为files()
的方法。那么,如何找到这些方法
files()
、get()
、list()
等的内部工作原理呢?
Resource
类似乎有一些方法可以动态地向自身添加方法。我会从那里开始。 - Jasper"的内容和代码,以打印堆栈跟踪(https://docs.python.org/2/library/traceback.html)(或使用您喜欢的调试器),以查看是谁在调用此函数来添加
files()、
get()`等。 - Jasper