Python Forum
Claims not declared, but is... why?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Claims not declared, but is... why?
#1
Hi

My class which I've imported in the app.py is complaining that the con variable doesn`t exist.

Ok. I get that it thinks the variable doesn`t exist, but it does. before the route is called, it is set up.

When you import, does it evaluate the class at that time (if so then that is why.. the variable is only created after the import)
from flask import Flask, render_template, flash, redirect, url_for, session, request
from flask import send_from_directory, logging

import os
import pymysql
import random

from setup import setupADB

app = Flask(__name__)
app.debug = True
app.config.from_object(__name__)
app.config['SECRET_KEY'] = 'development key'

con = pymysql.connect(
    host="localhost",
    user="root",
    password="thepwd",
    db="pyadventures",
    charset="utf8mb4",
    cursorclass=pymysql.cursors.DictCursor
    )


#the routes
@app.route('/favicon.ico')
def rFavicon():
    return redirect(url_for('static', filename='favicon.ico'), code=302)

@app.route('/')
def rIndex():
    return render_template("home.html")

@app.route('/setup1time')
def rSetupOneTime():
    r = []
    d = setupADB()
    d.createdb()
    r = d.dbtables()
    return 'l'
    #return render_template('setup.html',r=r)

if __name__ == '__main__':
	app.run()
and the class
class setupADB:
#    def __init__(self):
        #meh

    def createdb(self):
        '''
        on the command line...
        mysql -u root -p
        grant all priveledges on *.* to 'thtename'@'localhost' identifiedby 'pwd';
        \q
        mysql -u username -p
        create database nameofdatabase
        use nameofdatabase
        (or use the mysql manager, create a new schema (database) )
        '''

    def dbtables(self):
        r = []
        sql = ''
#complains on the following line - con should be global from the app.py???
        with con.cursor() as cr:
            try:
                sql = """CREATE TABLE ... sql
                """
                cr.execute(sql)
            except Exception as e:
                r.append("_su -> "+str(e))
            try:
                sql = """CREATE TABLE ... sql
                """
                cr.execute(sql)
            except Exception as e:
                r.append("stories -> "+str(e))
        return r
Reply
#2
Please show the actual error, complete and unaltered.
There is so much information packed in there, and we need it all.
Reply
#3
Error:
builtins.NameError NameError: name 'con' is not defined Traceback (most recent call last) File "c:\python\lib\site-packages\flask\app.py", line 2309, in __call__ return self.wsgi_app(environ, start_response) File "c:\python\lib\site-packages\flask\app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "c:\python\lib\site-packages\flask\app.py", line 1741, in handle_exception reraise(exc_type, exc_value, tb) File "c:\python\lib\site-packages\flask\_compat.py", line 35, in reraise raise value File "c:\python\lib\site-packages\flask\app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "c:\python\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "c:\python\lib\site-packages\flask\app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "c:\python\lib\site-packages\flask\_compat.py", line 35, in reraise raise value File "c:\python\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "c:\python\lib\site-packages\flask\app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "D:\Dev\python\py3\webAdventureDB\app.py", line 39, in rSetupOneTime r = d.dbtables() File "D:\Dev\python\py3\webAdventureDB\setup.py", line 20, in dbtables with con.cursor() as cr: NameError: name 'con' is not defined
Reply
#4
in second module:
class setupADB:
    def __init__(self, con):
        self.con = con
then refer to con in rest of class as self.con

also, line 37 of first script
    d = setupADB(con)
Reply
#5
Ah thank you... Thought it would be easy.
Can I use the global in the def or would that be bad practice?
Reply
#6
should never use global unless there is no other way.
I haven't used a global as far back as I can remember.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020