• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python client.head_container函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中swiftclient.client.head_container函数的典型用法代码示例。如果您正苦于以下问题:Python head_container函数的具体用法?Python head_container怎么用?Python head_container使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: test_storlet_acl_get_success

    def test_storlet_acl_get_success(self):
        headers = {'X-Run-Storlet': self.storlet_name}
        headers.update(self.additional_headers)
        exc_pattern = '^.*403 Forbidden.*$'
        with self.assertRaisesRegexp(ClientException, exc_pattern):
            swift_client.get_object(self.member_url, self.member_token,
                                    'myobjects', 'test_object',
                                    headers=headers)

        headers = {'X-Storlet-Container-Read': self.conf.member_user,
                   'X-Storlet-Name': self.storlet_name}
        swift_client.post_container(self.url,
                                    self.token,
                                    'myobjects',
                                    headers)
        swift_client.head_container(self.url,
                                    self.token,
                                    'myobjects')
        headers = {'X-Run-Storlet': self.storlet_name}
        headers.update(self.additional_headers)
        resp_dict = dict()
        swift_client.get_object(self.member_url,
                                self.member_token,
                                'myobjects', 'test_object',
                                response_dict=resp_dict,
                                headers=headers)
        self.assertEqual(resp_dict['status'], 200)
开发者ID:openstack,项目名称:storlets,代码行数:27,代码来源:test_test_storlet.py


示例2: test_server_error

 def test_server_error(self):
     body = "c" * 60
     c.http_connection = self.fake_http_connection(500, body=body)
     self.assertRaises(c.ClientException, c.head_container, "http://www.test.com", "asdf", "asdf")
     try:
         c.head_container("http://www.test.com", "asdf", "asdf")
     except c.ClientException as e:
         self.assertEqual(e.http_response_content, body)
开发者ID:AlphaStaxLLC,项目名称:python-swiftclient,代码行数:8,代码来源:test_swiftclient.py


示例3: getMember

 def getMember(self, name):
     try:
         client.head_container(self.storage_url,
                               self.auth_token,
                               container=name,
                               http_conn=self.http_connection)
         return ObjectCollection(name, self.environ, path=self.path)
     except client.ClientException as ex:
         if '404' in ex:
             raise dav_error.DAVError(dav_error.HTTP_NOT_FOUND)
开发者ID:cschwede,项目名称:swiftdav,代码行数:10,代码来源:swiftdav.py


示例4: test_server_error

 def test_server_error(self):
     body = 'c' * 60
     c.http_connection = self.fake_http_connection(500, body=body)
     self.assertRaises(c.ClientException, c.head_container,
                       'http://www.test.com', 'asdf', 'asdf',
                       )
     try:
         c.head_container('http://www.test.com', 'asdf', 'asdf')
     except c.ClientException as e:
         self.assertEquals(e.http_response_content, body)
开发者ID:scottkmaxwell,项目名称:python-swiftclient,代码行数:10,代码来源:test_swiftclient.py


示例5: create_thumbnail

def create_thumbnail(request, account, original_container_name, container,
                     objectname):
    """ Creates a thumbnail for an image. """
    storage_url = request.session.get('storage_url', '')
    auth_token = request.session.get('auth_token', '')

    try:
        client.head_container(storage_url, auth_token,
                              account)
    except client.ClientException:
        try:
            client.put_container(
                storage_url,
                auth_token,
                account)
        except client.ClientException as e:
            logger.error("Cannot put container %s. Error: %s "
                         % (container, str(e)))
            return None
    try:
        headers, content = client.get_object(
            storage_url,
            auth_token,
            container,
            objectname)

        im = Image.open(StringIO(content))
        im.thumbnail(settings.THUMBNAIL_SIZE, Image.ANTIALIAS)
        output = StringIO()
        mimetype = headers['content-type'].split('/')[-1]
        im.save(output, format=mimetype)
        content = output.getvalue()
        headers = {'X-Delete-After': settings.THUMBNAIL_DURABILITY}
        try:
            client.put_object(
                storage_url,
                auth_token,
                account,
                "%s_%s" % (original_container_name, objectname),
                content,
                headers=headers)
        except client.ClientException as e:
            logger.error("Cannot create thumbnail for image %s."
                         "Could not put thumbnail to storage: %s"
                         % (objectname, str(e)))
        output.close()
    except client.ClientException as e:
        logger.error("Cannot create thumbnail for image %s."
                     "Could not retrieve the image from storage: %s"
                     % (objectname, str(e)))
    except IOError as e:
        logger.error("Cannot create thumbnail for image %s."
                     "An IOError occured: %s" % (objectname, e.strerror))
开发者ID:OLRC,项目名称:django-swiftbrowser,代码行数:53,代码来源:utils.py


示例6: wrapper

    def wrapper(*args, **kw):

        storage_url = args[0].session.get('storage_url', '')
        auth_token = args[0].session.get('auth_token', '')
        username = args[0].session.get('username', '')
        password = args[0].session.get('password', '')

        # If the following variables are available, attempt to get an
        # auth token
        if (storage_url and auth_token and username and password):

             # If the user has no role, head the container to valid the token
            if args[0].session.get('norole'):

                storage_url = args[0].session.get('default_storage_url', '')
                auth_token = args[0].session.get('default_auth_token', '')

                #Attempt to get a new auth token
                try:
                    client.head_container(
                        storage_url, auth_token, args[0].session.get('user'))
                    return fn(*args, **kw)
                except:
                    # Failure to get an auth token, tell the user the session
                    # has expiredself.
                    messages.error(args[0], _("Session expired."))

            # A regular user's token is validated by heading the account.
            else:
                try:
                    client.head_account(storage_url, auth_token)
                    return fn(*args, **kw)
                except:

                    #Attempt to get a new auth token
                    try:
                        auth_version = settings.SWIFT_AUTH_VERSION or 1
                        (storage_url, auth_token) = client.get_auth(
                            settings.SWIFT_AUTH_URL, username, password,
                            auth_version=auth_version)
                        args[0].session['auth_token'] = auth_token
                        args[0].session['storage_url'] = storage_url
                        return fn(*args, **kw)
                    except:
                        # Failure to get an auth token, tell the user the
                        # session has expired.
                        messages.error(args[0], _("Session expired."))
        return redirect(swiftbrowser.views.login)
开发者ID:bkawula,项目名称:django-swiftbrowser,代码行数:48,代码来源:__init__.py


示例7: toggle_public

def toggle_public(request, container):
    """ Sets/unsets '.r:*,.rlistings' container read ACL """

    storage_url = request.session.get('storage_url', '')
    auth_token = request.session.get('auth_token', '')

    try:
        meta = client.head_container(storage_url, auth_token, container)
    except client.ClientException:
        traceback.print_exc()
        messages.add_message(request, messages.ERROR, _("Access denied."))
        return redirect(containerview)

    read_acl = meta.get('x-container-read', '')
    if '.rlistings' and '.r:*' in read_acl:
        read_acl = read_acl.replace('.r:*', '')
        read_acl = read_acl.replace('.rlistings', '')
        read_acl = read_acl.replace(',,', ',')
    else:
        read_acl += '.r:*,.rlistings'
    headers = {'X-Container-Read': read_acl, }

    try:
        client.post_container(storage_url, auth_token, container, headers)
    except client.ClientException:
        traceback.print_exc()
        messages.add_message(request, messages.ERROR, _("Access denied."))

    return redirect(objectview, container=container)
开发者ID:unibg-seclab,项目名称:django-swiftbrowser,代码行数:29,代码来源:views.py


示例8: object_versioning

def object_versioning(request, container, prefix=None):
    storage_url = get_endpoint(request, 'adminURL')
    auth_token = get_token_id(request)
    public_url = get_endpoint(request, 'publicURL') + '/' + container
    http_conn = client.http_connection(storage_url,
                                       insecure=settings.SWIFT_INSECURE)

    objects = []

    page = request.GET.get('page', 1)

    if request.method == 'GET':
        headers = client.head_container(storage_url,
                                auth_token,
                                container,
                                http_conn=http_conn)

        version_location = headers.get('x-versions-location', None)

        if version_location:
            try:
                _, objects = client.get_container(storage_url,
                                                  auth_token,
                                                  version_location,
                                                  prefix=prefix,
                                                  delimiter='/',
                                                  http_conn=http_conn)
            except client.ClientException:
                pass

        prefixes = prefix_list(prefix)
        object_list = pseudofolder_object_list(objects, prefix, public_url)

        context = utils.update_default_context(request, {
            'container': container,
            'objects': utils.generic_pagination(object_list, page),
            'version_location': version_location,
            'prefix': prefix,
            'prefixes': prefixes,
        })

        return render_to_response('container_versioning.html',
                                  dictionary=context,
                                  context_instance=RequestContext(request))

    if request.method == 'POST':

        action = request.POST.get('action', None)

        if action == 'enable':
            enable_versioning(request, container)
            actionlog.log(request.user.username, "enable", 'Versioning. Container: %s' % container)
        elif action == 'disable':
            disable_versioning(request, container)
            actionlog.log(request.user.username, "disable", 'Versioning. Container: %s' % container)
        else:
            messages.add_message(request, messages.ERROR, ugettext('Action is required.'))

        return redirect(object_versioning, container=container)
开发者ID:globocom,项目名称:vault,代码行数:59,代码来源:views.py


示例9: get_acls

def get_acls(storage_url, auth_token, container, http_conn):
    """ Returns ACLs of given container. """
    acls = client.head_container(storage_url,
                                auth_token,
                                container,
                                http_conn=http_conn)

    readers = acls.get('x-container-read', '')
    writers = acls.get('x-container-write', '')
    return (readers, writers)
开发者ID:globocom,项目名称:vault,代码行数:10,代码来源:utils.py


示例10: get_cors

def get_cors(storage_url, auth_token, container, http_conn):
    """ Returns CORS header of given container. """
    headers = client.head_container(storage_url,
                                    auth_token,
                                    container,
                                    http_conn=http_conn)

    cors = headers.get('x-container-meta-access-control-allow-origin', '')

    return cors
开发者ID:globocom,项目名称:vault,代码行数:10,代码来源:utils.py


示例11: get_acls

def get_acls(request, container):
    """ Read and return the Read and Write ACL of the given container. """

    storage_url = request.session.get("storage_url", "")
    auth_token = request.session.get("auth_token", "")

    cont = client.head_container(storage_url, auth_token, container)
    readers = split_acl(cont.get("x-container-read", ""))
    writers = split_acl(cont.get("x-container-write", ""))

    return JsonResponse({"read_acl": readers, "write_acl": writers})
开发者ID:OLRC,项目名称:django-swiftbrowser,代码行数:11,代码来源:containers.py


示例12: container_status

    def container_status(url, token, container_name):
        """
        Returns status of container.

        :param url: storage url.
        :param token: auth token from keystone.
        :param container_name: name of container to return status.
        :return: dict of information on specified container.
        """
        status = sc.head_container(url, token, container_name)
        return status
开发者ID:subecho,项目名称:Iridium,代码行数:11,代码来源:swift.py


示例13: check_incomplete_slo

def check_incomplete_slo(request, storage_url, auth_token, container,
                         prefix=None):
    '''Check the header 'x-container-meta-slo' for the names of SLO that are
    incomplete. Return a list of the names of objects and the percentage
    it is complete.'''

    incomplete_slo = []

    try:
        headers = client.head_container(storage_url, auth_token, container)
    except client.ClientException, e:
        return HttpResponse(e, status=500)
开发者ID:bkawula,项目名称:django-swiftbrowser,代码行数:12,代码来源:objects.py


示例14: limited_users_login

def limited_users_login(request):
    """ Get and parse the list of containers the user has access to. """

    storage_url = request.session.get('storage_url', '')
    auth_token = request.session.get('auth_token', '')
    user = request.session.get('user', '')

    # Get list of containers the user has access to in
    # "X-Container-Meta-container-list" of the container that matches the
    # user's username.
    try:
        meta = client.head_container(storage_url, auth_token, user)

        # Save the storage_url and auth_token as the default
        # These values will be the ones reused to validate the session in
        # session_valid.
        request.session["default_storage_url"] = storage_url
        request.session["default_auth_token"] = auth_token
    except client.ClientException:

        # The user may belong to more than one tenant and so the user's
        # container my be in another tenant. Switch to the next tenant
        # in the tenant list.
        for i, tenant in enumerate(request.session["tenants"]):
            if tenant == request.session["tenant_name"]:
                if i + 1 <= len(request.session["tenants"]):
                    return redirect(
                        swiftbrowser.views.main.switch_tenant,
                        request.session["tenants"][i + 1], True)
                else:
                    # We've tried all the tenants, no container exists
                    messages.add_message(
                        request, messages.ERROR,
                        _("Unable to find container {0} in any tenant."
                            .format(user)))
                    break

        return redirect(swiftbrowser.views.main.login)

    # List of containers
    if not "x-container-meta-container-list" in meta:
        # User does not have access to any container but it's own
        containers = request.session["tenant_name"] + ":" + user
    else:
        containers = meta["x-container-meta-container-list"]

    # Save the mapping of tenants and containers the user has access to.
    if not request.session.get('container_mapping', ''):
        request.session['container_mapping'] = get_tenant_container_mapping(
            containers)

    return redirect(limited_users_containerview)
开发者ID:bkawula,项目名称:django-swiftbrowser,代码行数:52,代码来源:limited_users.py


示例15: cache_set

    def cache_set(self, context, plan_name, key, contents):
        """Stores an object

        Allows the storage of jsonable objects except for None
        Storing None equals to a cache delete.

        """

        swift_client = self.get_object_client(context)
        if contents is None:
            self.cache_delete(context, plan_name, key)
            return

        try:
            swift_client.head_container(constants.TRIPLEO_CACHE_CONTAINER)
        except swiftexceptions.ClientException:
            swift_client.put_container(constants.TRIPLEO_CACHE_CONTAINER)

        swift_client.put_object(
            constants.TRIPLEO_CACHE_CONTAINER,
            self._cache_key(plan_name, key),
            zlib.compress(json.dumps(contents).encode()))
开发者ID:infraredgirl,项目名称:tripleo-common,代码行数:22,代码来源:base.py


示例16: copyMoveSingle

    def copyMoveSingle(self, destPath, isMove):
        src = '/'.join(self.path.split('/')[2:])
        dst = '/'.join(destPath.split('/')[2:])
        src_cont = self.path.split('/')[1]
        dst_cont = destPath.split('/')[1]

        headers = {'X-Copy-From': self.path}

        try:
            client.head_container(self.storage_url,
                              self.auth_token,
                              dst_cont,
                              headers=headers,
                              http_conn=self.http_connection)
        except client.ClientException as ex:
            client.put_container(self.storage_url,
                              self.auth_token,
                              dst_cont,
                              headers=headers,
                              http_conn=self.http_connection)

        try:
            client.put_object(self.storage_url,
                              self.auth_token,
                              dst_cont,
                              dst,
                              headers=headers,
                              http_conn=self.http_connection)

            if isMove:
                client.delete_object(self.storage_url,
                                     self.auth_token,
                                     src_cont,
                                     src,
                                     http_conn=self.http_connection)
        except client.ClientException:
            pass
开发者ID:morucci,项目名称:swiftdav,代码行数:37,代码来源:swiftdav.py


示例17: get_fine_grained_temp_key

def get_fine_grained_temp_key(storage_url, auth_token, container_name=None):
    """ 
    Tries to get meta-temp-url key from account or container.
    If not set, generate tempurl and save it.
    """

    logging.debug('  in get_fine_grained_temp_key: container_name:%s, \
        storage_url:%s ' % 
        (container_name, storage_url) )

    try:
        if container_name:
            container = client.head_container(storage_url, auth_token, 
                container_name)
            key = container.get('x-container-meta-temp-url-key')
            logging.debug(' key in get_fine_grained_temp_key container: %s ' % key)
        else:
            account = client.head_account(storage_url, auth_token)
            key = account.get('x-account-meta-temp-url-key')
            logging.debug(' key in get_fine_grained_temp_key account: %s ' % key)
    except client.ClientException:
        return None
    # logging.debug(' account or container in get_temp_key: %s ' 
    #     % account or container)

    if not key:
        chars = string.ascii_lowercase + string.digits
        key = ''.join(random.choice(chars) for x in range(32))
        if container_name:
            headers = {'x-container-meta-temp-url-key': key}
            try:
                client.post_container(storage_url, auth_token, container_name, 
                    headers)
                logging.debug(' post_container')

            except client.ClientException:
                return None
            raise ValueError('cannot get key, have no account rights to \
                get account key!')
        else:
            
            headers = {'x-account-meta-temp-url-key': key}
            try:
                client.post_account(storage_url, auth_token, headers)
                logging.debug(' post_account')

            except client.ClientException:
                return None
    return key
开发者ID:ddxgz,项目名称:swift-storage-restapi,代码行数:49,代码来源:swiftutils.py


示例18: get_original_account

def get_original_account(storage_url, auth_token, container):
    try:
        headers = client.head_container(storage_url, auth_token, container)
        msp = headers.get('x-container-meta-storage-path')
        if msp is None:
            account = storage_url.split('/')[-1]
            original_container_name = container
        else:
            account = msp.split('/')[2]
            original_container_name = '_'.join(container.split('_')[2:])
    except client.ClientException as e:
        logger.error("Cannot head container %s . Error: %s "
                     % (container, str(e)))
        return (None, None)

    return (account, original_container_name)
开发者ID:OLRC,项目名称:django-swiftbrowser,代码行数:16,代码来源:utils.py


示例19: disable_versioning

def disable_versioning(request, container):
    """ Enable/Disable versioning in container. """

    storage_url = get_endpoint(request, 'adminURL')
    auth_token = get_token_id(request)
    http_conn = client.http_connection(storage_url,
                                       insecure=settings.SWIFT_INSECURE)

    try:
        headers = client.head_container(storage_url,
                                    auth_token,
                                    container,
                                    http_conn=http_conn)
    except client.ClientException as err:
        log.exception('Exception: {0}'.format(err))
        messages.add_message(request, messages.ERROR, _('Access denied.'))
        return False

    version_location = headers.get('x-versions-location', None)

    if version_location:
        try:
            client.post_container(storage_url,
                                  auth_token,
                                  container,
                                  headers={'x-versions-location': ''},
                                  http_conn=http_conn)
            actionlog.log(request.user.username, "update", container)

        except client.ClientException as err:
            log.exception('{}{}'.format(_('Exception:').encode('UTF-8'), err))
            messages.add_message(request, messages.ERROR, _('Access denied.'))
            return False

        deleted = delete_container(request=request, container=version_location)
        if not deleted:
            return False

    messages.add_message(request, messages.SUCCESS, _('Versioning disabled.'))

    return True
开发者ID:globocom,项目名称:vault,代码行数:41,代码来源:views.py


示例20: limited_users_containerview

def limited_users_containerview(request):
    """ Display the containers the user has access to within the current
    tenant."""

    storage_url = request.session.get('storage_url', '')
    auth_token = request.session.get('auth_token', '')

    container_list = []
    keys = {}

    container_mapping = request.session.get('container_mapping', '')

    if not container_mapping:
        messages.add_message(
            request, messages.ERROR, _("No container mapping."))
        return redirect(swiftbrowser.views.main.login)

    # Get keys for all the containers
    for container_name in container_mapping[request.session["tenant_name"]]:

        # Make sure user has access to the container
        try:
            meta = client.head_container(
                storage_url, auth_token, container_name)

        except client.ClientException:
            messages.add_message(
                request, messages.ERROR,
                _("Failed to head container {0}.".format(container_name)))
            return redirect(swiftbrowser.views.main.login)

        container_list.append({"name": container_name})
        keys[container_name] = meta.get('x-container-meta-temp-url-key', '')

    # Store the keys for later use
    request.session["keys"] = keys

    return render_to_response('limited_containerview.html', {
        'containers': container_list,
        'session': request.session,
    }, context_instance=RequestContext(request))
开发者ID:bkawula,项目名称:django-swiftbrowser,代码行数:41,代码来源:limited_users.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python client.head_object函数代码示例发布时间:2022-05-27
下一篇:
Python client.head_account函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap