I'm making a form which allows me to add questions to a database. I've written code but when I try it I get this error ('AttributeError: 'module' object has no attribute 'GetTable')
The error lies with this part of my code 't = self.dbu.GetTable()'
#QtCore.pyqtSignature("on_add_btn_clicked()")
def Add_btn(self):
Question = self.Question_lineEdit.text()#Grabs the text from all line edit fields
Answer = self.Answer_lineEdit.text()
IsmultiChoice = self.IsMultiChoice_lineEdit.text()
if not Question:
QtGui.QMessageBox.warning(self, 'Warning', 'Username Missing')
else:
t = self.dbu.GetTable()
print (t)
for col in t:
if Question == col[1]:
QtGui.QMessageBox.warning(self, 'Warning', 'Question Taken. :(')#Checks the database and warns if the database does exist
else:
self.dbu.AddEntryToTable (Question, Answer, isMultiChoice)
QtGui.QMessageBox.information(self, 'Success', 'User Added Successfully!')#If everythings is okay it adds the user
self.close()
Here is my database code:
import mysql.connector
from mysql.connector import errorcode
from datetime import datetime
class DatabaseUtility:
def __init__(self, database, Tablename,):
self.db = database
self.Tablename = Tablename
self.cnx = mysql.connector.connect(user = 'root',
password = '',
host = 'localhost')
self.cursor = self.cnx.cursor()
def ConnectToDatabase(self):
try:
self.cnx.database = self.db
except mysql.connector.Error as err:
if err.errno == errorcode.ER_BAD_DB_ERROR:
self.CreateDatabase()
self.cnx.database = self.db
else:
print(err.msg)
def CreateDatabase(self):
try:
self.RunCommand("CREATE DATABASE %s DEFAULT CHARACTER SET 'utf8';" %self.db)
except mysql.connector.Error as err:
print("Failed creating database: {}".format(err))
def GetTable(self):
self.Tablename()
return self.RunCommand("SELECT * FROM %s;" % self.Tablename)
def GetColumns(self):
return self.RunCommand("SHOW COLUMNS FROM %s;" % self.Tablename)
def RunCommand(self, cmd):
print ("RUNNING COMMAND: " + cmd)
try:
self.cursor.execute(cmd)
except mysql.connector.Error as err:
print ('ERROR MESSAGE: ' + str(err.msg))
print ('WITH ' + cmd)
try:
msg = self.cursor.fetchall()
except:
msg = self.cursor.fetchone()
return msg
def AddEntryToTable(self, Question, Answer,IsMultiChoice):
cmd = " INSERT INTO " + self.Tablename + " (Question, Answer, IsMultiChoice)"
cmd += " VALUES ('%s', '%s', '%s');" % (Question, Answer, IsMultiChoice)
self.RunCommand(cmd)
def __del__(self):#Deconstructer class
self.cnx.commit()
self.cursor.close()
self.cnx.close()
if __name__ == '__main__':
db = 'UsernamePassword_DB'
Tablename = 'questiontable'
dbu = DatabaseUtility(db, Tablename)
What am I doing wrong and how can I correct it?
I'd need to see some additional code to be sure (see my comment). But for now my guess is it has to do with how you first instantiate or reference the dbu variable/attribute. If all you did is import it from another file, because dbu is created in that file's main() (in the snippet you provided), that might be the issue. For example, this is incorrect:
from whatever import dbu # wrong
from whatever.main import dbu # Also wrong. In fact I don't think this would even work
Instead, import DatabaseUtility directly into the script, then instantiate dbu like :
from whatever import Database Utility
class SomeClass(object):
...
def startDB(self, db, Tablename):
self.dbu = DatabaseUtility(db, Tablename)
The reason I guess this is because the error message says module has no attribute, instead of mentioning the actual class. Here's an example of the error I would expect to see:
In [31]: class MyClass(object):
one = 1
....:
In [32]: myc = MyClass()
In [33]: myc.one
Out[33]: 1
In [34]: myc.two
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-34-4bae87671838> in <module>()
----> 1 myc.two
AttributeError: 'MyClass' object has no attribute 'two'
Notice how it says MyClass is the problem, not "module".
Potentially unrelated, you might want to remove self.Tablename() from DatabaseUtility.GetTable(). The way you have your class defined, Table is an attribute to the DatabaseUtility class, but by including the parentheses you're trying to call it as if it were a method (like GetTable is).
Related
I have no idea to implement to handle the class variable exception. I am trying to create python module which has dependency with mongodb.
class HrmLookUps(DBMixin):
db_handle = DBMixin.get_db_handle(DBMixin, MONGO_STORE_DICT.get("DB_NAME"),
MONGO_STORE_DICT.get("DB_HOST"),
MONGO_STORE_DICT.get("DB_PORT"),
MONGO_STORE_DICT.get("USERNAME"),
MONGO_STORE_DICT.get("PASSWORD"))
#classmethod
def get_gender(cls):
collection_name = COLLECTION_NAME_DICT.get("COLLECTION_GENDER")
# collection_name = "departments"
gender_record = cls.get_from_db(cls, cls.db_handle, collection_name)
if gender_record[collection_name]:
return gender_record
else:
raise KeyError("Collection Name Invalid!")
I have multiple get method like above get_gender(). I am handling each method raised Keyerror if its data empty.
My question is,
Is this proper way to handle exception of methods?
If my class variable has some issues ex.database credential wrong how can I handle that?
Currently your else clause isn't really doing anything. Your if statement would already throw an error if collection_name wasn't a key in gender_record. So unless you want to raise KeyError in the else clause when collection_name is in gender_record but its value happens to be 0 or False or None.
I think what you are trying to do is something closer to these examples:
#classmethod
def get_gender(cls):
collection_name = COLLECTION_NAME_DICT.get("COLLECTION_GENDER")
# collection_name = "departments"
gender_record = cls.get_from_db(cls, cls.db_handle, collection_name)
if collection_name in gender_record:
return gender_record
else:
raise KeyError("Collection Name Invalid!")
or this maybe
#classmethod
def get_gender(cls):
collection_name = COLLECTION_NAME_DICT.get("COLLECTION_GENDER")
# collection_name = "departments"
gender_record = cls.get_from_db(cls, cls.db_handle, collection_name)
try:
gender_record[collection_name]
return gender_record
else KeyError as err:
raise KeyError("Collection Name Invalid!") from err
Handling exceptions is pretty much the same in any situation. so for the credentials it would be something like this:
try:
db_handle = DBMixin.get_db_handle(DBMixin, MONGO_STORE_DICT.get("DB_NAME"),
MONGO_STORE_DICT.get("DB_HOST"),
MONGO_STORE_DICT.get("DB_PORT"),
MONGO_STORE_DICT.get("USERNAME"),
MONGO_STORE_DICT.get("PASSWORD"))
except <SomeCredentialErrorHere>:
# whatever you put here is what gets executed if the error is raised.
Is there a more optimal way I can check to see if multiple ENV variables exist with customized exceptions? Perhaps a way to match a group of EVN variables, and then have the exception self-reference the variable name in its output?
if os.environ.get('USERNAME') is not None:
self.username = os.environ.get('USERNAME')
else:
raise CustomException('Environment variable USERNAME not set')
if os.environ.get('PASSWORD') is not None:
self.password = os.environ.get('PASSWORD')
else:
raise CustomException('Environment variable PASSWORD not set')
I am using Python 2.7. Thanks!
You can do something like this:
#
# ENV vars you want to go over
#
env_vars = 'HOME,PATH,NONEXISTS'.split(',')
for evar in env_vars:
# Loop will create it as: self.$evar = os.environ.get(evar)
if evar not in os.environ:
# Will skip: NONEXISTS
continue
# or if you want to raise exception
raise ValueError('Environment variable "%s" was not set' % evar)
# setattr: will create a dynamic attribute for "self"
# self.home = ...
# self.path = ...
# evar.lower() => so we'll have self.home vs self.HOME
setattr(self, evar.lower(), os.environ.get(evar))
In general, just note that you don't need to verify if it's "None" in Python, so
# Replace this
if os.environ.get('USERNAME') is not None:
# With this, the default of get => is None, and None won't pass "if"
if os.environ.get('USERNAME'):
# Will create an exception if USERNAME doesn't exists
if os.environ['USERNAME']
Hope it helps ...
You could always use a loop with a three items list:
for data in [
["USERNAME", "username", CustomException],
["PASSWORD", "password", CustomException]
]:
env_var = os.environ.get(data[0])
if env_var:
setattr(self, data[1], env_var)
else:
# Should work, cannot check due to not having actually Python installed.
raise data[2]("Environment variable %s not set" % data[0])
If you don't like using indexes, you could replace the items by dicts like this to have a more consistent access if you change order:
{"env_var_name": "USERNAME", "attr": "username", "exception_cls": CustomException}
Just put all the environment lookups in a try: block:
try:
self.username= os.environ['USERNAME']
self.password= os.environ['PASSWORD']
except KeyError as e:
raise CustomException('Environment variable {} not set'.format(e.args[0]))
I'm using python 3.5.2 for my project. I installed MySQLdb via pip for Mysql connection.
Code:
import MySQLdb
class DB:
def __init__(self):
self.con = MySQLdb.connect(host="127.0.0.1", user="*", passwd="*", db="*")
self.cur = self.con.cursor()
def query(self, q):
r = self.cur.execute(q)
return r
def test():
db = DB()
result = db.query('SELECT id, name FROM test')
return print(result)
def test1():
db = DB()
result = db.query('SELECT id, name FROM test').fetchall()
for res in result:
id, name = res
print(id, name)
test()
test1()
#test output >>> '3'
#test1 output >>> AttributeError: 'int' object has no attribute 'fetchall'
Test table:
id | name
1 | 'test'
2 | 'test2'
3 | 'test3'
Please read this link:http://mysql-python.sourceforge.net/MySQLdb.html
At this point your query has been executed and you need to get the
results. You have two options:
r=db.store_result()
...or... r=db.use_result() Both methods return a result object. What's the difference? store_result() returns the entire result set to
the client immediately. If your result set is really large, this could
be a problem. One way around this is to add a LIMIT clause to your
query, to limit the number of rows returned. The other is to use
use_result(), which keeps the result set in the server and sends it
row-by-row when you fetch. This does, however, tie up server
resources, and it ties up the connection: You cannot do any more
queries until you have fetched all the rows. Generally I recommend
using store_result() unless your result set is really huge and you
can't use LIMIT for some reason.
def test1():
db = DB()
db.query('SELECT id, name FROM test')
result = db.cur.fetchall()
for res in result:
id, name = res
print(id, name)
cursor.execute() will return the number of rows modified or retrieved, just like in PHP. Have you tried to return the fetchall() like so?
def query(self, q):
r = self.cur.execute(q).fetchall()
return r
See here for more documentation: https://ianhowson.com/blog/a-quick-guide-to-using-mysql-in-python/
when I try to call the changeProfile function, I keep getting the error "getAuthCode is not defined" even though it is clearly defined. Why do I keep getting this error? What am I doing wrong? It used to work from what I remember, but now all of a sudden it doesn't. Any help would be appreciated :)
import os,re,json,socket,random,select,threading,time,sys
import urllib.request as urlreq
from urllib.request import quote,unquote
import urllib.parse
class miscellanous:
"""Main class."""
def __init__():
"""What to do on initalizing."""
pass
def getAuthCode(u, p):
"""Get authentification code from username and password specified."""
try:
data=urllib.request.urlopen('http://chatango.com/login',urllib.parse.urlencode({'user_id': u, 'password': p, 'storecookie': 'on', 'checkerrors': 'yes'}).encode()).headers
except Exception as e: print("Error: Auth request: %s" % e)
for x, y in data.items():
if x.lower() == 'set-cookie':
returned = re.compile(r"auth\.chatango\.com ?= ?([^;]*)", re.IGNORECASE).search(y)
if returned:
ret = returned.group(1)
if ret == "": raise ValueError("Error: Unable to get auth: Error in username/password.")
return ret
def createAccount(u, p):
"""Create an account with the username and password specified."""
try:
resp=urllib.request.urlopen("http://chatango.com/signupdir", urllib.parse.urlencode({"email": "accmaker"+str(random.randrange(1,1000000000000))+"#hotmail.com", "login": u, "password": p, "password_confirm": p, "storecookie": "on", "checkerrors": "yes"}).encode())
fu=str(resp.read())
resp.close()
if "screen name has been" in fu: r = "Error: User could not be created: Already exists."
else: r = "The user was created. If it didn't work, try another username."
return r
except: return "Error: Invalid or missing arguments."
def createGroup(u, p, g, d="Description.", m="Owner message."):
"""Creates a group with the username, password, group name, description and owner message specified."""
try:
g=g.replace(" ","-")
resp=urllib.request.urlopen("http://chatango.com/creategrouplogin",urllib.parse.urlencode({"User-Agent": "Mozilla/5.0", "uns": "0", "p": p, "lo": u, "d": d, "u": g, "n": m}).encode())
fu=str(resp.read())
resp.close()
if "groupexists" in fu: r = "Error: Group could not be created: Already exists."
else: r = "The group was created. If it didn't work, try another group name. Click <a href='http://%s.chatango.com/' target='_blank'>[[here]]<a> to get to the new group."
return r
except: return "Error: Invalid or missing arguments."
def changeProfile(u, p, m="Default", e="accmaker"+str(random.randrange(1,1000000000000))+"#hotmail.com", l="Norway", g="M", a="18"):
try:
resp = urlreq.urlopen('http://'+u.lower()+'.chatango.com/updateprofile?&d&pic&s='+getAuthCode(u, p), urllib.parse.urlencode({"show_friends": "checked", "dir": "checked", "checkerrors": "yes", "uns": "1", "line": m, "email": e, "location": l, "gender": g, "age": a}).encode())
return "The profile change was successful."
except Exception as e:
return "%s" % e
def checkOnlineStatus(u):
"""Check if the predefined username is online or offline."""
if "Chat with" in urlreq.urlopen("http://"+u.lower()+".chatango.com").read().decode(): return '<b><font color="#00ff00">Online</font></b>'
else: return "<b><font color='#ff0000'>Offline</font></b>"
resp.close()
def checkUserGender(u):
"""Get the gender for the predefined username."""
resp=urlreq.urlopen("http://st.chatango.com/profileimg/%s/%s/%s/mod1.xml" % (u.lower()[0], u.lower()[1], u.lower()))
try: ru=re.compile(r'<s>(.*?)</s>', re.IGNORECASE).search(resp.read().decode()).group(1)
except: ru="?"
ret=unquote(ru)
resp.close()
if ret=="M": r="Male"
elif ret=="F": r="Female"
elif ret=="?": r="Not specified"
return r
def changeBackGround(u, p, x, transparency=None):
"""Update the user's bg using the predefined username, password and bg color."""
color=quote(x.split()[0])
try: image=x.split()[1]
except: image=None
if color and len(color)==1:
color=color*6
if color and len(color)==3:
color+=color
elif color and len(color)!=6:
return False
if transparency!=None and abs(transparency)>1:
transparency = abs(transparency) / 100
data=urllib.request.urlopen("http://fp.chatango.com/profileimg/%s/%s/%s/msgbg.xml" % (u[0], u[1], u.lower())).read().decode()
data=dict([x.replace('"', '').split("=") for x in re.findall('(\w+=".*?")', data)[1:]])
data["p"]=p
data["lo"]=u
if color: data["bgc"] = color
if transparency!=None: data["bgalp"]=abs(transparency) * 100
if image!=None: data["useimg"]=1 if bool(image) else 0
data12=urllib.parse.urlencode(data)
data13=data12.encode()
der=urllib.request.urlopen("http://chatango.com/updatemsgbg", data13).read()
def checkIfGroupExists(g):
"""Check if the predefined group exists."""
i = urlreq.urlopen('http://'+g+'.chatango.com').read().decode()
if '<table id="group_table"' in i: return True#"This chat does exist!"
else: return False#"This chat doesn't exist."
i.close()
All of the functions you've shown are part of the miscellaneous class, so to access them, you need to prefix them with the class name. To refer to the getAuthCode function, you'd use miscellaneous.getAuthCode.
But, it doesn't seem like you should really be using a class here. You never create instances of miscellaneous, nor are the functions set up to be run as methods. So, probably the right answer is to get rid of the class miscellaneous: declaration at the top of the file, and then to unindent all the functions one level.
(Note, in Python 2 you'd have an additional issue if you kept the class: Unbound methods required that their first argument be an instance of their class (or a subclass). In that situation, you'd need to use the staticmethod decorator on any functions that did not expect to get an instance at all.)
Functions within a Python class are called methods. They normally take a self parameter before their other parameters. Furthermore, methods cannot "see" each other directly; you need to call them as self.method(args) instead of just method(args).
I have a program that is aiming to take inputs from sensors and then act upon inputs from these sensors from some pre-defined rules that are stored and called within a class. I am having problems passing the variables that the sensors are defined as into the rules class. Where I get errors of 'Rules object has not attribute .rules_temperature. My code is below:
class myInterfaceKit():
__interfaceKit = None
def __init__(self ):
try:
self.__interfaceKit = InterfaceKit()
except RuntimeError as e:
print("Runtime Exception: %s" % e.details)
print("Exiting....")
exit(1)
def open(self):
try:
self.__interfaceKit.openPhidget()
except PhidgetException as e:
print("Phidget Exception %i: %s" % (e.code, e.details))
def getInterfaceKit(self):
return self.__interfaceKit
def getSensor(self, sensor):
return self.__interfaceKit.getSensorValue(sensor)
class sensors():
__sound = 0
__temperature = 0
__light = 0
__motion = 0
__dbName = ""
__interfaceKit = None
__connection = None
__rules = None
def __init__(self, theInterfaceKit, dbName):
self.__sound = 0
self.__temperature=0
self.__light=0
self.__motion=0
self.__timeStamp=time.time()
self.__strTimeStamp=datetime.datetime.fromtimestamp(self.__timeStamp).strftime('%Y-%m-%d %H:%M:%S')
self.__dbName = dbName
self.__interfaceKit = theInterfaceKit
self.__connection = sqlite3.connect('testing1.db', check_same_thread=False) ######
def interfaceKitAttached(self, e):
attached = e.device
print("InterfaceKit %i Attached!" % (attached.getSerialNum()))
self.__interfaceKit.getInterfaceKit().setSensorChangeTrigger(0, 5)
self.__interfaceKit.getInterfaceKit().setSensorChangeTrigger(1, 35)
self.__interfaceKit.getInterfaceKit().setSensorChangeTrigger(2, 60)
self.__interfaceKit.getInterfaceKit().setSensorChangeTrigger(3, 200)
def sensorInputs(self, e):
temperature = (self.__interfaceKit.getSensor(0)*0.2222 - 61.111)
sound = (16.801 * math.log((self.__interfaceKit.getSensor(1))+ 9.872))
light = (self.__interfaceKit.getSensor(2))
motion = (self.__interfaceKit.getSensor(3))
# check temperature has changed - if yes, save and update
if temperature != self.__temperature:
self.__timeStamp=time.time()
self.__strTimeStamp=datetime.datetime.fromtimestamp(self.__timeStamp).strftime('%Y-%m-%d %H:%M:%S')
self.__temperature = temperature
print("Temperature is: %i:" % self.__temperature)
self.writeToDatabase( 'temperature', self.__temperature, self.__strTimeStamp)
#check sound has changed - if yes, save and update
if sound != self.__sound:
self.__timeStamp=time.time()
self.__strTimeStamp=datetime.datetime.fromtimestamp(self.__timeStamp).strftime('%Y-%m-%d %H:%M:%S')
self.__sound = sound
print("Sound is: %i " % self.__sound)
self.writeToDatabase( 'sound', self.__sound, self.__strTimeStamp )
#check light has changed - if yes, save and update
if light != self.__light:
self.__timeStamp=time.time()
self.__strTimeStamp=datetime.datetime.fromtimestamp(self.__timeStamp).strftime('%Y-%m-%d %H:%M:%S')
self.__light = light
print("Light is: %i " % self.__light)
self.writeToDatabase( 'light', self.__light, self.__strTimeStamp )
if motion != self.__motion:
self.__motion = motion
print ("motion is %i" % self.__motion)
def openDatabase(self):
cursor = self.__connection.cursor()
cursor.execute("CREATE TABLE " + self.__dbName + " (sensor text, value text, time_stamp text)")
def writeToDatabase(self, sensorType, data, time):
cursor = self.__connection.cursor()
cursor.execute("INSERT INTO " + self.__dbName + " VALUES (?, ?, ?)", (sensorType, data, time))
self.__connection.commit()
def closeDatabase():
self.__connection.close()
def start(self):
try:
self.__interfaceKit.getInterfaceKit().setOnAttachHandler(self.interfaceKitAttached)
self.__interfaceKit.getInterfaceKit().setOnSensorChangeHandler(self.sensorInputs)
self.openDatabase()
except PhidgetException as e:
print("Phidget Exception %i: %s" % (e.code, e.details))
print("Exiting....")
exit(1)
This is where the problem lies:::
class Rules(sensors):
__tempLower=0
__tempUpper=0
def __init__(self):
self.__tempLower=28
self.__tempUpper=30
self.__temperature
def tempRule(self, sensors): ##Temperature rule
if self.__temperature == self.__tempLower:
print("testing")
phidgetInterface = myInterfaceKit()
phidgetInterface.open()
theSensors = sensors(phidgetInterface, "event156")
theSensors.start()
theRule = Rules()
theRule.tempRule()
chr = sys.stdin.read(1)
edit, error message:
Traceback (most recent call last):
File "H:\Project\Student\Prototype 1\eventProto.py", line 159, in
theRule = Rules()
File "H:\Project\Student\Prototype 1\eventProto.py", line 146, in init
self.__temperature
AttributeError: 'Rules' object has no attribute 'Rules_temperature'
Private members (starting with __) cannot be accessed by subclasses. (Well, they can be accessed using some hackery, but should not).
(see here)
In your case, __temperature is a private member of the base class sensors, but you're accessing it from the subclass Rules.
Replace the double underscore prefix with a single underscore (__temperature -> _temperature), and you're good to go.
Double underscore members are considered private, you have to prepend those with class name that defined said member.
Use these magic private members like this:
class sensors:
__temp = 42
assert sensors()._sensors__temp == 42
class Rules(sensors):
def test(self):
assert self._sensors__temp == 42
Rules().test()