-3

I have many instances that look like the code below. How can I abstract them and make them reusable?

#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()
drum
  • 5,416
  • 7
  • 57
  • 91

1 Answers1

-1

Pass the object to function:

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

For second function:

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()

I don't know what's the code actually doing...

M. Volf
  • 1,259
  • 11
  • 29
  • Can someone explain me why did he downvote? I don't care about my rep., but I really don't understand what I did wrong... `:(` – M. Volf Dec 03 '17 at 17:00