google存储api在python中的put文件问题

2024-06-16 12:13:16 发布

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

我试图上传一个文件到谷歌存储,但我的代码冻结,没有响应。请帮帮我。

霉菌:

def PutFile(self,filename):
    conn = httplib.HTTPConnection("%s.commondatastorage.googleapis.com" % self.bucket)
    conn.set_debuglevel(2)

    dd = "%s" % datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT")
    strToSign = "PUT\n"+"\nimage/jpeg\n"+dd+"\nx-goog-acl:public-read\n/%s/x.jpg" % self.bucket
    f = open(filename,"r")
    m = hashlib.md5()
    m.update(f.read())
    h = m.hexdigest()
    sig = base64.b64encode(hmac.new(self.secret, strToSign, hashlib.sha1).digest())
    total = os.path.getsize(filename)

    header = {"Date":dd,"x-goog-acl":"public-read","Content-MD5":h,'Content-Length':total,'Content-Type':'image/jpeg','Authorization':"GOOG1 %s:%s" % (self.key,sig)}


    r1 = conn.getresponse()
    print r1.status, r1.reason
    print r1.read()
    conn.close()

Tags: selfreaddatetimebucketcontentpublicfilenameconn
2条回答

我自己解决问题:)我的代码:

        conn = httplib.HTTPConnection("mustafa-yontar.commondatastorage.googleapis.com")
        conn.set_debuglevel(2)
        f = open(filename,"r")
        m = hashlib.md5()
        m.update(f.read())
        h = m.hexdigest()
        has = h
        dd = "%s" % datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT")
        strToSign = "PUT\n"+h+"\n\n"+dd+"\nx-goog-acl:public-read\n/mustafa-yontar/x.jpg"

        sig = base64.b64encode(hmac.new(self.secret, strToSign, hashlib.sha1).digest())
        total = os.path.getsize(filename)

        header = {"Date":dd,"x-goog-acl":"public-read","Content-MD5":h,'Content-Length':total,'Authorization':"GOOG1 %s:%s" % (self.key,sig)}

        conn.putrequest('PUT', "/x.jpg")
        for h in header:
            conn.putheader(h, header[h])
        conn.endheaders()
        bytess = open('x.jpg', 'rb').read()
        f = StringIO(bytess)
        f.seek(0)


        while True:
            bytes = f.read(1024)
            if not bytes: break

            length = len(bytes)
            conn.send('%X\r\n' % length)
            conn.send(bytes + '\r\n')
        conn.send('0\r\n\r\n')

        #errcode, errmsg, headers = conn.getresponse()
        #h.close()


        #conn.request("PUT","/mustafa-yontar/x.jpg",f.read(),header)
        r1 = conn.getresponse()
        print r1.status, r1.reason
        print r1.read()
        conn.close()
        print has

我知道这更多的是一个评论,而不是对你的问题的回答,但我把这个作为一个答案,因为我还不能评论。在

如果你能缩小函数中挂起它的地方,那真的会有帮助。尽管添加print函数/语句会稍微改变内存的状态,但还是值得一试,因为挂起的一个可能原因是您正在进行的网络调用。在

还有-听起来很简单,但是你确定你在网络上并且能够访问Google存储站点吗?在

相关问题 更多 >