problem with writing a simple module

Discussion in 'Python' started by nephish@xit.net, May 22, 2006.

  1. Guest

    ello there. i am having a problem getting a module to work right.

    i wrote a class that is going to be used in a few different scripts in
    the same directory.

    it looks like this:

    #!/usr/bin/python

    import MySQLdb

    class DbConnector(object):
    """
    Database Connection object.
    class receives the db argument to specify the database.
    """

    def __init__(self, db='test_db', host="10.10.10.16",user="me",
    passwd="mypass"):
    self.host = host
    self.user = user
    self.passwd = passwd
    self.db = db
    # Unpack Other Database Arguments Here
    self.CreateConnection()

    def createConnection(self):
    self.connection = MySQLdb.connect(self.host, self.user, self.passwd,
    self.db)

    def killConnection(self):
    self.connection.close()

    def getMany(self, sql_statement):
    cursor = self.connection.cursor()
    try:
    cursor.execute(sql_statement)
    result = cursor.fetchall()
    self.connection.close()
    return result
    except:
    self.connection.close()

    the file is saved as DbConnector.py and made executable.
    then i get this in idle

    >> import DbConnector
    >> x = DbConnector()


    then it tells me that the module object is not callable.

    this works though
    >> import DbConnector
    >> x = DbConnector
    >> x.db = 'other_db'
    >> results = x.getOne("SELECT * FROM `stuff`")


    it tells me that the module has no attribute getOne.

    i am really not trying for an attribute, but a method.

    anyone know what i am doing wrong?

    thanks
    , May 22, 2006
    #1
    1. Advertising

  2. Larry Bates Guest

    wrote:
    > ello there. i am having a problem getting a module to work right.
    >
    > i wrote a class that is going to be used in a few different scripts in
    > the same directory.
    >
    > it looks like this:
    >
    > #!/usr/bin/python
    >
    > import MySQLdb
    >
    > class DbConnector(object):
    > """
    > Database Connection object.
    > class receives the db argument to specify the database.
    > """
    >
    > def __init__(self, db='test_db', host="10.10.10.16",user="me",
    > passwd="mypass"):
    > self.host = host
    > self.user = user
    > self.passwd = passwd
    > self.db = db
    > # Unpack Other Database Arguments Here
    > self.CreateConnection()
    >
    > def createConnection(self):
    > self.connection = MySQLdb.connect(self.host, self.user, self.passwd,
    > self.db)
    >
    > def killConnection(self):
    > self.connection.close()
    >
    > def getMany(self, sql_statement):
    > cursor = self.connection.cursor()
    > try:
    > cursor.execute(sql_statement)
    > result = cursor.fetchall()
    > self.connection.close()
    > return result
    > except:
    > self.connection.close()
    >
    > the file is saved as DbConnector.py and made executable.
    > then i get this in idle
    >
    >>> import DbConnector
    >>> x = DbConnector()

    >
    > then it tells me that the module object is not callable.
    >
    > this works though
    >>> import DbConnector
    >>> x = DbConnector
    >>> x.db = 'other_db'
    >>> results = x.getOne("SELECT * FROM `stuff`")

    >
    > it tells me that the module has no attribute getOne.
    >
    > i am really not trying for an attribute, but a method.
    >
    > anyone know what i am doing wrong?
    >
    > thanks
    >

    You can do either:

    from DbConnector import *
    x=DbConnector()

    or (preferred method these days)

    import DbConnector
    x=DbConnector.DbConnector()

    When you zay x=DbConnector all you are doing is setting a
    variable (pointer) x that points to the class DBconnector,
    which is basically an alias. x in fact would not have
    a getOne method as it hasn't been instantiated yet.

    -Larry Bates
    Larry Bates, May 22, 2006
    #2
    1. Advertising

  3. Guest

    ok, cool, and thanks very much. That worked.
    thanks for the info too.
    i am still new at the OO thing, just tired of doing a copy and paste
    over and over again.

    thanks again
    , May 22, 2006
    #3
  4. Larry Bates Guest

    wrote:
    > ok, cool, and thanks very much. That worked.
    > thanks for the info too.
    > i am still new at the OO thing, just tired of doing a copy and paste
    > over and over again.
    >
    > thanks again
    >

    Glad that helped. The OO "stuff" does require a new
    set of understanding, but once you get it you can write
    reusable classes and productivity really begins to take
    off.

    If you haven't yet picked one up, get a copy of the
    Python Cookbook (really good) and if you do Windows
    get a copy of Python Programming on Win32.

    -Larry
    Larry Bates, May 22, 2006
    #4
  5. Guest

    yeah, i have thought of picking that one up. That one, or nutshell.
    i got programming python, which was way over my head, then learning
    python, which has helped me a great deal.

    thanks
    , May 22, 2006
    #5
  6. wrote:
    > ello there. i am having a problem getting a module to work right.
    >
    > i wrote a class that is going to be used in a few different scripts in
    > the same directory.
    >
    > it looks like this:
    >
    > #!/usr/bin/python


    This is not needed for a module.

    (snip code)
    > the file is saved as DbConnector.py


    The most common convention is to name modules all_lower, and keep
    CamelCaseNames for classes.

    > and made executable.


    This is not needed for a module.

    You may want to make "scripts" (ie: modules that has to be runned as
    main program" executables and then add the shebang. Other modules (the
    ones that are meant to be used via import) don't need this.

    > then i get this in idle
    >
    >
    >>>import DbConnector
    >>>x = DbConnector()

    >
    >
    > then it tells me that the module object is not callable.


    cf Larry's answer. You may also want to browse the very recent (may 19)
    thread named "noob import question".

    --
    bruno desthuilliers
    python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
    p in ''.split('@')])"
    bruno at modulix, May 22, 2006
    #6
  7. On 22 May 2006 06:47:53 -0700, declaimed the following
    in comp.lang.python:


    > def createConnection(self):
    > self.connection = MySQLdb.connect(self.host, self.user, self.passwd,
    > self.db)
    >

    I believe the recommendation, at least for db-api adapters, is to
    use keyword calling, since so many arguments are optional.

    ... = MySQLdb.connect(host=self.host, user=...)

    > >> import DbConnector
    > >> x = DbConnector()

    >
    > then it tells me that the module object is not callable.
    >

    Well, look at the error: the MODULE is not callable. It isn't. It's
    a "container" holding items. In your case, that is just one item -- a
    class that is also called "DbConnector".

    To access items within a module, you have to specify both the
    container and the item...

    x = DbConnector.DbConnector()
    ^container ^item-in-container

    > this works though
    > >> import DbConnector
    > >> x = DbConnector
    > >> x.db = 'other_db'
    > >> results = x.getOne("SELECT * FROM `stuff`")

    >
    > it tells me that the module has no attribute getOne.
    >

    Again, notice the MODULE... All you did was make "x" another name
    for the container, and the container doesn't have a class or function
    named "getOne" (not that the class you showed at the start has a
    "getOne" either <G>).


    Separate note. You should change all your database queries so that
    parameter substitution is performed by the .execute*() methods...
    --
    Wulfraed Dennis Lee Bieber KD6MOG

    HTTP://wlfraed.home.netcom.com/
    (Bestiaria Support Staff: )
    HTTP://www.bestiaria.com/
    Dennis Lee Bieber, May 22, 2006
    #7
  8. Guest

    ok, thanks everyone. The funny thing about the name conventions is, i
    was just two days ago looking around on the web for the best way to go
    about consistancy in variable names, class names, etc..

    i have the module working now. thanks to you guys. And i think i
    understand the container name | object name paradigm.

    i did not get the suggestion to change all my database queries so the
    parameter substitution is performed by the .execute*() methods..

    that one went over me head.

    thanks for all the help, guys
    , May 23, 2006
    #8
  9. On 23 May 2006 06:25:43 -0700, declaimed the following
    in comp.lang.python:

    >
    > i did not get the suggestion to change all my database queries so the
    > parameter substitution is performed by the .execute*() methods..
    >

    Your example was just a simple "select * from a_table". But if you
    intend to expand to allowing insertions, updates, and "where" clauses,
    with values that are coming from the user...

    sql = "update a_table set fld_y = %s where fld_x = %s"
    crs.execute(sql, (new_value, match_value))

    The .execute() method will make sure the data values have the
    correct quoting for the arguments; strings will have quotes around them,
    quotes INSIDE strings will be escaped, etc. And you don't open yourself
    up to an injection attack.

    For example, say some malicious user entered:

    junk";select "Got you

    on some form for the new_value. If you don't take care when putting
    together the sql to be executed (say you know that new_value is a string
    so you need quotes around it) you might generate and submit:

    update a_table set fld_y = "junk";select "Got you" where fld_x = 12

    The first and last " are those you'd have put in, knowing you had to
    create a string value. But if you didn't parse the value first for
    escapes, the above code sets ALL records to have "junk", and then
    creates a result set containing a constant "Got you" (though, since you
    were executing an update, you aren't expecting to read a result set).

    Instead, letting the .execute() method do the substitution (as I
    show above -- though the %s placeholders may be different depending on
    the DB-API adapter in use) relies on the adapter to properly handle the
    substitution... It know that strings need quoting, and to escape what is
    inside. The resulting sql might look like:

    update a_table set fld_y = "junk\";select \"Got you" where fld_x =
    12

    which only sets fld_y to the string value of
    junk";select "Got you
    for rows with fld_x = 12

    --
    Wulfraed Dennis Lee Bieber KD6MOG

    HTTP://wlfraed.home.netcom.com/
    (Bestiaria Support Staff: )
    HTTP://www.bestiaria.com/
    Dennis Lee Bieber, May 23, 2006
    #9
  10. Guest

    ok, what i posted above had the getOne method, the whole class has a
    function for getMany, update, and Insert.

    none of this will be used by an end user, it kinda runs in the
    background. But, if you have a good link to the docs on the API, i
    would like to see it. Still kinda new at this.

    thanks
    , May 23, 2006
    #10
  11. On 23 May 2006 09:24:01 -0700, declaimed the following
    in comp.lang.python:

    >
    > none of this will be used by an end user, it kinda runs in the
    > background. But, if you have a good link to the docs on the API, i
    > would like to see it. Still kinda new at this.
    >

    For the DB-API, PEP 249 is the main source. There may be "manuals"
    available for details peculiar to any specific adapter.

    Google should find them...
    --
    Wulfraed Dennis Lee Bieber KD6MOG

    HTTP://wlfraed.home.netcom.com/
    (Bestiaria Support Staff: )
    HTTP://www.bestiaria.com/
    Dennis Lee Bieber, May 24, 2006
    #11
  12. Guest

    cool, thanks, i was running on some thinner examples i found on the
    net.
    , May 24, 2006
    #12
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jiong Feng
    Replies:
    2
    Views:
    534
    Wade A. Hilmo [MS]
    Nov 29, 2003
  2. HNguyen
    Replies:
    4
    Views:
    2,400
    HNguyen
    Dec 21, 2004
  3. alejandro david weil
    Replies:
    0
    Views:
    312
    alejandro david weil
    May 12, 2004
  4. Maric Michaud
    Replies:
    0
    Views:
    7,186
    Maric Michaud
    Jun 24, 2006
  5. Module file writing problem

    , Apr 30, 2005, in forum: Perl Misc
    Replies:
    1
    Views:
    79
    Brian McCauley
    Apr 30, 2005
Loading...

Share This Page