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


Python logger.error函数代码示例

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


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

示例1: lookupEmail

def lookupEmail(userid):
    """
    Grabs email for the user based on LDAP attrs
    """
    try:
        logger.debug(type(userid))
        if isinstance(userid, WSGIRequest):
            raise Exception("WSGIRequest invalid.")
        attr = _search_ldap(userid)
        emailaddr = attr[0][1]["mail"][0]
        return emailaddr
    except Exception as e:
        logger.warn("Error occurred looking up email for user: %s" % userid)
        logger.exception(e)
        import traceback
        import sys
        import inspect

        s = inspect.stack()
        for i in range(0, 4):
            logger.debug(s[i])
        etype, value, tb = sys.exc_info()
        logger.error("TB = %s" % traceback.format_tb(tb))

        return None
开发者ID:420reich,项目名称:atmosphere,代码行数:25,代码来源:ldap.py

示例2: get_default_identity

def get_default_identity(username, provider=None):
    """
    Return the default identity given to the user-group for provider.
    """
    try:
        from core.models.group import get_user_group
        group = get_user_group(username)
        identities = group.identities.all()
        if provider:
            if provider.is_active():
                identities = identities.filter(provider=provider)
                return identities[0]
            else:
                logger.error("Provider provided for "
                             "get_default_identity is inactive.")
                raise "Inactive Provider provided for get_default_identity "
        else:
            default_provider = get_default_provider(username)
            default_identity = group.identities.filter(
                provider=default_provider)
            if not default_identity:
                logger.error("User %s has no identities on Provider %s" % (username, default_provider))
                raise "No Identities on Provider %s for %s" % (default_provider,username)
            #Passing
            default_identity = default_identity[0]
            logger.debug(
                "default_identity set to %s " %
                default_identity)
            return default_identity
    except Exception as e:
        logger.exception(e)
        return None
开发者ID:EthanChen-Field,项目名称:atmosphere,代码行数:32,代码来源:user.py

示例3: post

 def post(self, request, provider_id, identity_id, format=None):
     """
     Create a new identity member (ADMINS & OWNERS GROUP LEADERS ONLY)
     """
     user = request.user
     data = request.DATA
     try:
         identity = Identity.objects.get(id=identity_id)
         group_name = data['group']
         group = Group.objects.get(name=group_name)
         prov_member = identity.provider.share(group)
         id_member = identity.share(group)
     except ObjectDoesNotExist as odne:
         return failure_response(
             status.HTTP_404_NOT_FOUND,
             '%s does not exist.' % odne.message.split()[0])
     if not identity.can_share(user):
         logger.error("User %s cannot share identity %s. "
                      + "This incident will be reported")
         return failure_response(
             status.HTTP_401_UNAUTHORIZED,
             "User %s cannot remove sharing from identity %s. "
             + "This incident will be reported"
             % (user, identity_id))
     serializer = IdentitySerializer(id_member.identity)
     serialized_data = serializer.data
     return Response(serialized_data)
开发者ID:420reich,项目名称:atmosphere,代码行数:27,代码来源:identity_membership.py

示例4: delete

 def delete(self, request, provider_id,
            identity_id, group_name, format=None):
     """
     Unshare the identity
     """
     try:
         identity = Identity.objects.get(id=identity_id)
     except Identity.DoesNotExist:
         return failure_response(
             status.HTTP_404_NOT_FOUND,
             "Identity does not exist.")
     if not identity.can_share(user):
         logger.error("User %s cannot remove sharing from identity %s. "
                      + "This incident will be reported"
                      % (user, identity_id))
         return failure_response(
             status.HTTP_401_UNAUTHORIZED,
             "User %s cannot remove sharing from identity %s. "
             + "This incident will be reported"
             % (user, identity_id))
     group = Group.objects.get(name=group_name)
     id_member = identity.unshare(group)
     serializer = IdentitySerializer(id_member.identity)
     serialized_data = serializer.data
     return Response(serialized_data)
开发者ID:420reich,项目名称:atmosphere,代码行数:25,代码来源:identity_membership.py

示例5: get

    def get(self, request, username):
        """
        Create a new token in the database on behalf of 'username'
        Returns success 201 Created - Body is JSON and contains
        """
        params = request.DATA
        user = request.user
        if user.username is not 'admin' and not user.is_superuser:
            logger.error("URGENT! User: %s is attempting to emulate a user!"
                         % user.username)
            return Response('Only admin and superusers can emulate accounts. '
                            'This offense has been reported',
                            status=status.HTTP_401_UNAUTHORIZED)
        if not AtmosphereUser.objects.filter(username=username):
            return Response("Username %s does not exist as an AtmosphereUser"
                            % username, status=status.HTTP_404_NOT_FOUND)

        #User is authenticated, username exists. Make a token for them.
        token = createAuthToken(username)
        expireTime = token.issuedTime + secrets.TOKEN_EXPIRY_TIME
        auth_json = {
            #Extra data passed only on emulation..
            'emulated_by': request.user.username,
            #Normal token data..
            'token': token.key,
            'username': token.user.username,
            'expires': expireTime.strftime("%b %d, %Y %H:%M:%S")
        }
        return Response(auth_json, status=status.HTTP_201_CREATED)
开发者ID:420reich,项目名称:atmosphere,代码行数:29,代码来源:token.py

示例6: get

    def get(self, request, username):
        """
        Create a new token in the database on behalf of 'username'
        Returns success 201 Created - Body is JSON and contains
        """
        user = request.user
        if not username:
            return Response("Username was not provided",
                            status=status.HTTP_400_BAD_REQUEST)
        if user.username is not 'admin' and not user.is_superuser:
            logger.error("URGENT! User: %s is attempting to emulate a user!"
                         % user.username)
            return Response("Only admin and superusers can emulate accounts. "
                            "This offense has been reported",
                            status=status.HTTP_401_UNAUTHORIZED)
        if not AtmosphereUser.objects.filter(username=username):
            return Response("Username %s does not exist as an AtmosphereUser"
                            % username, status=status.HTTP_404_NOT_FOUND)

        # User is authenticated, username exists. Make a token for them.
        user_to_emulate = AtmosphereUser.objects.get_by_natural_key(username)
        token = get_or_create_token(user_to_emulate, issuer="DRF-EmulatedUser")
        expireTime = token.issuedTime + secrets.TOKEN_EXPIRY_TIME
        auth_json = {
            # Extra data passed only on emulation..
            "emulator": request.user.username,
            # Normal token data..
            "token": token.key,
            "username": token.user.username,
            "expires": expireTime.strftime("%b %d, %Y %H:%M:%S")
        }
        return Response(auth_json, status=status.HTTP_201_CREATED)
开发者ID:xuhang57,项目名称:atmosphere,代码行数:32,代码来源:token.py

示例7: get_default_provider

def get_default_provider(username):
    """
    Return default provider given
    """
    try:
        from core.models.group import get_user_group
        from core.models.provider import Provider
        group = get_user_group(username)
        provider_ids = group.current_identities.values_list(
            'provider',
            flat=True)
        provider = Provider.objects.filter(
            id__in=provider_ids,
            type__name="OpenStack")
        if provider:
            logger.debug("get_default_provider selected a new "
                         "Provider for %s: %s" % (username, provider))
            provider = provider[0]
        else:
            logger.error("get_default_provider could not find a new "
                         "Provider for %s" % (username,))
            return None
        return provider
    except Exception as e:
        logger.exception("get_default_provider encountered an error "
                         "for %s" % (username,))
        return None
开发者ID:catdewey,项目名称:atmosphere,代码行数:27,代码来源:user.py

示例8: _get_cached

def _get_cached(key, data_method, scrub_method, force=False):
    try:
        r = redis_connection()
        if force:
            _invalidate(key)
        data = r.get(key)
    except redis.exceptions.ConnectionError:
        logger.error(
            "EXTERNAL SERVICE redis-server IS NOT RUNNING! "
            "Somebody should turn it on!"
        )
        data = None
    if not data:
        data = data_method()
        scrub_method(data)
        logger.debug(
            "Updated redis({0}) using {1} and {2}".format(
                key, data_method, scrub_method
            )
        )
        r.set(key, pickle.dumps(data))
        r.expire(key, 30)
        return data
    logger.debug("Actual type {0}".format(type(data)))
    return pickle.loads(data)
开发者ID:iPlantCollaborativeOpenSource,项目名称:atmosphere,代码行数:25,代码来源:cache.py

示例9: get_default_provider

def get_default_provider(username):
    """
    Return default provider given 
    """
    try:
        from core.models.group import get_user_group
        group = get_user_group(username)
        provider = group.providers.filter(
            Q(end_date=None) | Q(end_date__gt=timezone.now()),
            active=True, type__name="OpenStack")
        if provider:
            provider = provider[0]
        else:
            logger.error("get_default_provider could not find "
                         "a valid Provider")
            return None
        logger.debug(
            "default provider is %s " % provider)
        return provider
    except IndexError:
        logger.info("No provider found for %s" % username)
        return None
    except Exception, e:
        logger.exception(e)
        return None
开发者ID:420reich,项目名称:atmosphere,代码行数:25,代码来源:user.py

示例10: build_host_name

def build_host_name(ip):
    """
    Build host name from the configuration in settings
    See:
    * INSTANCE_HOSTNAMING_FORMAT
    * INSTANCE_HOSTNAMING_DOMAIN (Required if you use `%(domain)s`)
    """
    # NOTE: This is a hack until we address 'provider specific' hostnaming
    if "114.5" in ip:
        return raw_hostname(ip)

    if not hasattr(settings, "INSTANCE_HOSTNAMING_FORMAT"):
        return raw_hostname(ip)
    if all((str_val not in settings.INSTANCE_HOSTNAMING_FORMAT) for str_val in ["one", "two", "three", "four"]):
        logger.error(
            "Invalid INSTANCE_HOSTNAMING_FORMAT: Expected string containing "
            "at least one of the IP octets. "
            "(ex:'vm%(three)s-%(four)s.%(domain)s')"
        )
    # IP --> octet_tuple (127,0,0,1)
    hostnaming_format_map = create_hostnaming_map(ip)
    try:
        return settings.INSTANCE_HOSTNAMING_FORMAT % hostnaming_format_map
    except (KeyError, TypeError) as exc:
        logger.error("Invalid INSTANCE_HOSTNAMING_FORMAT: %s" % exc)
开发者ID:Cyberlusion,项目名称:Restoring-the-ecosystem,代码行数:25,代码来源:deploy.py

示例11: deploy_init_to

def deploy_init_to(driverCls, provider, identity, instance_id,
                   username=None, password=None, redeploy=False,
                   *args, **kwargs):
    try:
        logger.debug("deploy_init_to task started at %s." % datetime.now())
        driver = get_driver(driverCls, provider, identity)
        instance = driver.get_instance(instance_id)
        if not instance:
            logger.debug("Instance has been teminated: %s." % instance_id)
            return
        image_metadata = driver._connection\
                               .ex_get_image_metadata(instance.machine)
        deploy_chain = get_deploy_chain(driverCls, provider, identity,
                                        instance, password, redeploy)
        logger.debug("Starting deploy chain for: %s." % instance_id)
        deploy_chain.apply_async()
        #Can be really useful when testing.
        #if kwargs.get('delay'):
        #    async.get()
        logger.debug("deploy_init_to task finished at %s." % datetime.now())
    except SystemExit:
        logger.exception("System Exits are BAD! Find this and get rid of it!")
        raise Exception("System Exit called")
    except NonZeroDeploymentException as non_zero:
        logger.error(str(non_zero))
        logger.error(non_zero.__dict__)
        raise
    except Exception as exc:
        logger.warn(exc)
        deploy_init_to.retry(exc=exc)
开发者ID:chromabinary,项目名称:atmosphere,代码行数:30,代码来源:driver.py

示例12: get_default_identity

def get_default_identity(username, provider=None):
    """
    Return the default identity given to the user-group for provider.
    """
    try:
        from core.models.group import get_user_group
        group = get_user_group(username)
        identities = group.identities.all()
        if provider:
            if provider.is_active():
                identities = identities.filter(provider=provider)
                return identities[0]
            else:
                logger.error("Provider provided for "
                             "get_default_identity is inactive.")
                raise("Provider provided for get_default_identity "
                      "is inactive.")
        else:
            default_provider = get_default_provider(username)
            default_identity = group.identities.filter(
                provider=default_provider)[0]
            logger.debug(
                "default_identity set to %s " %
                default_identity)
            return default_identity
    except Exception, e:
        logger.exception(e)
        return None
开发者ID:Angelfirenze,项目名称:atmosphere,代码行数:28,代码来源:user.py

示例13: put

    def put(self, request, provider_id, identity_id, machine_id):
        """
        TODO: Determine who is allowed to edit machines besides
            core_machine.owner
        """
        user = request.user
        data = request.DATA
        esh_driver = prepare_driver(request, provider_id, identity_id)
        if not esh_driver:
            return invalid_creds(provider_id, identity_id)
        esh_machine = esh_driver.get_machine(machine_id)
        core_machine = convert_esh_machine(esh_driver, esh_machine, provider_id)

        if not user.is_staff\
           and user is not core_machine.application.created_by:
            logger.error('Non-staff/non-owner trying to update a machine')
            return failure_response(
                status.HTTP_401_UNAUTHORIZED,
                'Only Staff and the machine Owner '
                + 'are allowed to change machine info.')
        core_machine.application.update(data)
        serializer = ProviderMachineSerializer(core_machine,
                                               data=data, partial=True)
        if serializer.is_valid():
            logger.info('metadata = %s' % data)
            update_machine_metadata(esh_driver, esh_machine, data)
            serializer.save()
            logger.info(serializer.data)
            return Response(serializer.data)
        return failure_response(
            status.HTTP_400_BAD_REQUEST,
            serializer.errors)
开发者ID:zhanghaihua,项目名称:atmosphere,代码行数:32,代码来源:machine.py

示例14: o_callback_authorize

def o_callback_authorize(request):
    logger.info(request.__dict__)
    if 'code' not in request.GET:
        logger.info(request.__dict__)
        #TODO - Maybe: Redirect into a login
        return HttpResponse("")
    oauth_client = get_cas_oauth_client()
    oauth_code = request.GET['code']
    #Exchange code for ticket
    access_token, expiry_date = oauth_client.get_access_token(oauth_code)
    if not access_token:
        logger.info("The Code %s is invalid/expired. Attempting another login."
                    % oauth_code)
        return o_login_redirect(request)
    #Exchange token for profile
    user_profile = oauth_client.get_profile(access_token)
    if not user_profile or "id" not in user_profile:
        logger.error("AccessToken is producing an INVALID profile!"
                     " Check the CAS server and caslib.py for more"
                     " information.")
        #NOTE: Make sure this redirects the user OUT of the loop!
        return login(request)
    #ASSERT: A valid OAuth token gave us the Users Profile.
    # Now create an AuthToken and return it
    username = user_profile["id"]
    auth_token = obtainOAuthToken(username, access_token, expiry_date)
    #Set the username to the user to be emulated
    #to whom the token also belongs
    request.session['username'] = username
    request.session['token'] = auth_token.key
    logger.info("Returning user - %s - to application "
                % username)
    logger.info(request.session.__dict__)
    logger.info(request.user)
    return HttpResponseRedirect(settings.REDIRECT_URL+"/application/")
开发者ID:Angelfirenze,项目名称:atmosphere,代码行数:35,代码来源:views.py

示例15: validate_input

    def validate_input(self, user, data):
        error_map = {}

        name = data.get('name')
        identity_uuid = data.get('identity')
        source_alias = data.get('source_alias')
        size_alias = data.get('size_alias')
        if not name:
            error_map['name'] = "This field is required."
        if not identity_uuid:
            error_map['identity'] = "This field is required."
        if not source_alias:
            error_map['source_alias'] = "This field is required."
        if not size_alias:
            error_map['size_alias'] = "This field is required."

        if error_map:
            raise Exception(error_map)

        try:
            identity = Identity.objects.get(uuid=identity_uuid)
            # Staff or owner ONLY
            if not user.is_staff and identity.created_by != user:
                logger.error("User %s does not have permission to use identity %s" % (user, identity))
                raise Identity.DoesNotExist("You are not the owner")
        except Identity.DoesNotExist:
            error_map["identity"] = "The uuid (%s) is invalid." % identity_uuid
            raise Exception(error_map)
        return
开发者ID:Cyberlusion,项目名称:Restoring-the-ecosystem,代码行数:29,代码来源:instance.py


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