当前位置: 首页>>代码示例>>Python>>正文


Python BlobService.create_container方法代码示例

本文整理汇总了Python中azure.storage.BlobService.create_container方法的典型用法代码示例。如果您正苦于以下问题:Python BlobService.create_container方法的具体用法?Python BlobService.create_container怎么用?Python BlobService.create_container使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在azure.storage.BlobService的用法示例。


在下文中一共展示了BlobService.create_container方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_azure_call

# 需要导入模块: from azure.storage import BlobService [as 别名]
# 或者: from azure.storage.BlobService import create_container [as 别名]
def test_azure_call(request):
    import os
    try:
        from azure.storage import BlobService
        bs = BlobService(os.environ["AZURE_STORAGE_ACCOUNT"], os.environ["AZURE_STORAGE_ACCESS_KEY"])
        import random
        container_name = hex(int(random.random() * 1000000000))

        bs.create_container(container_name)
        bs.put_blob(container_name, 'testblob', 'hello world\n', 'BlockBlob')
        blob = bs.get_blob(container_name, 'testblob')
        if blob != 'hello world\n':
            return HttpResponse("Failed!", status = '404')
        
        bs.delete_blob(container_name, 'testblob')
        bs.delete_container(container_name)

        return HttpResponse("Succeeded!")
    except:
        try:
            import traceback
        
            return HttpResponse(traceback.format_exc() + str(os.environ.keys()))
        except:
            import traceback
            return HttpResponse(traceback.format_exc())
开发者ID:KuduApps,项目名称:PythonApp,代码行数:28,代码来源:test_urls.py

示例2: FileService

# 需要导入模块: from azure.storage import BlobService [as 别名]
# 或者: from azure.storage.BlobService import create_container [as 别名]
class FileService(Component):
    def __init__(self):
        self.blob_service = None

    def generate_blob_service(self):
        if self.blob_service is None:
            # if storage info doesn't exist in config.py upload file function stop working
            self.blob_service = BlobService(account_name=self.util.get_config("storage.azure.account_name"),
                                            account_key=self.util.get_config("storage.azure.account_key"),
                                            host_base=self.util.get_config("storage.azure.blob_service_host_base"))

    def create_container_in_storage(self, container_name, access):
        """
        create a container if doesn't exist
        :param container_name:
        :param access:
        :return:
        """
        self.generate_blob_service()
        try:
            names = map(lambda x: x.name, self.blob_service.list_containers())
            if container_name not in names:
                self.blob_service.create_container(container_name, x_ms_blob_public_access=access)
            else:
                self.log.debug("container already exsit in storage")
            return True
        except Exception as e:
            self.log.error(e)
            return False

    def upload_file_to_azure(self, stream, container_name, blob_name):
        try:
            if self.create_container_in_storage(container_name, 'container'):
                self.blob_service.put_block_blob_from_file(container_name, blob_name, stream)
                return self.blob_service.make_blob_url(container_name, blob_name)
            else:
                return None
        except Exception as e:
            self.log.error(e)
            return None

    def upload_file_to_azure_from_path(self, path, container_name, blob_name):
        try:
            if self.create_container_in_storage(container_name, 'container'):
                self.blob_service.put_block_blob_from_path(container_name, blob_name, path)
                return self.blob_service.make_blob_url(container_name, blob_name)
            else:
                return None
        except Exception as e:
            self.log.error(e)
            return None

    def delete_file_from_azure(self, container_name, blob_name):
        try:
            if self.create_container_in_storage(container_name, 'container'):
                self.blob_service.delete_blob(container_name, blob_name)
        except Exception as e:
            self.log.error(e)
            return None
开发者ID:mshubian,项目名称:open-hackathon,代码行数:61,代码来源:azure_file_service.py

示例3: AzureTransfer

# 需要导入模块: from azure.storage import BlobService [as 别名]
# 或者: from azure.storage.BlobService import create_container [as 别名]
class AzureTransfer(BaseTransfer):
    def __init__(self, account_name, account_key, container_name):
        BaseTransfer.__init__(self)
        self.account_name = account_name
        self.account_key = account_key
        self.container_name = container_name
        self.conn = BlobService(account_name=self.account_name, account_key=self.account_key)
        self.container = self.get_or_create_container(self.container_name)
        self.log.debug("AzureTransfer initialized")

    def get_metadata_for_key(self, key):
        key = fix_path(key)
        return self.list_path(key)[0]['metadata']

    def list_path(self, path):
        return_list = []
        path = fix_path(path)
        self.log.info("Asking for listing of: %r", path)
        for r in self.conn.list_blobs(self.container_name, prefix=path, delimiter="/",
                                      include="metadata"):
            entry = {"name": r.name, "size": r.properties.content_length,
                     "last_modified": dateutil.parser.parse(r.properties.last_modified),
                     "metadata": r.metadata}
            return_list.append(entry)
        return return_list

    def delete_key(self, key_name):
        key_name = fix_path(key_name)
        self.log.debug("Deleting key: %r", key_name)
        return self.conn.delete_blob(self.container_name, key_name)

    def get_contents_to_file(self, obj_key, filepath_to_store_to):
        obj_key = fix_path(obj_key)
        self.log.debug("Starting to fetch the contents of: %r to: %r", obj_key, filepath_to_store_to)
        return self.conn.get_blob_to_path(self.container_name, obj_key, filepath_to_store_to)

    def get_contents_to_string(self, obj_key):
        obj_key = fix_path(obj_key)
        self.log.debug("Starting to fetch the contents of: %r", obj_key)
        return self.conn.get_blob_to_bytes(self.container_name, obj_key), self.get_metadata_for_key(obj_key)

    def store_file_from_memory(self, key, memstring, metadata=None):
        # For whatever reason Azure requires all values to be strings at the point of sending
        metadata_to_send = dict((str(k), str(v)) for k, v in metadata.items())
        self.conn.put_block_blob_from_bytes(self.container_name, key, memstring,
                                            x_ms_meta_name_values=metadata_to_send)

    def store_file_from_disk(self, key, filepath, metadata=None):
        # For whatever reason Azure requires all values to be strings at the point of sending
        metadata_to_send = dict((str(k), str(v)) for k, v in metadata.items())
        self.conn.put_block_blob_from_path(self.container_name, key, filepath,
                                           x_ms_meta_name_values=metadata_to_send)

    def get_or_create_container(self, container_name):
        start_time = time.time()
        self.conn.create_container(container_name)
        self.log.debug("Got/Created container: %r successfully, took: %.3fs", container_name, time.time() - start_time)
        return container_name
开发者ID:Ormod,项目名称:pghoard,代码行数:60,代码来源:azure.py

示例4: main

# 需要导入模块: from azure.storage import BlobService [as 别名]
# 或者: from azure.storage.BlobService import create_container [as 别名]
def main():
    service = BlobService(
        credentials.getStorageServicesName(),
        credentials.getStorageServicesKey(),
    )

    service.create_container(CONTAINER_NAME)

    process(service, LOCAL_BLOCK_BLOB_FILES, CONNECTION_COUNTS, is_page_blob=False)
    process(service, LOCAL_PAGE_BLOB_FILES, CONNECTION_COUNTS, is_page_blob=True)
开发者ID:acht1984,项目名称:azure-sdk-for-python,代码行数:12,代码来源:blob_performance.py

示例5: main

# 需要导入模块: from azure.storage import BlobService [as 别名]
# 或者: from azure.storage.BlobService import create_container [as 别名]
def main(argv):
    options = _parse_options(argv)

    blob_service = BlobService(options[_opt_azure_acc_name], options[_opt_azure_acc_key])
    _print_container_names(blob_service)

    blob_service.create_container(options[_opt_azure_container_name])
    _print_blobs(blob_service, options[_opt_azure_container_name])

    export_dir = _export_repo(options)
    export_zip = _zip_export(export_dir)
    _upload_zip(blob_service, options[_opt_azure_container_name], export_zip)
开发者ID:manicmonkey,项目名称:export-svn-to-azure,代码行数:14,代码来源:azure_upload.py

示例6: create_container

# 需要导入模块: from azure.storage import BlobService [as 别名]
# 或者: from azure.storage.BlobService import create_container [as 别名]
def create_container(storage_account_name, container_name, storage_keys):
    """
    Creates a file share in the specified Microsoft Azure Storage account.
    A container is like a folder within a storage account
    :param storage_account_name:
    :param container_name:
    :param storage_keys:
    :return:
    """
    logging.info('Creating Container \'{0}\' in Storage account {1}'.format(container_name, storage_account_name))
    blob_svc = BlobService(account_name=storage_account_name, account_key=storage_keys.storage_service_keys.primary)
    blob_svc.create_container(container_name)
    logging.info('Creating Container \'{0}\' in Storage account {1} complete'.format(container_name, storage_account_name))
开发者ID:dominoFire,项目名称:sweeper,代码行数:15,代码来源:manager.py

示例7: connect

# 需要导入模块: from azure.storage import BlobService [as 别名]
# 或者: from azure.storage.BlobService import create_container [as 别名]
def connect(config=False):
  # Connect to the cloud service. 
  if not config: config = misc.config['_private']

  from azure.storage import BlobService
  container = 'streams'

  if not 'azure' in config:
    return None, None

  blob_service = BlobService(config['azure']['storage_account_name'], config['azure']['primary_access_key'])
  blob_service.create_container(container, x_ms_blob_public_access='container')
  return blob_service, container
开发者ID:EQ4,项目名称:DRR,代码行数:15,代码来源:cloud.py

示例8: _ensureStorageContainersExist

# 需要导入模块: from azure.storage import BlobService [as 别名]
# 或者: from azure.storage.BlobService import create_container [as 别名]
 def _ensureStorageContainersExist(self):
     """
     Creates Blob storage containers required by the service.
     """
     logger.info("Checking for existence of Blob containers.")
     account_name = self.config.getServiceStorageAccountName()
     account_key = self._getStorageAccountKey(account_name)
     blob_service = BlobService(account_name, account_key)
     name_and_access_list = [(self.config.getServicePublicStorageContainer(), 'blob'),
                             (self.config.getServiceBundleStorageContainer(), None)]
     for name, access in name_and_access_list:
         logger.info("Checking for existence of Blob container %s.", name)
         blob_service.create_container(name, x_ms_blob_public_access=access, fail_on_exist=False)
         access_info = 'private' if access is None else 'public {0}'.format(access)
         logger.info("Blob container %s is ready (access: %s).", name, access_info)
开发者ID:prags,项目名称:codalab,代码行数:17,代码来源:__init__.py

示例9: AzureBlobStorage

# 需要导入模块: from azure.storage import BlobService [as 别名]
# 或者: from azure.storage.BlobService import create_container [as 别名]
class AzureBlobStorage(StorageBase):

    def __init__(self, account_name, account_key, container_name):
        self.__container_name = container_name
        self.__blob_service = BlobService(account_name=account_name,
                                          account_key=account_key)
        self.__blob_service.create_container(container_name)

    def get(self, key, default=None):
        logger.info('get: key = %s' % key)
        return pickle.loads(self.__blob_service
                            .get_blob_to_text(self.__container_name, key))

    def set(self, key, value):
        logger.info('get: key = %s, value = %s' % (key, value))
        self.__blob_service.put_block_blob_from_text(self.__container_name,
                                                     key, pickle.dumps(value))
开发者ID:supby,项目名称:DeepSportsAnalytics,代码行数:19,代码来源:azure_storage.py

示例10: do_step

# 需要导入模块: from azure.storage import BlobService [as 别名]
# 或者: from azure.storage.BlobService import create_container [as 别名]
def do_step(context):

    settings = context.meta['settings']

    # Prepare the containers
    storage_account_name = settings["STORAGE-ACCOUNT-NAME"]
    storage_access_key = settings["STORAGE-ACCESS-KEY"]
    blob_service = BlobService(storage_account_name, storage_access_key)
    blob_service.create_container('bosh')
    blob_service.create_container(container_name='stemcell', x_ms_blob_public_access='blob')

    # Prepare the table for storing meta datas of storage account and stemcells
    table_service = TableService(storage_account_name, storage_access_key)
    table_service.create_table('stemcells')

    context.meta['settings'] = settings
    return context
开发者ID:KundanaP,项目名称:bosh-azure-template,代码行数:19,代码来源:prep_containers_and_tables.py

示例11: __init__

# 需要导入模块: from azure.storage import BlobService [as 别名]
# 或者: from azure.storage.BlobService import create_container [as 别名]
class BlobCache:
    '''
    Simplistic cache toolkit targetting an Azure Blob Service.

    name:      the name of a storage account.
    key:       the access key for the storage account.
    container: the name of the container to use.
    '''

    def __init__(self, name, key, container):
        self.container = container
        self.blobstore = BlobService(name, key)
        self.blobstore.create_container(self.container)

    def getresponse(self, cachekey):
        '''
        Get a value from the cache.

        cachekey: The key.

        Kilroy notes that this throws an exception rather than returning a 
        value on failure.
        '''
        return self.blobstore.get_blob_to_text(self.container,str2blobname(cachekey))

    def putresponse(self, cachekey, value):
        '''
        Put a value in the cache with the given key.

        cachekey: The key.

        value: The value to associate with the key.
        '''
        return self.blobstore.put_block_blob_from_text(self.container, str2blobname(cachekey), value)

    def invalidate(self, cachekey):
        '''
        Invalidate a value in the cache. Immediate. Permanent.

        cachekey: The key.
        '''
        self.blobstore.delete_blob(self.container, str2blobname(cachekey))
开发者ID:aaarendt,项目名称:ice2oceans_api,代码行数:44,代码来源:blobcache.py

示例12: AzureBackend

# 需要导入模块: from azure.storage import BlobService [as 别名]
# 或者: from azure.storage.BlobService import create_container [as 别名]
class AzureBackend(BakthatBackend):
    """Backend to handle Azure upload/download."""
    def __init__(self, conf={}, profile="default"):
        BakthatBackend.__init__(self, conf, profile)

        self.blob_service = BlobService(self.conf["account_name"], self.conf["account_key"])
       
         
        try:
            self.containe_properties =  self.blob_service.get_container_properties(self.conf["azure_container"])
        except WindowsAzureError, e:
            if type(e)==WindowsAzureMissingResourceError:
                self.containe_properties =self.blob_service.create_container(self.conf["azure_container"])
            else:
                raise e

        self.container = self.conf["azure_container"]
        self.container_key = "azure_container"
开发者ID:Arttii,项目名称:bakthat,代码行数:20,代码来源:backends.py

示例13: upload_to_blob

# 需要导入模块: from azure.storage import BlobService [as 别名]
# 或者: from azure.storage.BlobService import create_container [as 别名]
def upload_to_blob(filename):
	#uploads to azure blob storage
	blob_service = BlobService(account_name=storage_account_name, account_key=storage_account_key)
	blob_service.create_container('pubsubcat-pics')
	blob_service.put_block_blob_from_path("pubsubcat-pics", hostname + "/" + filename, 'temp/' + filename)
开发者ID:kherr9,项目名称:pubsubcat-agent,代码行数:7,代码来源:pubsubcat-agent.py

示例14: generate_and_upload

# 需要导入模块: from azure.storage import BlobService [as 别名]
# 或者: from azure.storage.BlobService import create_container [as 别名]
def generate_and_upload(gauge_factory, config, logger):
    start = datetime.datetime.now()
    twitter_followers = gauge_factory('twitter.followers')
    twitter_tweets = gauge_factory('twitter.tweets')
    fb_friends = gauge_factory('facebook.friends')
    foursq_checkins = gauge_factory('foursquare.checkins')
    klout_score = gauge_factory('klout.score')
    runkeeper_activities = gauge_factory('runkeeper.activities')
    runkeeper_calories = gauge_factory('runkeeper.calories_burned')
    runkeeper_weight = gauge_factory('runkeeper.weight')
    tmp102_celsius = gauge_factory('tmp102.te  mperature', gauge_type='hourly')
    lastfm_listened = gauge_factory('lastfm.listened')
    jawbone_sleeps = gauge_factory('jawbone.sleeps')
    jawbone_steps = gauge_factory('jawbone.steps')
    jawbone_caffeine = gauge_factory('jawbone.caffeine')

    data = {}
    data_sources = [
        # (output key, gauge, days back, aggregator, postprocessors)
        ('twitter.followers', twitter_followers, 30, None,
            [zero_fill_daily, interpolators.linear]),
        ('twitter.tweets', twitter_tweets, 20, None, [zero_fill_daily]),
        ('facebook.friends', fb_friends, 180, monthly_max, None),
        ('foursquare.checkins', foursq_checkins, 14, None, [zero_fill_daily]),
        ('lastfm.listened', lastfm_listened, 14, None, [zero_fill_daily]),
        ('klout.score', klout_score, 30, weekly_max, [zero_fill_weekly,
                                                      interpolators.linear]),
        ('runkeeper.calories', runkeeper_calories, 60, weekly_sum,
            [zero_fill_weekly]),
        ('runkeeper.activities', runkeeper_activities, 60,weekly_sum,
            [zero_fill_weekly]),
        ('runkeeper.weight', runkeeper_weight, 180,weekly_min,
            [zero_fill_weekly, interpolators.linear]),
        ('sleeps', jawbone_sleeps, 14, None, [zero_fill_daily,
            interpolators.linear]),
        ('steps', jawbone_steps, 14, None, [zero_fill_daily,
            interpolators.linear]),
        ('caffeine', jawbone_caffeine, 30, None, [zero_fill_daily]),
        ('tmp102.temperature', tmp102_celsius, 2.5, None, None)
    ]

    for ds in data_sources:
        data[ds[0]] = ds[1].aggregate(today_utc() - timedelta(days=ds[2]),
                                      aggregator=ds[3],
                                      post_processors=ds[4])

    report = {
        'generated': str(now_utc()),
        'data': data,
        'took': (datetime.datetime.now() - start).seconds
    }
    report_json = json.dumps(report, indent=4, default=json_date_serializer)
    report_content = '{0}({1})'.format(JSONP_CALLBACK_NAME, report_json)
    
    blob_service = BlobService(config['azure.account'], config['azure.key'])
    blob_service.create_container(config['azure.blob.container'])
    blob_service.set_container_acl(config['azure.blob.container'],
                                   x_ms_blob_public_access='container')
    blob_service.put_blob(config['azure.blob.container'],
                          config['azure.blob.name'], report_content, 'BlockBlob')

    took = (datetime.datetime.now() - start).seconds
    logger.info('Report generated and uploaded. Took {0} s.'.format(took))
开发者ID:JonathanGitHub,项目名称:personal-dashboard,代码行数:65,代码来源:reporting.py

示例15: BlobService

# 需要导入模块: from azure.storage import BlobService [as 别名]
# 或者: from azure.storage.BlobService import create_container [as 别名]
import glob
import os
import time

logtime = time.strftime("%Y%m%d-%H%M%S")
logmessage = "uploadmp3.py started"
command = "sed -i '1s/^/" + logtime + " " + logmessage + "\\n/' /home/pi/selcuk/log.txt"
os.system(command)

from azure.storage import BlobService
blob_service = BlobService(account_name='account_name', account_key='account_key')
blob_service.create_container('record')
blob_service.create_container('record', x_ms_blob_public_access='container')
blob_service.set_container_acl('record', x_ms_blob_public_access='container')

directory = "/home/pi/selcuk/mp3"

os.chdir(directory)
for file in glob.glob("*.mp3"):
    full_path = directory + "/" + file
    blob_service.put_block_blob_from_path(
        'record',
        file,
        full_path,
        x_ms_blob_content_type='audio/mpeg3'
    )
    delete_command = "rm " + file
    os.system(delete_command)

    logtime = time.strftime("%Y%m%d-%H%M%S")
    logmessage = file + " uploaded to cloud and deleted from device"
开发者ID:selcukyavuz,项目名称:raspberry314,代码行数:33,代码来源:uploadmp3.py


注:本文中的azure.storage.BlobService.create_container方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。