Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > problem with writing a simple module

Reply
Thread Tools

problem with writing a simple module

 
 
nephish@xit.net
Guest
Posts: n/a
 
      05-22-2006
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

 
Reply With Quote
 
 
 
 
Larry Bates
Guest
Posts: n/a
 
      05-22-2006
http://www.velocityreviews.com/forums/(E-Mail Removed) 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
 
Reply With Quote
 
 
 
 
nephish@xit.net
Guest
Posts: n/a
 
      05-22-2006
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

 
Reply With Quote
 
Larry Bates
Guest
Posts: n/a
 
      05-22-2006
(E-Mail Removed) 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
 
Reply With Quote
 
nephish@xit.net
Guest
Posts: n/a
 
      05-22-2006
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

 
Reply With Quote
 
bruno at modulix
Guest
Posts: n/a
 
      05-22-2006
(E-Mail Removed) 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 '(E-Mail Removed)'.split('@')])"
 
Reply With Quote
 
Dennis Lee Bieber
Guest
Posts: n/a
 
      05-22-2006
On 22 May 2006 06:47:53 -0700, (E-Mail Removed) 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
(E-Mail Removed) (E-Mail Removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (E-Mail Removed))
HTTP://www.bestiaria.com/
 
Reply With Quote
 
nephish@xit.net
Guest
Posts: n/a
 
      05-23-2006
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

 
Reply With Quote
 
Dennis Lee Bieber
Guest
Posts: n/a
 
      05-23-2006
On 23 May 2006 06:25:43 -0700, (E-Mail Removed) 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
(E-Mail Removed) (E-Mail Removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (E-Mail Removed))
HTTP://www.bestiaria.com/
 
Reply With Quote
 
nephish@xit.net
Guest
Posts: n/a
 
      05-23-2006
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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: module docstring, documentation,anything? please note is the module type/object NOT some module Maric Michaud Python 0 06-24-2006 12:42 PM
Module file writing problem webmaster@explodingpickle.org Perl Misc 1 04-30-2005 12:34 PM
Any problems with writing the information into a file - Multi-users perform writing the same file at the same time ???? HNguyen ASP .Net 4 12-21-2004 01:53 PM
Problem with module variables / module deallocation . . . alejandro david weil Python 0 05-12-2004 03:26 AM
Re: Http Module Problem: not all requests hit my module why? Jiong Feng ASP .Net 2 11-29-2003 05:14 PM



Advertisments