如何从URL在Google App Engine上存储文件到Google Storage?

5 投票
2 回答
1302 浏览
提问于 2025-04-16 06:36

我想在Google App Engine上创建一个服务,用Python编写,这个服务可以接收一个图片的URL,并把它存储到Google Storage上。我已经成功通过boto或者gsutil命令行从本地文件上传,但通过URL获取文件上传却遇到了问题。我尝试使用HTTP请求(PUT,但是收到了错误的签名响应。显然我哪里做错了,但我不知道具体是哪里。

所以我想问的是:我该如何用Python在Google App Engine上从URL获取文件并存储到Google Storage呢?

这是我做的(参考了另一个回答):

class ImportPhoto(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        srow = self.response.out.write
        url = self.request.get('url')
        srow('URL: %s\n' % (url))
        image_response = urlfetch.fetch(url)
        m = md5.md5()
        m.update(image_response.content)
        hash = m.hexdigest()
        time = "%s" % datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT")
        str_to_sig = "PUT\n" + hash + "\n\n" + 
                      time + "\nx-goog-acl:public-read\n/lipis/8418.png"
        sig = base64.b64encode(hmac.new(
                                  config_credentials.GS_SECRET_ACCESS_KEY,
                                  str_to_sig, hashlib.sha1).digest())
        total = len(image_response.content) 
        srow('Size: %d bytes\n' % (total))

        header = {"Date": time,
                  "x-goog-acl": "public-read",
                  "Content-MD5": hash,
                  'Content-Length': total,
                  'Authorization': "GOOG1 %s:%s" % 
                                    (config_credentials.GS_ACCESS_KEY_ID, sig)}

        conn = httplib.HTTPConnection("lipis.commondatastorage.googleapis.com")
        conn.set_debuglevel(2)

        conn.putrequest('PUT', "/8418.png")
        for h in header:
            conn.putheader(h, header[h])
        conn.endheaders()
        conn.send(image_response.content + '\r\n')
        res = conn.getresponse()

        srow('\n\n%d: %s\n' % (res.status, res.reason))
        data = res.read()
        srow(data)
        conn.close()

而我得到的响应是:

URL: https://stackoverflow.com/users/flair/8418.png
Size: 9605 bytes

400: Bad Request
<?xml version='1.0' encoding='UTF-8'?><Error><Code>BadDigest</Code><Message>The Content-MD5 you specified did not match what we received.</Message><Details>lipis/hello.jpg</Details></Error>

2 个回答

1

Content-MD5 这个头部在 PUT 请求 中是可选的。你可以试着不加这个头部来测试一下。

另外,必需的头部有 AuthorizationDateHost。看起来你的请求缺少了 Host 这个头部。

1

你有没有看过关于如何签名请求的文档?要签名的字符串必须包含Content-MD5Content-TypeDate这些头信息,除此之外,还要包括自定义的头信息和资源路径。

撰写回答