python database query using two scripts
Question: I have two scripts main.py and testscript.py. On main.py is the function to
connect to my database and on testscript.py I will use as my query request and
call this query to my database by using main.py. Adding to main.py

    
    
     if __name__ == '__main__':
            q = "select domain_name from domains_domain limit 10"
            query(q)
    

and run script

> python main.py

working as is expected, but I don't know how to do this on testscript.py

Here is main.py

    
    
    import MySQLdb
    from localdb import *
    import socket
    
    host = socket.gethostname()
    error_report = "Check if MySQL service is running and user name/password are correct" 
    
    class WeekQuery:
        def __init__(self, name):
            self.name = name
    
        def query(self):
            cursor = None
            results = None
            week_number = None
            #Connecting to production database
            if host == 'db01':
                try:
                    db = MySQLdb.connect("db01", "myuser", "mypass", "mydb")
                    cursor = db.cursor()
                    cursor.callproc(self)
                    results = cursor.fetchall()
                    week_number = [i[0] for i in cursor.description]
                except MySQLdb.Error, e:
                    try:
                        print "%s \n MySQL Error [%d]: %s" % (error_report, e.args[0], e.args[1])
                    except IndexError:
                        print "%s \n MySQL Error: %s " % (error_report, str(e))
            else:
    
                #local database rename localdb.py_example to localdb.py
                try:
                    db = MySQLdb.connect(host=MYSQL_HOST, user=MYSQL_USER, passwd=MYSQL_PASSWD, db=MYSQL_DATABASE)
                    cursor = db.cursor()
                    cursor.execute(self)
                    results = cursor.fetchall()
                    week_number = [i[0] for i in cursor.description]
                except MySQLdb.Error, e:
                    try:
                        print "%s \n MySQL Error [%d]: %s" % (error_report, e.args[0], e.args[1])
                    except IndexError:
                        print "%s \n MySQL Error: %s " % (error_report, str(e))
    
                #finally:
                #    cursor.close()
                #    db.close()
                print(results, week_number) #For debuging only
            return (results, week_number)
    

Here my testscript.py

    
    
    from main import WeekQuery
    
    def sample():
        q = "select domain_name from domains_domain limit 10"
        x = WeekQuery(q)
        for y in x.query():
            print(y)
    


Answer: You need tom import host and error_report too from main. Is that your problem
?

