0

So some code in MainApp.py goes like this, the lines I am concerned about are where DBQuery occurs. DB302.py is in the same folder as MainApp.py and contains a class called DB302 with member methods query shown below. Why does it only work when I use DB302.DB302.query(DBQuery...) where DBQuery is already an instance of DB302.DB302... Is there a way to not have to use firstly, the instance DBQuery = DB302.DB302() instead just DBQuery = DB302 and also to be able to use it then as `DBQuery.query(Instance, var1, var2).

My second question pertains to the use of self.method or variable in DB302.py. Have I used them correctly? I am getting ThrowsU() showing up now, and can't figure out why. My DB has been set up to work correctly and I can access it through the python terminal. Id is a primary key and I am incrementing it for each test case.

#MainApp.py
import DB302

class MainApp(object):

@cherrypy.expose
def default(self, *args, **kwargs):     
    page = "<b>&quot;args&quot; has %d variables</b><br/>\n" % len(args)
    for x in xrange(0, len(args)):
        if args[x] == "":
            page += "<i>error</i>\n"
        else:
            page += args[x] + "<br/>\n"

    page += "<b>&quot;cherrypy.request.params&quot; has %d variablez</b><br/>\n" % len(cherrypy.request.params)
    for key, value in cherrypy.request.params.items():
        if cherrypy.request.params[key] == "":
            page += "<i>empty</i>\n"
        elif key == "username":
            DBQuery = DB302.DB302()
            data = DB302.DB302.query(DBQuery, 'SELECT * FROM test', 'SELECT')
        else:
            page += key + " = " + value + "<br/>\n"

    page += """
            <form name="form1" method="POST" action="/testURL/part2">
                <input name="username" type="text" maxlength="256" autocomplete="off">
                </input>
            </form>
            """

    return page

#DB302.py
import sqlite3

class DB302(object):

    def __init__(self):
        print "<b>Within DB302</b><br/>\n"

    def throws(self):
        raise RuntimeError('Connection to DB failed, terminating...')

    def throwsQ(self):
        raise RuntimeError('Error in DB query, terminating...')

    def throwsU(self):
        raise RuntimeError('Unknown DB error encountered...')

    def connect(self):
        # Where the DB connection will be made
        CS302="<!-- Private -->" # The datbase file is on my desktop

        try:
            DBCon=sqlite3.connect(CS302)
            cursor=DBCon.cursor()
            return True
        except IOError:
            self.throws()
        except:
            self.throwsU()
        else:
            return False

    def disconnect(self):
        # Used to disconnect...

        try:
            self.cursor.close()
            return True
        except IOError:
            self.throws()
        except:
            self.throwsU()
        else:
            return False

    def query(self, queryString, queryType):
        # Queries will be made here

        if self.connect():
            try:
                self.cursor.execute(queryString)
                if queryType == "SELECT":
                    # return all the rows if there's a select query
                    allRows = self.cursor.fetchall()
                    return allRows
                elif queryType == "DELETE":
                    # return affected rows if there's a deletion
                    rowsAffected = self.cursor.rowcount()
                    self.DBCon.commit()
                    return rowsAffected
                elif queryType == "INSERT":
                    # return true if success
                    self.DBCon.commit()
                    return True
                elif queryType == "CREATE":
                    self.DBCon.commit()
                    return True
                else:
                    return False
            except IOError:
                self.throwsQ()
            except:
                self.throwsU()
        else:
            return False
Supernovah
  • 1,946
  • 12
  • 34
  • 50
  • Okay for some reason the expected instantiation using `DBQuery = DB302.DB302()` then `DBQuery.query(Arg1, Arg2)` now works. Any way to reduce it to DB302() regardless though? Stilling getting `throwsU()` from within the query method (line 3 from bottom in this copy paste) – Supernovah Mar 21 '12 at 02:20

1 Answers1

1

To make calling your class method easier you can do:

from DB302 import DB302 as DBQuery
...
DBQuery.query(Arg1, Arg2)

For your second question:
You should avoid, when possible, using a so-called "naked" except, i.e. except:.
This delightful construct has the unfortunate property of making debugging more difficult than it need be.

So I would recommend instead taking the advice from here: http://wiki.python.org/moin/HandlingExceptions
And catching all exceptions in such a way that you print out information about the exception:

import sys
...
    except:
        e = sys.exc_info()[1]
        print e

I also notice that your custom-exceptions do not inherit from Exception.
This question and accompanying answers may provide some insight: Proper way to declare custom exceptions in modern Python?

Community
  • 1
  • 1
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
  • Okay thanks for the advice! For error handling I removed my overloading of the unknown exception and was able to discover the problem. It was the scope of `cursor`. It seems I have to write anything in the same class as `self.variable` or `self.method` if I want to use it in another method even in the same class. Why is this? Is there a was to localise a variable to the own class without using a reference object? I am aware python doesn't strictly have private, public and global variables. – Supernovah Mar 21 '12 at 02:43
  • You're most welcome. Good job on finding the error. In response to your question: You must use `self` to bind the variable to the instance of the class. Otherwise the variable is a class variable, and you won't need those often if at all. – mechanical_meat Mar 21 '12 at 02:46