Nick White
Nick White

Reputation: 11

How to access an object from main within a class

I need to use the Flask app instantiated from the main function within the InterestGroupsForm class so I can access a db.

InterestGroupForm class:

class InterestGroupForm(FlaskForm, app):
    c = app.db.cursor()
    c.execute('SELECT TAG_TITLE FROM TAGS;')
    primary_tags_list = c.fetchall()
    print(new_list, file=sys.stderr)
    primary_tags = []
    .....

In the main function:

app = Flask(__name__)
app.db = None
app.config['SECRET_KEY'] = 'a hard to guess string'
bootstrap = Bootstrap(app)
moment = Moment(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
user_db = {}

I should be able able to access the database normally (I've used the same code elsewhere for queries) but I keep getting an error

Traceback (most recent call last): 
File "/home/proj/main.py", line 53, in <module> class InterestGroupForm(FlaskForm, app): 
NameError: name 'app' is not defined 

Upvotes: 0

Views: 112

Answers (1)

Loocid
Loocid

Reputation: 6451

I think you misunderstand the syntax of python classes. The brackets after your class name are for inheritance, you seem to be using as a constructor.

The syntax for python classes is:

class ClassName(BaseClass):
    def __init__(self, args): # this is the constructor

app isn't a class. I suspect you want something like this:

class InterestGroupForm(FlaskForm):
    def __init__(self, app):
        c = app.db.cursor()
        c.execute('SELECT TAG_TITLE FROM TAGS;')
        primary_tags_list = c.fetchall()
        print(new_list, file=sys.stderr)
        primary_tags = []
        .....

However it's hard to say because I don't know where new_list is defined etc.

Upvotes: 1

Related Questions