質問

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!

役に立ちましたか?

解決 2

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!

他のヒント

There's hardly any real code in either of those functions. Half of each is a slow recreation of the list() constructor. Once you get rid of that, you're left with a conditional, which can easily be condensed to a single line. So:

def getAllUsersFrom(db, asJSON=False):
    users = list(db.users.find())
    return json.dumps(users, default=json_util.default) if asJSON else users

This seems simple enough to me to not bother refactoring. There are some commonalities between the two functions, but breaking them out wouldn't reduce the number of lines of code any further.

One direction for possible simplification, however, is to not pass in a flag to tell the function what format to return. Let the caller do that. If they want it as a list, there's list(). For JSON, you can provide your own helper function. So, just write your functions to return the desired iterator:

def getAllUsersFrom(db):
    return db.users.find()

def getAllMarkersFrom(db):
    return db.markers.find()

And the helper function to convert the result to JSON:

def to_json(cur):
    return json.dumps(list(cur), default=json_util.default)

So then, putting it all together, you just call:

markers = list(getAllMarkersFrom(mydb))

or:

users = to_json(getAllUsersFrom(mydb))

As you need.

If you really want a generic function for requesting various types of records, that'd be:

def getAllRecordsFrom(db, kind):
    return getattr(db, kind).find()

Then call it:

users = list(getAllRecordsFrom(mydb, "users"))

etc.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top