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}