为了提高我的Python技能,我尝试阅读并理解Google API Python client的源代码。
但我陷入了困境,尽管四处搜索,我无法理解代码的特定部分的工作。了解如何在Python中使用Google API客户端库
我做了一个小程序,以证明部分:
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 repository以及其code documentation,但一直没有找到有用的东西。
这里是我到目前为止已经试过:
通过查看文件discovery.py
,build()
返回函数build_from_document()
,这反过来又返回类Resource()
的一个实例的结果的功能。
但现在有一个死胡同,因为类Resource()
没有任何方法称为files()
。
那么,如何找到这些方法的内部运作方式files()
,get()
,list()
等?
但'Resource'类我的钥匙似乎有方法动态方法添加到自身。我会从那里开始。 – Jasper
@Jasper我绝对没有任何关于如何工作的线索(我是Python的初学者)。你能否详细解释一下更详细的情况? –
https://github.com/google/google-api-python-client/blob/master/googleapiclient/discovery.py#L967这是我猜测的相关函数。添加类似“'attr_name,value'”和代码以打印栈跟踪(https://docs.python.org/2/library/traceback.html)(或者使用您最喜欢的调试器)来查看谁在调用此函数函数添加'文件()','get()'等 – Jasper