I wanted to shorten my code, since i`m having more functions like this. I was wondering if I could use getattr() to do something like this guy asked.
Well, here it goes what I`ve got:
def getAllMarkersFrom(db, asJSON=False):
'''Gets all markers from given database. Returns list or Json string'''
markers = []
for marker in db.markers.find():
markers.append(marker)
if not asJSON:
return markers
else:
return json.dumps(markers, default=json_util.default)
def getAllUsersFrom(db, asJSON=False):
'''Gets all users from given database. Returns list or Json string'''
users = []
for user in db.users.find():
users.append(user)
if not asJSON:
return users
else:
return json.dumps(users, default=json_util.default)
I`m using pymongo
and flask
helpers on JSON
.
What I wanted is to make a single getAllFrom(x,db)
function that accepts any type of object. I don`t know how to do this, but I wanted to call db.X.find()
where X is passed through the function.
Well, there it is. Hope you can help me. Thank you!
I would say that its better to have separate functions for each task. And then you can have decorators for common functionality between different functions. For example:
@to_json
def getAllUsersFrom(db):
return list(db.users.find())
enjoy!