Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There's hardly any real code in either of those functions. Half of each is a slow recreation of the <code>list()</code> constructor. Once you get rid of that, you're left with a conditional, which can easily be condensed to a single line. So:</p> <pre><code>def getAllUsersFrom(db, asJSON=False): users = list(db.users.find()) return json.dumps(users, default=json_util.default) if asJSON else users </code></pre> <p>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.</p> <p>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 <code>list()</code>. For JSON, you can provide your own helper function. So, just write your functions to return the desired iterator:</p> <pre><code>def getAllUsersFrom(db): return db.users.find() def getAllMarkersFrom(db): return db.markers.find() </code></pre> <p>And the helper function to convert the result to JSON:</p> <pre><code>def to_json(cur): return json.dumps(list(cur), default=json_util.default) </code></pre> <p>So then, putting it all together, you just call:</p> <pre><code>markers = list(getAllMarkersFrom(mydb)) </code></pre> <p>or:</p> <pre><code>users = to_json(getAllUsersFrom(mydb)) </code></pre> <p>As you need.</p> <p>If you really want a generic function for requesting various types of records, that'd be:</p> <pre><code>def getAllRecordsFrom(db, kind): return getattr(db, kind).find() </code></pre> <p>Then call it:</p> <pre><code>users = list(getAllRecordsFrom(mydb, "users")) </code></pre> <p>etc.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload