我正在尝试构建小函数(稍后部署到云函数(,以将BAK文件恢复到云sql。此函数将由cron触发。当我读到关于授权这个API的文档时,我有点不知所措:https://cloud.google.com/sql/docs/sqlserver/import-export/importing#importing_data_from_a_bak_file_in
已经创建了包括此角色的服务帐户:云SQL管理员、存储管理员、存储对象管理员、存储Object Viewer,并在创建云功能时从下拉列表中选择该服务帐户,但不起作用。
在阅读以下内容后,还尝试生成API密钥:https://cloud.google.com/sql/docs/sqlserver/admin-api/how-tos/authorizing
所以我的POST url变成了这样:
https://www.googleapis.com/sql/v1beta4/projects/project-id/instances/instance-id/import?key=generatedAPIKey
但仍然出现错误:
"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"errors": [
{
"message": "Login Required.",
"domain": "global",
"reason": "required",
"location": "Authorization",
"locationType": "header"
}
],
"status": "UNAUTHENTICATED"
}
}
我需要使用Oauth 2吗?这是我在云功能中的代码:
import http.client
import mimetypes
def restore_bak(request):
conn = http.client.HTTPSConnection("www.googleapis.com")
payload = "{rn "importContext":rn {rn "fileType": "BAK",rn "uri": "gs://{bucket_name}/{backup_name}.bak",rn "database": "{database_name}"rn }rn}rn"
headers = {
'Content-Type': 'application/json'
}
conn.request("POST", "/sql/v1beta4/projects/{project_id}/instances/{instance_name}/import", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
return(data.decode("utf-8"))
这看起来像python,所以我建议使用python的发现客户端库。这个库为SQL管理API提供了一个方便的包装器:
# Construct the service object for the interacting with the Cloud SQL Admin API.
service = discovery.build('sqladmin', 'v1beta4', http=http)
req = service.instances().list(project="PROJECT_ID")
resp = req.execute()
print json.dumps(resp, indent=2)
默认情况下,此库使用";应用程序默认证书(ADC(";从环境中获取凭据的策略。
您还可以手动验证您的请求(例如,如果您想使用asyncio(,方法是创建oauth2令牌并将其设置为请求中的标头。最简单的方法是使用googleauth包获取ADC并将其设置为头:
import google.auth
import google.auth.transport.requests
credentials, project_id = google.auth.default()
credentials.refresh(google.auth.transport.requests.Request())
headers = {
"Authorization": "Bearer {}".format(credentials.token),
"Content-Type": "application/json"
}