Permalink
Browse files

Factor business logic into bl.py and DB interface into dblib.py.

  • Loading branch information...
jmafc committed Jun 12, 2011
1 parent 4e8669b commit 846f286679e381675660e6e6255b98c8fc14eb08
Showing with 126 additions and 41 deletions.
  1. +2 −0 .gitignore
  2. +29 −0 LICENSE
  3. +5 −0 README
  4. +30 −0 cmdline/bl.py
  5. +9 −41 cmdline/dbapp.py
  6. +51 −0 cmdline/dblib.py
View
@@ -0,0 +1,2 @@
+*.pyc
+*~
View
29 LICENSE
@@ -0,0 +1,29 @@
+Copyright (c) 2011 by Joe Abbate.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+
+ * Neither the name of the Pyrseas project nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
View
5 README
@@ -1,4 +1,9 @@
+Database User Interface Tutorial
+================================
+
Python programs to explore design of database user interfaces to
PostgreSQL. This follows a series of blog posts at
http://pyrseas.wordpress.com/ starting with
http://pyrseas.wordpress.com/2011/05/23/user-interfaces-for-databases/.
+
+This is distributed under the BSD license.
View
@@ -0,0 +1,30 @@
+# -*- coding: utf-8 -*-
+
+from dblib import fetchall, fetchone, execute
+
+
+def get_all(dbconn):
+ return fetchall(
+ dbconn, "SELECT id, title, release_year FROM film ORDER BY id")
+
+
+def get_one(dbconn, id):
+ return fetchone(
+ dbconn, "SELECT id, title, release_year FROM film WHERE id = %s",
+ (id,))
+
+
+def insert(dbconn, film):
+ return execute(
+ dbconn, "INSERT INTO film VALUES "
+ "(%(id)s, %(title)s, %(release_year)s)", film.__dict__)
+
+
+def update(dbconn, film):
+ return execute(
+ dbconn, "UPDATE film SET title = %s, release_year = %s "
+ "WHERE id = %s", (film.title, film.release_year, film.id))
+
+
+def delete(dbconn, id):
+ return execute(dbconn, "DELETE FROM film WHERE id = %s", (id,))
View
@@ -2,7 +2,9 @@
from optparse import OptionParser
-from psycopg2 import connect
+from dblib import connect
+from bl import get_all, get_one
+from bl import insert, update, delete
class Film(object):
@@ -50,41 +52,16 @@ def get_by_key(dbconn):
print "Id must be a positive integer"
continue
break
- curs = dbconn.cursor()
- try:
- curs.execute("SELECT id, title, release_year FROM film WHERE id = %s",
- (id,))
- except Exception, exc:
- curs.close()
- dbconn.rollback()
- print "ERROR: ", exc.args[0]
- return None
- row = curs.fetchone()
- curs.close()
- dbconn.commit()
+ row = get_one(dbconn, id)
if not row:
print "Film not found"
return None
return Film(row[0], row[1], row[2])
-def execute(dbconn, query, args):
- curs = dbconn.cursor()
- try:
- curs.execute(query, args)
- except Exception, exc:
- curs.close()
- dbconn.rollback()
- print "ERROR: ", exc.args[0]
- return False
- curs.close()
- dbconn.commit()
- return True
-
-
def dbapp():
(opts, args) = OptionParser("usage: %prog dbname").parse_args()
- dbconn = connect("dbname=%s" % args[0])
+ dbconn = connect(args[0])
while True:
for cmd in ['Add', 'List', 'Update', 'Delete', 'Quit']:
print ' ', cmd[:1], '-', cmd
@@ -93,16 +70,10 @@ def dbapp():
break
elif cmd == 'A':
film = edit(Film())
- if execute(dbconn, "INSERT INTO film VALUES "
- "(%(id)s, %(title)s, %(release_year)s)", film.__dict__):
+ if insert(dbconn, film):
print "Film '%r' added" % film
elif cmd == 'L':
- curs = dbconn.cursor()
- curs.execute("SELECT id, title, release_year FROM film "
- "ORDER BY id")
- rows = curs.fetchall()
- curs.close()
- dbconn.commit()
+ rows = get_all(dbconn)
print " Id %-32s Year" % 'Title'
for row in rows:
print "%6d %-32s %4d" % (row[0], row[1], row[2])
@@ -112,9 +83,7 @@ def dbapp():
continue
print "Updating '%r'" % old_film
film = edit(old_film, True)
- if execute(dbconn, "UPDATE film SET title = %s, release_year = %s "
- "WHERE id = %s", (film.title, film.release_year,
- film.id)):
+ if update(dbconn, film):
print "Film '%r' updated" % film
elif cmd == 'D':
old_film = get_by_key(dbconn)
@@ -123,8 +92,7 @@ def dbapp():
confirm = raw_input("Delete film '%r' (y/n) [n]: " % old_film)
if not confirm.lower()[:1] == 'y':
continue
- if execute(dbconn, "DELETE FROM film WHERE id = %s",
- (old_film.id,)):
+ if delete(dbconn, old_film.id):
print "Film '%r' deleted" % old_film
else:
print "Invalid choice"
View
@@ -0,0 +1,51 @@
+# -*- coding: utf-8 -*-
+
+from psycopg2 import connect as pgconnect
+
+
+def connect(dbname):
+ return pgconnect("dbname=%s" % dbname)
+
+
+def fetchall(dbconn, query):
+ curs = dbconn.cursor()
+ try:
+ curs.execute(query)
+ except Exception, exc:
+ curs.close()
+ dbconn.rollback()
+ print "ERROR: ", exc.args[0]
+ return None
+ rows = curs.fetchall()
+ curs.close()
+ dbconn.commit()
+ return rows
+
+
+def fetchone(dbconn, query, args):
+ curs = dbconn.cursor()
+ try:
+ curs.execute(query, args)
+ except Exception, exc:
+ curs.close()
+ dbconn.rollback()
+ print "ERROR: ", exc.args[0]
+ return None
+ row = curs.fetchone()
+ curs.close()
+ dbconn.commit()
+ return row
+
+
+def execute(dbconn, query, args):
+ curs = dbconn.cursor()
+ try:
+ curs.execute(query, args)
+ except Exception, exc:
+ curs.close()
+ dbconn.rollback()
+ print "ERROR: ", exc.args[0]
+ return False
+ curs.close()
+ dbconn.commit()
+ return True

0 comments on commit 846f286

Please sign in to comment.