Flask Snippets

Snippets are unofficial and unmaintained.

This is an archived view of user-submitted snippets. Despite being hosted on the Flask site, they are not official. No Flask maintainer has curated or checked the snippets for security, correctness, or design.

Simple insertion and row id

Posted by WillyFrog on 2010-08-05 @ 23:50 and filed in Database

This function lets you abstract the insertion into the database and get it's last id. This example uses sqlite3.

def insert(table, fields=(), values=()):
    # g.db is the database connection
    cur = g.db.cursor()
    query = 'INSERT INTO %s (%s) VALUES (%s)' % (
        ', '.join(fields),
        ', '.join(['?'] * len(values))
    cur.execute(query, values)
    id = cur.lastrowid
    return id

This snippet by WillyFrog can be used freely for anything you like. Consider it public domain.