adduser.pyThis Python script, with its associated form, adds a new member to a database table of users.
Try it: add user
01: #!/usr/bin/python
02: import cgi, cgitb, sys
03: import MySQLdb
04: import dbname
05: cgitb.enable() # formats errors in HTML
06:
07: sys.stderr = sys.stdout
08: print "Content-type: text/html"
09: print
10: print '''<html>
11: <head>
12: <title>Add User</title>
13: </head>
14: <body>'''
15:
16: form = cgi.FieldStorage()
17:
18: fields = ["fullname", "email", "username", "password"]
19: errors = False
20:
21: print '<dir><pre>'
22: for field in fields:
23: if (not form.has_key(field)):
24: print 'missing <b>%s</b>' % field
25: errors = True
26: print '</pre></dir>'
27: if (errors):
28: print '<p>Use back button to return to the sign-up page.'
29: print '</body></html>'
30: sys.exit()
31:
32: db = dbname.dbopen()
33: cur = db.cursor()
34:
35: username = form["username"].value
36:
37: try:
38: cur.execute("SELECT uid FROM users WHERE username= '%s'" % username)
39: rows = cur.fetchall()
40: if (cur.rowcount>0):
41: print '<p>That username is already taken.'
42: print '</body></html>'
43: sys.exit()
44: except MySQLdb.Error, e:
45: print e
46: sys.exit()
47:
48:
49:
50: try:
51: cur.execute("""INSERT INTO users ( username, password, fullname, email, created, modified )
52: VALUES (
53: '%s',
54: '%s',
55: '%s',
56: '%s',
57: now(), now() )""" % (username,
58: form["password"].value, form["fullname"].value, form["email"].value) )
59: cur.close()
60: db.close()
61: except MySQLdb.Error, e:
62: print e
63:
64: print '<p>%s has been added to the database.' % form["fullname"].value
65:
66: print '<p><table border>'
67: for field in fields:
68: print '<tr><td>%s<td>%s' % (field, form[field].value)
69: print '</table>'
70:
71:
72: print '</body></html>'
Maintained by John Loomis, updated Sun Mar 02 21:18:08 2008