I'm having a simple problem. I'm using this class to do some stuff with another module. Now, for some reason the self.database and other variables are not able to be accessed by the other methods. I thought _init_ was suppose to work as a constructor, thus the other methods should have access to any variables define as self. that are set in _init_. Help? Please?

'''
Created on Jun 5, 2009

@author: Steven Norris

This module provides basic utilities for the FLOSS mole spiders.
'''

class FLOSSmoleutils:
    '''
    This method provides the ability to gather a page
    '''
    def _init_(self):
        try:
            dbfile = open("dbInfo.txt", 'r')
        except:
            raise Exception("Database file error: dbinfo.txt")
        try:
            self.host = dbfile.readline().strip()
            self.port = int(dbfile.readline().strip())
            self.username = dbfile.readline().strip()
            self.password = dbfile.readline().strip()
            self.database = dbfile.readline().strip()
            self.db=MySQLdb.connect(host=self.host, user=self.username, passwd=self.password, db=self.database)
            self.cursor = self.db.cursor()
        except:
            print("Database connection failed.")
        
    def get_page(self,url, conn):
        try:
            conn.request("GET",url)
            resp=conn.getresponse()
            html_page=resp.read()
            html_page=str(html_page)
            return html_page
        except:
            print ("The page request failed.")
    
    
    '''
    This method provides the ability to insert into a database
    '''
    def db_insert(self,query_string,*params):
        try:
            self.cursor.execute(query_string, params)
            print ("Inserted into: "+self.database+".\n")  
        except:
            print("Database insertion failed for: "+self.database+"\n")

Recommended Answers

All 3 Replies

The constructor has two underscores on either side of the name. def __init__(self) .

Wow. I knew it would be somethign simple like that. The database requests are still failing though. They worked fine when I put the code directly into main, but that was repetative and ugly. Any suggestions?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.