mardi 8 mars 2016

Insert form fields into database (Bottle, sqlite)

There has to be a better way to do this.. I've read the bottle documentation, but it doesn't really help all that much. This works, but it's dirty. Seems like I'm missing something.

@route('/client/new', method="POST")
def add_new_client():
    c = db.cursor()
    query = """INSERT INTO Clients VALUES(NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"""

    try:
        r = request.POST

        d = r['LastContact'].split('/') # mm/dd/yyyy
        try: lastcontact = datetime(int(d[2]), int(d[0]), int(d[1]))
        except Exception as e: lastcontact = datetime.now()

        try: taxExempt = r['TaxExempt'] 
        except Exception as e: taxExempt = 0

        c.execute(query, (r['FirstName'], r['LastName'], r['Address1'], r['Address2'], r['City'], r['State'], r['Zip'],
                 r['HomePhone'], r['CellPhone'], r['WorkPhone'], r['Email'], r['ContactMethod'], r['ContactTime'],
                 r['ContactFrequency'], lastcontact, taxExempt, r['TaxID'], r['Notes']))
        db.commit()
    except Exception as e:
        print "ERROR %s" % e
    redirect('/client/%d' % c.lastrowid)
    c.close()

Aucun commentaire:

Enregistrer un commentaire