如何创建可重用的代码?

时间:2017-12-03 16:53:48

标签: python sqlalchemy reusability

我有很多实例看起来像下面的代码。我如何抽象它们并使它们可重复使用?

#json_generator() is a function that yields paginated json
#Foo and Bar are sqlalchemy models

def fetch_foo_data():
    URL = BASE_URL + ','.join(Foo.__table__.columns.keys())
    return json_generator(URL)

def fetch_bar_data():
    #Bar model has id as primary key that doesn't exist in the JSON data
    #so I am excluding it
    URL = BASE_URL + ','.join(Bar.__table__.columns.keys()[1:])
    return json_generator(URL)

def bulk_load_foo_data():
    for json in fetch_foo_data():
        foos = map(lambda foo: Foo(**foo), json)
        try:
            session.bulk_save_objects(foos)
            session.commit()
        except Exception as e:
            print e
            session.rollback()

def bulk_load_bar_data():
    for json in fetch_bar_data():
        bars = map(lambda bar: Bar(**bar), json)
        try:
            session.bulk_save_objects(bars)
            session.commit()
        except Exception as e:
            print e
            session.rollback()

1 个答案:

答案 0 :(得分:-1)

将对象传递给函数:

def fetch_object_data(obj, min=0, max=-1):
    URL = BASE_URL + ','.join(obj.__table__.columns.keys()[min:max])
    return json_generator(URL)

第二个功能:

def bulk_load_object_data(obj):
    for json in fetch_foo_data():
        foos = map(lambda foo: obj(**foo), json)
        try:
            session.bulk_save_objects(foos)
            session.commit()
        except Exception as e:
            print e
            session.rollback()

我不知道代码究竟在做什么......