GAE运行Python脚本和GCE权限

2024-04-20 04:31:26 发布

您现在位置:Python中文网/ 问答频道 /正文

  1. GAE需要某种WSGI(https://cloud.google.com/appengine/docs/python/tools/webapp/running)吗?这像HTTPD的CGI配置吗? 也就是说,在app.yaml中,我必须script.app并引用app到wsgi/webapp对象?

  2. 正在尝试使用AppAssertionCredentials从GAE到GCE的身份验证。 我做了另一个脚本,这个片段在其中工作:

credentials = AppAssertionCredentials( scope='https://www.googleapis.com/auth/compute') auth_http = credentials.authorize(httplib2.Http()) compute = discovery.build('compute', 'v1', http=auth_http)

我现在要做的是使用restapi从GAE创建GCE快照。 我不知道如何为我的POST引用compute对象,以使auth正常工作(现在未经授权)。在

这是我的脚本(由于测试,import太多):

import requests
import urllib2
import logging
import sys
import argparse
import httplib2
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client import tools
from oauth2client.tools import run_flow
from oauth2client.appengine import AppAssertionCredentials
from google.appengine.api import memcache
import datetime
import httplib2
import json
import logging
from pprint import pformat
from apiclient import discovery
from google.appengine.api import memcache
from oauth2client.appengine import AppAssertionCredentials
import cgi
from google.appengine.api import users
import urllib
from google.appengine.api import users
from google.appengine.ext import ndb
import time

PROJECT = "testprojgce"
ZONE = "europe-west1-b"


### OAuth2

credentials = AppAssertionCredentials(
scope='https://www.googleapis.com/auth/compute')
auth_http = credentials.authorize(httplib2.Http())
compute = discovery.build('compute', 'v1', http=auth_http)


# Create snapshot
createsnapurl= "https://www.googleapis.com/compute/v1/projects/"+PROJECT+"/zones/"+ZONE+"/disks/testdisk1/createSnapshot"
req=requests.post(createsnapurl)  

Tags: fromhttpsimportcomauthapihttpgoogle
1条回答
网友
1楼 · 发布于 2024-04-20 04:31:26

1)据我所知,实际上需要一个WSGI对象,因为它是应用程序与服务器环境通信的方式。使用Django、Flask、webapp2或其他框架可以很容易地获得这个对象,因此应该不会太难获得。看看:

https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/appengine

对于大量的GAE配置示例。在

2)现在建议使用应用程序默认凭据代替AppAssertion凭据。在

https://developers.google.com/identity/protocols/application-default-credentials

它更容易使用,并且可以无缝地工作在GAE、GCE(假设您创建了具有正确作用域的实例)、MVMs。它也可以在您的本地环境中工作,可以使用从gcloud init获得的默认“user”帐户,也可以将GOOGLE_APPLICATION_CREDENTIALS环境变量指向JSON服务帐户凭据。在本地,我通常建议下载一个JSON服务帐户并将该环境变量指向它,因为不是每个API都支持用户帐户。在

credentials = GoogleCredentials.get_application_default()
compute_service = discovery.build(
    'compute', 'v1', credentials=credentials)

注意对于大多数API,您不需要指定作用域,因为它是自动注入的,但是如果您缺少范围问题,请尝试使用'created\u作用域'方法。在

最后,您几乎永远不需要使用像请求这样的东西来直接与restapi交互,这是客户机库的重点。它确保您的http请求被正确授权,并且您使用语言级方法而不是URL字符串。相反,做一些类似的事情:

^{pr2}$

这可能不是确切的语法,如果你不能让它工作,请留下评论,我会设法解决它。在

相关问题 更多 >