从Twisted上传到GCS

时间:2012-12-13 16:43:23

标签: python twisted google-cloud-storage

我需要将文件从扭曲的应用程序中放入Google的云存储中。

我一直在使用亚马逊和txAWS,但现在我正在使用GCS我不确定是否存在可以让我这样做的事情吗?

是否可以将txAWS与GCS一起使用?这听起来像一个奇怪的问题但是可以将boto S3Connection与GCS一起使用,所以也许可以通过txAWS来做同样的事情。 ?

1 个答案:

答案 0 :(得分:1)

我建议将Twisted Web clientGCS JSON API一起使用。以下是列出存储桶内容的示例:

import json
from twisted.internet import reactor
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Protocol
from twisted.web.client import Agent
from twisted.web.error import Error
from twisted.web.http_headers import Headers

GCS_BASE_URL = 'https://www.googleapis.com/storage/v1beta1'
GCS_API_KEY = '<your-api-key>'
GCS_BUCKET = '<your-bucket>'

class ResponseAccumulate(Protocol):
    def __init__(self, finished):
        self.finished = finished
        self.fullbuffer = ''

    def dataReceived(self, bytes):
        print 'Received %d bytes.' % len(bytes)
        self.fullbuffer += bytes

    def connectionLost(self, reason):
        if isinstance(reason, Error):
            print 'Finished receiving body:', reason.getErrorMessage()
        else:
            parsed = json.loads(self.fullbuffer)
            print 'Bucket contents:'
            for item in parsed['items']:
              print ' ', item['id']
        self.finished.callback(None)

agent = Agent(reactor)

d = agent.request(
    'GET',
    '%s/b/%s/o?key=%s' % (GCS_BASE_URL, GCS_BUCKET, GCS_API_KEY),
    Headers({'User-Agent': ['Twisted Web Client Example']}),
    None)

def cbResponse(response):
    print 'Response received', response.code
    finished = Deferred()
    response.deliverBody(ResponseAccumulate(finished))
    return finished
d.addCallback(cbResponse)

def cbShutdown(ignored):
    reactor.stop()
d.addBoth(cbShutdown)

reactor.run()