在Python中不使用google-api-python-client访问Google Drive API(已安装应用)
我想用Python3做一个安装应用程序,来管理我谷歌账户里的Google Drive文件。
因为官方的google-api-python-client不支持Python3,所以我决定自己编写oauth2的方法,通过urlib.request来访问Google Drive的API。
我成功完成了身份验证并获取了令牌。然后我尝试按照API的说明去访问Google Drive API(复制一个文件):POST https://www.googleapis.com/drive/v2/files/fileId/copy
,用以下代码:
def copy_file(token, target_name):
print("Access Token: " + token)
url_target = "https://www.googleapis.com/drive/v2/files/0Akg4S5DP95FAdFM3VXNJbVo4TjM0MFFGVm5hWlFtU2c/copy"
request = urllib.request.Request(url_target)
request.add_header("Authorization", "OAuth" + token)
request.add_header("title", target_name)
f = urllib.request.urlopen(request)
print(f.read())
但是我只得到了404错误。
当我用Google Api Explorer测试时,一切正常:
Request
POST https://www.googleapis.com/drive/v2/files/0Akg4S5DP95FAdFM3VXNJbVo4TjM0MFFGVm5hWlFtU2c/copy?key={YOUR_API_KEY}
Content-Type: application/json
Authorization: Bearer ya29.1.AADtN_ULTFZ3jvv962bVVjAYv_GknktRMgvIGAGJPdZ5OAocQANLmN5q_UMq5cA53aqoHBkqo39wHiGM1-pg
X-JavaScript-User-Agent: Google APIs Explorer
{
"title": "copia de HiperAgenda"
}
Response
200 OK
我在代码中省略了这个?key={YOUR_API_KEY}
,我的API密钥在哪里呢?
我哪里出错了?
2 个回答
0
你在Python的实现中没有加上copy
这个请求参数的值(也就是在API浏览器中显示的"copy?key={YOUR_API_KEY}
"那部分)。
2
解决了
def copyFile(token, target_name):
print("Access Token: " + token)
url_destino = "https://www.googleapis.com/drive/v2/
files/0AilPd9i9ydNTdFc4a2lvYmZnNkNzSU1kdVFZb0syN1E/copy
?key=(YOUR_API_KEY provided by Google API Console)"
values = "{'title': '%'}" % target_name
data = values.encode('utf-8')
request = urllib.request.Request(url_destino, data, method='POST')
request.add_header("Authorization", "Bearer " + token)
request.add_header("Content-Length", len(data))
request.add_header("Content-Type", "application/json")
print(request.header_items())
f = urllib.request.urlopen(request)
print(f.read())
修复的错误:
- 我在谷歌API控制台找到了我的API密钥。
- HTTP请求的方法是'POST'。
- 令牌的值以“Bearer”开头,不要用“OAuth”(这个已经不推荐使用了)。
- 所需的参数不是请求头,而是请求的数据。
- 'data'是json格式,但实际上是二进制的。
- 需要添加头部“Content-Type: application/json”。
- 需要添加头部“Content-Length: ”。
我上传了一个Gist,里面有完整的示例,运行良好:https://gist.github.com/SalvaJ/9722045