nlr25
nlr25

Reputation: 1635

Importing variables from other py files

I have a .py file that contains database settings (call it connection.py). I am trying to import the variables contained in my connection.py into my views.py. However, the variables are not being imported.

In my views.py I have:

from connection import *

def location_where_connection_variables_needed(request, some_id):

 conn = psycopg2.connect(conn_string)
 cursor = conn.cursor()

I then use the variables in connection.py in my views.py script. But the variables are not being imported into my views.py. I placed connection.py in the main folder (ie, connection.py is in the same folder as my app's folder). Is this the correct place to put this? Or am I doing something else fundamentally wrong?

Edit: What I mean by not being imported: I am not getting any error at all but the variables are not being imported because the code in views.py is not executing. If I add the connection variable manually in my views.py, everything works fine.

Connection.py

conn_string = "host='localhost' dbname='test' user='postgres' password='pwd'"

Upvotes: 0

Views: 686

Answers (2)

Brandon Taylor
Brandon Taylor

Reputation: 34553

With constant values, I typically put those into a file called constants.py and specify those values in all caps, which is a Python convention. So, I would replace "connection.py" with "constants.py" as such:

# constants.py
CONN_STRING = "host='localhost' dbname='test' user='postgres' password='pwd'"


# views.py
from constants import CONN_STRING

def location_where_connection_variables_needed(request, some_id):
    conn = psycopg2.connect(CONN_STRING)
    cursor = conn.cursor()

Also, make sure to clear out any .pyc files that might not be getting cleared out by manage.py. That can sometimes cause things not to work as expected. You might also stay away from import * since it's not as implicit (you can't see what you're importing) and it's easy to run into naming collisions.

Upvotes: 2

Subhasis Das
Subhasis Das

Reputation: 1677

You can try a global variable instead of a local one. Use it as

global conn_string = "host='localhost' dbname='test' user='postgres' password='pwd'"

Upvotes: 0

Related Questions