Skip to content
Advertisement

How to call a function in a different module in Python and not repeating the function

I have defined a function in a different page in Python like so:

def getData():
    user=input('Enter Name')
    if user=='Irfan':
        mydb = mysql.connector.connect(host='localhost', user='root', passwd='', database='sample_data')
        df = pd.read_sql_query('select * from sample_data.sample_data3', mydb)
    else:
        if user=='Usman':
            mydb = mysql.connector.connect(host='localhost', user='root', passwd='', database='')
            df = pd.read_sql_query('select * from sample_data.sample_data1', mydb)

    return df

However, because that function is called in many other files in the project, it is asking me over and over again at runtime to enter the user name.

How can I input the user name once and then use that cached value to get the required database without having to enter the user name multiple times?

(Sorry for asking in layman’s terms; I am a beginner.)

Advertisement

Answer

Make the credentials global..

user=input('Enter Name')

def getData():
global user
if user=='Irfan':
    mydb = mysql.connector.connect(host='localhost', user='root', passwd='', database='sample_data')
    df = pd.read_sql_query('select * from sample_data.sample_data3', mydb)
else:
    if user=='Usman':
        mydb = mysql.connector.connect(host='localhost', user='root', passwd='', database='')
        df = pd.read_sql_query('select * from sample_data.sample_data1', mydb)

return df
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement