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


Python logger.error函数代码示例

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


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

示例1: make_request

def make_request(method, host, url, username, password, fields=None):
    if host.lower().startswith('https://'):
        connection = urllib3.connection_from_url(
            host,
            cert_reqs=ssl.CERT_REQUIRED,
            ca_certs=certs_file()
        )
    else:
        connection = urllib3.connection_from_url(host)
    headers = urllib3.util.make_headers(
        basic_auth='{0}:{1}'.format(username, password),
        accept_encoding=True,
        user_agent=user_agent_identifier(),
        keep_alive=True
    )
    r = None
    try:
        r = connection.request(method, url, headers=headers, fields=fields)
        data = r.data
        charset = determine_charset(r)
        if isinstance(data, bytes):
            data = data.decode(charset)
        if r.status < 200 or r.status >= 400:
            if r.status == 404:
                raise HttpNotFound(data)
            else:
                raise Exception(data)
        return data, charset
    except SSLError:
        logger.error("Invalid SSL certificate")
        raise
    finally:
        if not r is None:
            r.close()
开发者ID:shimizukawa,项目名称:transifex-client,代码行数:34,代码来源:utils.py

示例2: get_details

def get_details(api_call, username, password, *args, **kwargs):
    """
    Get the tx project info through the API.

    This function can also be used to check the existence of a project.
    """
    url = (API_URLS[api_call] % (kwargs)).encode('UTF-8')
    conn = urllib3.connection_from_url(kwargs['hostname'])
    headers = urllib3.util.make_headers(
        basic_auth='{0}:{1}'.format(username, password),
        accept_encoding=True,
        user_agent=user_agent_identifier(),
    )
    try:
        r = conn.request('GET', url, headers=headers)
        if r.status < 200 or r.status >= 400:
            raise Exception(r.data)
        remote_project = parse_json(r.data)
        return remote_project
    except ssl.SSLError:
        logger.error("Invalid SSL certificate")
        raise
    except Exception, e:
        logger.debug(unicode(e))
        raise
开发者ID:stefanw,项目名称:transifex-client,代码行数:25,代码来源:utils.py

示例3: _init

    def _init(self, path_to_tx=None):
        instructions = "Run 'tx init' to initialize your project first!"
        try:
            self.root = self._get_tx_dir_path(path_to_tx)
            self.config_file = self._get_config_file_path(self.root)
            self.config = self._read_config_file(self.config_file)

            local_txrc_file = self._get_transifex_file(os.getcwd())
            if os.path.exists(local_txrc_file):
                self.txrc_file = local_txrc_file
            else:
                self.txrc_file = self._get_transifex_file()
            self.txrc = self._get_transifex_config([self.txrc_file, ])
        except ProjectNotInit as e:
            logger.error('\n'.join([six.u(str(e)), instructions]))
            raise
        host = self.config.get('main', 'host')
        if host.lower().startswith('https://'):
            self.conn = urllib3.connection_from_url(
                host,
                cert_reqs=ssl.CERT_REQUIRED,
                ca_certs=certs_file()
            )
        else:
            self.conn = urllib3.connection_from_url(host)
开发者ID:akx,项目名称:transifex-client,代码行数:25,代码来源:project.py

示例4: _create_resource

    def _create_resource(self, resource, pslug, fileinfo, filename, **kwargs):
        """Create a resource.

        Args:
            resource: The full resource name.
            pslug: The slug of the project.
            fileinfo: The information of the resource.
            filename: The name of the file.
        Raises:
            URLError, in case of a problem.
        """
        multipart = True
        method = "POST"
        api_call = 'create_resource'

        host = self.url_info['host']
        try:
            username = self.txrc.get(host, 'username')
            passwd = self.txrc.get(host, 'password')
            token = self.txrc.get(host, 'token')
            hostname = self.txrc.get(host, 'hostname')
        except ConfigParser.NoSectionError:
            raise Exception("No user credentials found for host %s. Edit"
                " ~/.transifexrc and add the appropriate info in there." %
                host)

        # Create the Url
        kwargs['hostname'] = hostname
        kwargs.update(self.url_info)
        kwargs['project'] = pslug
        url = (API_URLS[api_call] % kwargs).encode('UTF-8')

        headers = None

        i18n_type = self._get_option(resource, 'type')
        if i18n_type is None:
            logger.error(
                "Please define the resource type in .tx/config (eg. type = PO)."
                " More info: http://bit.ly/txcl-rt"
            )

        headers = urllib3.util.make_headers(
            basic_auth='{0}:{1}'.format(username, passwd),
            accept_encoding=True,
            user_agent=user_agent_identifier(),
            keep_alive=True
        )
        data = {
            "slug": fileinfo.split(';')[0],
            "name": fileinfo.split(';')[0],
            "uploaded_file": (filename, open(filename, 'rb').read()),
            "i18n_type": i18n_type
        }
        try:
            r = self.conn.request(method, url, fields=data, headers=headers)
        except ssl.SSLError:
            logger.error("Invalid SSL certificate")
        r.close()
        return r.data
开发者ID:mpessas,项目名称:transifex-client,代码行数:59,代码来源:project.py

示例5: _extension_for

 def _extension_for(self, i18n_type):
     """Return the extension used for the specified type."""
     try:
         res = parse_json(self.do_url_request('formats'))
         return res[i18n_type]['file-extensions'].split(',')[0]
     except Exception,e:
         logger.error(e)
         return ''
开发者ID:sayanchowdhury,项目名称:transifex-client,代码行数:8,代码来源:project.py

示例6: _init

 def _init(self, path_to_tx=None):
     instructions = "Run 'tx init' to initialize your project first!"
     try:
         self.root = self._get_tx_dir_path(path_to_tx)
         self.config_file = self._get_config_file_path(self.root)
         self.config = self._read_config_file(self.config_file)
         self.txrc_file = self._get_transifex_file()
         self.txrc = self._get_transifex_config(self.txrc_file)
     except ProjectNotInit, e:
         logger.error('\n'.join([unicode(e), instructions]))
         raise
开发者ID:sayanchowdhury,项目名称:transifex-client,代码行数:11,代码来源:project.py

示例7: get_projects_for_org

    def get_projects_for_org(self, organization):
        try:
            projects = self.api.get('projects', organization=organization)
        except Exception as e:
            logger.error(e)
            raise

        # return project list sorted by name
        return sorted(
            [p for p in projects if not p['archived']],
            key=lambda x: x['name']
        )
开发者ID:transifex,项目名称:transifex-client,代码行数:12,代码来源:wizard.py

示例8: get_organizations

    def get_organizations(self):
        try:
            organizations = self.api.get('organizations')
        except Exception as e:
            logger.error(e)
            raise

        # return org list sorted by name
        return sorted(
            [(o['slug'], o['name']) for o in organizations],
            key=lambda x: x[1]
        )
开发者ID:transifex,项目名称:transifex-client,代码行数:12,代码来源:wizard.py

示例9: _get_stats_for_resource

 def _get_stats_for_resource(self):
     """Get the statistics information for a resource."""
     try:
         r = self.do_url_request('resource_stats')
         logger.debug("Statistics response is %s" % r)
         stats = parse_json(r)
     except ssl.SSLError:
         logger.error("Invalid SSL certificate")
         raise
     except Exception, e:
         logger.debug(unicode(e))
         raise
开发者ID:GbalsaC,项目名称:bitnamiP,代码行数:12,代码来源:project.py

示例10: __init__

 def __init__(self, token=None, username=None, password=None,
              path_to_tx=None, host=None):
     self.hostnames = self.map_paths_to_hostnames(path_to_tx, host)
     if token:
         self.token = token
         self.username = self.USERNAME
     elif username and password:
         self.token = password
         self.username = username
     else:
         logger.error("Authorization credentials are missing. Make sure "
                      "that you have run `tx init` to setup your "
                      "credentials.")
开发者ID:transifex,项目名称:transifex-client,代码行数:13,代码来源:api.py

示例11: get_formats

    def get_formats(self, filename):
        _, extension = os.path.splitext(filename)
        try:
            formats = self.api.get('formats')
        except Exception as e:
            logger.error(e)
            raise

        def display_format(v):
            return '{} - {}'.format(v['description'], v['file-extensions'])

        formats = [(k, display_format(v)) for k, v in formats.items()
                   if extension in v['file-extensions']]
        if not formats:
            raise Exception(messages.TEXTS['formats']['empty'])
        return sorted(formats, key=lambda x: x[0])
开发者ID:transifex,项目名称:transifex-client,代码行数:16,代码来源:wizard.py

示例12: get_branch_from_options

def get_branch_from_options(options, project_root):
    """ Returns the branch name that needs to be used in command
    based on parser options.

    options: optparse parser options as returned from `parse()`
    project_root: project root directory
    """
    if not options.branch:
        return

    if options.branch != '-1':
        return options.branch

    branch = utils.get_current_branch(project_root)
    if not branch:
        logger.error("You specified the --branch option but current "
                     "directory does not seem to belong in any git repo.")
        sys.exit(1)
    return branch
开发者ID:transifex,项目名称:transifex-client,代码行数:19,代码来源:commands.py

示例13: main

def main(argv=None):
    """
    Here we parse the flags (short, long) and we instantiate the classes.
    """
    parser = tx_main_parser()
    options, rest = parser.parse_known_args()
    if not options.command:
        parser.print_help()
        sys.exit(1)

    utils.DISABLE_COLORS = options.color_disable

    # set log level
    if options.quiet:
        set_log_level('WARNING')
    elif options.debug:
        set_log_level('DEBUG')

    # find .tx
    path_to_tx = options.root_dir or utils.find_dot_tx()

    cmd = options.command
    try:
        utils.exec_command(cmd, rest, path_to_tx)
    except SSLError as e:
        logger.error("SSL error %s" % e)
    except utils.UnknownCommandError:
        logger.error("Command %s not found" % cmd)
    except AuthenticationError:
        authentication_failed_message = """
Error: Authentication failed. Please make sure your credentials are valid.
For more information, visit:
https://docs.transifex.com/client/client-configuration#-transifexrc.
"""
        logger.error(authentication_failed_message)
    except Exception as e:
        import traceback
        if options.trace:
            traceback.print_exc()
        else:
            msg = "Unknown error" if not str(e) else str(e)
            logger.error(msg)
    # The else statement will be executed only if the command raised no
    # exceptions. If an exception was raised, we want to return a non-zero exit
    # code
    else:
        return
    sys.exit(1)
开发者ID:transifex,项目名称:transifex-client,代码行数:48,代码来源:cmdline.py

示例14: _delete_translation

 def _delete_translation(self, project_details, resource, stats, language):
     """Delete a specific translation from the specified resource."""
     project_slug, resource_slug = resource.split('.', 1)
     if language not in stats:
         if not self.skip:
             msg = "Skipping %s: Translation does not exist."
             logger.warning(msg % (language))
         return
     if not self.force:
         teams = project_details['teams']
         if language in teams:
             msg = (
                 "Skipping %s: Unable to delete translation because it is "
                 "associated with a team.\nPlease use -f or --force option "
                 "to delete this translation."
             )
             logger.warning(msg % language)
             return
         if int(stats[language]['translated_entities']) > 0:
             msg = (
                 "Skipping %s: Unable to delete translation because it "
                 "is not empty.\nPlease use -f or --force option to delete "
                 "this translation."
             )
             logger.warning(msg % language)
             return
     try:
         self.do_url_request(
             'delete_translation', language=language, method="DELETE"
         )
         msg = "Deleted language %s from resource %s of project %s."
         logger.info(msg % (language, resource_slug, project_slug))
     except Exception as e:
         msg = "Unable to delete translation %s"
         logger.error(msg % language)
         if isinstance(e, SSLError) or not self.skip:
             raise
开发者ID:akx,项目名称:transifex-client,代码行数:37,代码来源:project.py

示例15: _delete_resource

 def _delete_resource(self, project_details, resource, stats, *args):
     """Delete a resource from Transifex."""
     project_slug, resource_slug = resource.split('.', 1)
     project_resource_slugs = [
         r['slug'] for r in project_details['resources']
     ]
     logger.info("Deleting resource %s:" % resource)
     if resource_slug not in project_resource_slugs:
         if not self.skip:
             msg = "Skipping: %s : Resource does not exist."
             logger.info(msg % resource)
         return
     if not self.force:
         slang = self.get_resource_option(resource, 'source_lang')
         for language in stats:
             if language == slang:
                 continue
             if int(stats[language]['translated_entities']) > 0:
                 msg = (
                     "Skipping: %s : Unable to delete resource because it "
                     "has a not empty %s translation.\nPlease use -f or "
                     "--force option to delete this resource."
                 )
                 logger.info(msg % (resource, language))
                 return
     try:
         self.do_url_request('delete_resource', method="DELETE")
         self.config.remove_section(resource)
         self.save()
         msg = "Deleted resource %s of project %s."
         logger.info(msg % (resource_slug, project_slug))
     except Exception as e:
         msg = "Unable to delete resource %s of project %s."
         logger.error(msg % (resource_slug, project_slug))
         if isinstance(e, SSLError) or not self.skip:
             raise
开发者ID:akx,项目名称:transifex-client,代码行数:36,代码来源:project.py


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