繁体   English   中英

如何组织我的代码,以便重复尝试除了子句只存在一次?

[英]How can I organize my code so that repeating try except clauses only exist once?

try语句中的代码将会有所不同,但try except语句本身始终是相同的。 如何减少冗余?

def cloudflare_add_zone(ctx, url, jumpstart, organization):
    try:

        if organization:
            ctx.create_zone(url, jumpstart, organization)
        else:
            ctx.create_zone(url, jumpstart)
        click.echo('Zone successfully created: %s' % url)

    except HTTPServiceError, e:
        code = str(e.details['errors'][0]['code'])
        message = e.details['errors'][0]['message']
        click.echo(code + ":" + message)

def cloudflare_add_record(ctx, domain, name, type, content, ttl):
    try:

        payload = {
            'type': type,
            'name': name,
            'content': content
        }
        if ttl:
            payload['ttl'] = ttl
        zone_id = ctx.get_zone_by_name(domain).get('id')
        ctx.create_dns_record(zone_id, payload)

    except HTTPServiceError, e:
        code = str(e.details['errors'][0]['code'])
        message = e.details['errors'][0]['message']
        click.echo(code + ":" + message)

你可以写一个装饰者:

from functools import wraps

def http_safe(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except HTTPServiceError, e:
            click.echo('{[code]}: {[message]}'.format(e.details['errors'][0]))
   return wrapper

然后使用它:

@http_safe
def cloudflare_add_zone(ctx, url, jumpstart, organization):
    if organization:
        ctx.create_zone(url, jumpstart, organization)
    else:
        ctx.create_zone(url, jumpstart)
    click.echo('Zone successfully created: %s' % url)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM