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

时间:2016-01-02 16:17:19

标签: python try-catch except

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)

1 个答案:

答案 0 :(得分:8)

你可以写一个装饰者:

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)