Python class database constructor - python

I am trying to convert my script into a class, Since I will be using the connect method everytime,
I want to place it in the constructor, and then call it in the other functions.
I am new classes in Python, This is a
from datetime import date
import pymssql
import sys
class PHQuery:
def __init__(self):
self.conn = self.conn()
def get_stock_by_sku(self, sku):
if self.conn["code"] < 0:
return {"code":-1,"error":conn["error"]}
cursor = self.conn.cursor(as_dict=True)
try:
cursor.execute('''
SELECT NUMBER, UNITS, LOW, UNCOST, PRICE1, ONORDER
FROM STOCK
WHERE NUMBER=%s''', sku)
return {"code":1,"data":cursor.fetchone()}
except Exception as e:
return {"code":-2,"error":e}
def conn(self):
try:
conn = pymssql.connect(server='server', user='user', password='pwd', database='db', timeout=0, login_timeout=60, charset='UTF-8', as_dict=False, port='1433')
return {"code":1,"data":conn}
except Exception as e:
return {"code":-1,"error":e}
OUTPUT ERRORS:
File "test.py", line 3, in
print testObject.get_stock_by_sku('BK31')
TypeError: unbound method get_stock_by_sku() must be called with PHQuery instance as first argument (got str instance instead)
THIS IS THE CALL TO THE METHOD
from query import PHQuery
testObject = PHQuery
print testObject.get_stock_by_sku('BK31')
Here is my goal
data = {"stock_id" : "12345"}
qobject = PHQuery()
qobject.get_stock_by_sku(data["stock_id"])
and return the same data my script returns:
The script below is working perfectly fine, I just need to make it a class.
THANK YOU IN ADVANCE.
WORKING CODE:
import time
from datetime import date
import pymssql
import sys
def conn():
try:
conn = pymssql.connect(server='', user='', password='', database='', timeout=0, login_timeout=60, charset='UTF-8', as_dict=False, port='1433')
return {"code":1,"data":conn}
except Exception as e:
return {"code":-1,"error":e}
conn = conn()
def get_stock_by_sku(conn,sku):
""" Returns stock information when passing a sku"""
if conn["code"] < 0:
return {"code":-1,"error":conn["error"]}
cursor = conn["data"].cursor(as_dict=True)
try:
cursor.execute('''
SELECT NUMBER, UNITS, LOW, UNCOST, PRICE1, ONORDER
FROM STOCK
WHERE NUMBER=%s''', sku)
return {"code":1,"data":cursor.fetchone()}
except Exception as e:
return {"code":-2,"error":e}

Related

sqlite3.OperationalError: no such table: departments

this error comes suddenly , i am sure the tables exists in database cause it was works nicely after that i dont know wht happnd the window couldn't shown up to me :
Traceback (most recent call last):
File "c:\Users\LENOVO\Desktop\HR_project\HR_System\controler\app\app.py", line 71, in <module>
window=MainWindow()
File "c:\Users\LENOVO\Desktop\HR_project\HR_System\controler\app\app.py", line 12, in __init__
self.depts=Departments.get_all_depts()
File "c:\Users\LENOVO\Desktop\HR_project\HR_System\controler\app\departments.py", line 18, in get_all_depts
result= cur.execute(sql).fetchall()
sqlite3.OperationalError: no such table: departments
this is departments.py :
from sqlite3 import connect
class Departments:
def __init__(self,dept_id,dept_name,location_id):
self.dept_id=dept_id
self.dept_name=dept_name
self.location_id=location_id
def __repr__(self):
return self.dept_name
#staticmethod
def get_all_depts():
path="C:\\Users\\LENOVO\\Desktop\\HR_project\\HR_System\\controler\\app\\hr.db"
with connect(path)as conn:
cur=conn.cursor()
sql= 'SELECT * FROM departments'
result= cur.execute(sql).fetchall()
result=[Departments(*row)for row in result]
return result
def saveToDb(self):
path="C:\\Users\\LENOVO\\Desktop\\HR_project\\HR_System\\controler\\app\\hr.db"
with connect(path)as conn:
cur=conn.cursor()
sql='INSERT INTO departments VALUES (:dept_id , :dept_name , :location_id)'
cur.execute(sql,self.__dict__)
conn.commit()
def deleteFromDb(self):
path="C:\\Users\\LENOVO\\Desktop\\HR_project\\HR_System\\controler\\app\\hr.db"
with connect(path)as conn:
cur=conn.cursor()
sql='DELETE FROM departments WHERE department_id = :dept_id'
cur.execute(sql,self.__dict__)
conn.commit()
and here app.py when i run it the error above shown up:
from PyQt5.uic import loadUi
from PyQt5.QtWidgets import *
from main_window import Ui_Form
from departments import Departments
from locats import locates
from emloyee import Employee
class MainWindow(QWidget,Ui_Form):
def __init__(self):
QWidget.__init__(self)
self.setupUi(self)
self.depts=Departments.get_all_depts()
self.load_depts()
self.emps= Employee.get_all_emps()
self.load_emps()
self.cb_depts.currentIndexChanged.connect(self.select_depts)
self.le_search.textChanged.connect(self.search)
self.bt_add_dept.clicked.connect(self.show_add_depts_dialog)
self.bt_del_dept.clicked.connect(self.delet_dept)
def load_depts(self):
dept_names= [d.dept_name for d in self.depts]
self.cb_depts.addItems(dept_names)
def load_emps(self):
self.tb_emps.setRowCount(0)
for i,e in enumerate(self.emps):
self.tb_emps.insertRow(i)
for n,v in enumerate(e.__dict__.values()):
self.tb_emps.setItem(i,n,QTableWidgetItem(str(v)))
def select_depts(self,idx):
self.load_emps()
if idx !=0:
dept_i=self.depts[idx-1]
for i,e in enumerate(self.emps):
if e.dept_id != dept_i.dept_id:
self.tb_emps.hideRow(i)
def search(self):
self.load_emps()
text=self.le_search.text()
if text != "":
for i,e in enumerate (self.emps):
if not e.emp_name.startswith(text):
self.tb_emps.hideRow(i)
def show_add_depts_dialog(self):
dialog = loadUi("C:\\Users\\LENOVO\\Desktop\\HR_project\\HR_System\\controler\\app\\add_depts.ui")
locs={str(l.location_id) for l in self.depts}
dialog.cb_locats.addItems(locs)
choice =dialog.exec()
if choice ==1:
dept = Departments(dialog.le_deps_id.text(),
dialog.le_deps_name.text(),
dialog.cb_locats.currentText())
self.depts.append(dept)
self.cb_depts.addItem(dept.dept_name)
dept.saveToDb()
def delet_dept(self):
idx=self.cb_depts.currentIndex()
if idx != 0:
self.cb_depts.removeItem(idx)
dept = self.depts.pop(idx-1)
dept.deleteFromDb()
app = QApplication([])
window=MainWindow()
window.show()
app.exec()
employee.py:
from sqlite3 import connect
class Employee:
def __init__(self,emp_id,emp_name,email,hire_date,job_id,salary,dept_id):
self.emp_id=emp_id
self.emp_name=emp_name
self.email=email
self.hire_date=hire_date
self.job_id=job_id
self.salary=salary
self.dept_id=dept_id
def __repr__(self):
return self.emp_name
#staticmethod
def get_all_emps():
path="C:\\Users\\LENOVO\\Desktop\\HR_project\\HR_System\\controler\\app\\hr.db"
with connect(path)as conn:
cur=conn.cursor()
sql= 'SELECT employee_id,last_name,email,hire_date,job_id,salary,department_id FROM employees'
result= cur.execute(sql).fetchall()
result=[Employee(*row)for row in result]
return result
tables are already existed i take screen shoot:
enter image description here
any help pls????????????????????????????????????????????????????

Mocking a module selectively in Python 3.7

I am trying to write unit test for one of my module using pymysql as follows:
def execute(self, query):
try:
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='',
db='mysql')
cur = conn.cursor()
cur.execute(query)
except pymysql.Error as e:
raise
except Exception as e:
raise
While writing unit test for the above function, I am mocking pysql as follows #patch(my_package.my_module.pymysql). As a result pymysql.erroris also becoming mocked. So while testing the failure scenario as follows:
#patch('my_package.my_module.pymysql')
def test_execute_with_failure(self, mock_pymysql):
...
self.my_obj.cur.execute.side_effect = pymysql.Error
with self.assertRaises(pymysql.Error) as context:
_ = self.my_obj.execute(query="SELECT FOO FROM BAR")
I am getting the below error:
TypeError: catching classes that do not inherit from BaseException is not allowed
In this regard I have gone through this: Can't catch mocked exception because it doesn't inherit BaseException. But I am not getting how to make this work for pymysql.
EDIT 1: As suggested, I have tried to mock only pymysql.connect as follows:
#patch('my_package.my_module.pymysql.connect')
def test_execute_with_failure(self, mock_pymysql_conn):
cursor = MagicMock()
mock_pymysql_conn.return_value.cursor = cursor
self.my_obj.cur = cursor
self.my_obj.cur.execute.side_effect = pymysql.Error
with self.assertRaises(pymysql.Error) as context:
_ = self.my_obj.execute(query="SELECT FOO FROM BAR")
But, I am getting here, as follows:
E AttributeError: <module 'pymysql' from '/my_project/venv/lib/python3.7/site-packages/pymysql/__init__.py'> does not have the attribute ''
EDIT 2: I have tried with below approach as well:
#patch('my_package.my_module.pymysql')
def test_execute_with_failure(self, mock_pymysql):
conn = Mock()
mock_pymysql.connect.return_value = conn
cursor = MagicMock()
conn.return_value.cursor = cursor
self.my_obj.cur = cursor
mock_pymysql.Error = type('PymysqlError', (Exception,), {})
self.my_obj.cur.execute.side_effect = mock_pymysql.Error
with self.assertRaises(mock_pymysql.Error) as context:
_ = self.my_obj.execute(query="SELECT * FROM TEST")
Still the same error as Edit 1.

how to return a collection from mongodb using pymongo

I'm trying to create a Collection Class in Python to access the various collections in my db. Here's what I've got:
import sys
import os
import pymongo
from pymongo import MongoClient
class Collection():
client = MongoClient()
def __init__(self, db, collection_name):
self.db = db
self.collection_name = collection_name
# self.data_base = getattr(self.client, db)
# self.collObject = getattr(self.data_base, self.collection_name)
def getCollection(self):
data_base = getattr(self.client, self.db)
collObject = getattr(data_base, self.collection_name)
return collObject
def getCollectionKeys(self, collection):
"""Get a set of keys from a collection"""
keys_list = []
collection_list = collection.find()
for document in collection_list:
for field in document.keys():
keys_list.append(field)
keys_set = set(keys_list)
return keys_set
if __name__ == '__main__':
print"Begin Main"
agents = Collection('hkpr_restore','agents')
print "agents is" , agents
agents_collection = agents.getCollection
print agents_collection
print agents.getCollectionKeys(agents_collection)
I get the following output:
Begin Main
agents is <__main__.Collection instance at 0x10ff33e60>
<bound method Collection.getCollection of <__main__.Collection instance at 0x10ff33e60>>
Traceback (most recent call last):
File "collection.py", line 52, in <module>
print agents.getCollectionKeys(agents_collection)
File "collection.py", line 35, in getCollectionKeys
collection_list = collection.find()
AttributeError: 'function' object has no attribute 'find'
The function getCollectionKeys works fine outside of a class. What am I doing wrong?
This line:
agents_collection = agents.getCollection
Should be:
agents_collection = agents.getCollection()
Also, you don't need to use getattr the way you are. Your getCollection method can be:
def getCollection(self):
return self.client[self.db][self.collection_name]

how to make a python-mysqldb template?

I've learn some basics about python-mysqldb ,when I want to define anther function for query,I have to write (connect ,cursor...try ..) repeatedly
so I want to design a template like jdbcTemplate (Java EE, Spring)
my code is:
def DBV():
def templateFN(fn):
logging.basicConfig(level=logging.INFO)
log = logging.getLogger('DB')
conn = MySQLdb.connect(user='root',passwd='247326',db='lucky',charset="utf8",cursorclass=MySQLdb.cursors.DictCursor);
cursor = conn.cursor()
def wrap(data=None):
try:
return fn(cursor=cursor,data=data)
#conn.commit()
except Exception ,e:
conn.rollback()
log.error('%s, transaction rollback',e)
finally:
cursor.close()
conn.close()
return wrap
class DB():
#templateFN
def insertTest(self,cursor,data=None):
data = {
'field':'this is a test',
'name':'this is a name'
}
return cursor.execute('insert into test(field,name) values(%(field)s,%(name)s)',data)
return DB()
db = DBV()
print 'return value',db.insertTest(data="ok")
Traceback (most recent call last):
File "D:\WorkSpaces\Aptana Studio 3 Workspace\VLuck\src\com\test.py", line 164, in
print 'return value',db.insertTest(data="ok")
TypeError: wrap() got multiple values for keyword argument 'data'
but failed,how should I do it right
Here's a solution I came up with, inspired by another answer:
def connect_mysql(func):
# Assign value of 'self' to be default func
func.func_defaults = func.func_defaults[:-1] + (func,)
func._cnx = mysql.connector.connect(**CONFIG)
func._cursor = func._cnx.cursor()
return func
#connect_mysql
def test(data, self=None):
self._cursor.execute("SELECT %(c1)s", data)
print(self._cursor.fetchall())
test({'c1': 1})

AttributeError: 'NoneType' object has no attribute 'GetDataStore'

I guys, I developing a utility in python and i have 2 object the main class and an database helper for get sqlserver data.
database.py
import _mssql
class sqlserver(object):
global _host, _userid, _pwd, _db
def __new__ (self, host, userid, pwd, database):
_host = host
_userid = userid
_pwd = pwd
_db = database
def GetDataStore(self, sql):
conn = _mssql.connect(server='(local)\\sqlexpress', user='sa', password='xxx', database='Framework.Data2')
conn.execute_non_query('CREATE TABLE persons(id INT, name VARCHAR(100))')
conn.execute_non_query("INSERT INTO persons VALUES(1, 'John Doe')")
conn.execute_non_query("INSERT INTO persons VALUES(2, 'Jane Doe')")
gaemodel.py
import os
import sys
from fwk import system, types, databases
class helper(object):
pass
def usage(app_name):
return "Usage: %s <project name>" % (app_name)
def main(argv):
_io = system.io()
project_name = argv[1]
project_home = os.path.join(_io.CurrentDir(), project_name)
_db = databases.sqlserver('(local)\sqlexpress', 'sa', 'xxx', 'Framework.Data2')
_db.GetDataStore("select name from sysobjects where xtype = 'U' and name not like 'Meta%'")
str = "from google.appengine.ext import db"
#for row in cur:
# str += "class %s" % row["name"]
print cur
if __name__ == "__main__":
if len(sys.argv) > 1:
main(sys.argv[1:])
else:
print usage(sys.argv[0]);
My problem is when i try run code return me this error
Traceback (most recent call last):
File "C:\Projectos\FrameworkGAE\src\gaemodel.py", line 28, in <module>
main(sys.argv[1:])
File "C:\Projectos\FrameworkGAE\src\gaemodel.py", line 18, in main
_ db. GetDataStore("select name from sysobjects where xtype = 'U' and name not like 'Meta%'")
AttributeError: 'NoneType' object has no attribute 'GetDataStore'
What is wrong ??
First of all:
The __new__ method should be named __init__.
Remove the global _host etc. line
Then change the __init__ method:
self.host = host
self.userid = userid
etc.
And change GetDataStore:
conn = _mssql.connect(server=self.host, user=self.userid, etc.)
That should do the trick.
I suggest you read a bit on object-oriented Python.
Have a look at what __new__ is supposed to be doing and what arguments it's supposed to have. I think you wanted to use __init__ and not __new__. The reason for your particular error is that _db is None.
I think you want to change databases.py like this:
import _mssql
class sqlserver(object):
def __init__ (self, host, userid, pwd, database):
self.host = host
self.userid = userid
self.pwd = pwd
self.db = database
def GetDataStore(self, sql):
conn = _mssql.connect(server=self.host, user=self.userid, password=self.pwd, database=self.db)
conn.execute_non_query('CREATE TABLE persons(id INT, name VARCHAR(100))')
conn.execute_non_query("INSERT INTO persons VALUES(1, 'John Doe')")
conn.execute_non_query("INSERT INTO persons VALUES(2, 'Jane Doe')")

Categories

Resources