1

Can somebody explain me the last line return (rv[0] if rv else None) if one else rv ? Especially the role of one.

def query_db(query, args=(), one=False):
    cur = g.db.execute(query, args)
    rv = [dict((cur.description[idx][0], value)
               for idx, value in enumerate(row)) for row in cur.fetchall()]
    return (rv[0] if rv else None) if one else rv
Max
  • 13
  • 2

2 Answers2

2

one indicates whether or not to return only a single record. If one is true then it returns the first (rv[0]) if there are records to be found (if rv), otherwise it returns all the records.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

By default, one is False, so by default the list-of-dicts generated from the fetchall gets returned.

If you pass True for one, you get only the first row (turned into a dict) of the query, or None if the query didn't return any rows.

agf
  • 171,228
  • 44
  • 289
  • 238