AttributeError: database instance has no attribute '_db' - python

I copied this code from some place in internet , i was trying to learn python from some video tutorial and i found this code ..
When i am trying to compile it with python2.7 its given below errro
ERROR-OUTPUT
In [23]: %run "C:\Users\Developer\Canopy\DevDir\aaa.py"
Create table test
AttributeError Traceback (most recent call last)
C:\Users\Developer\Canopy\DevDir\aaa.py in <module>()
101 for row in db: print(row)
102
--> 103 if __name__ == "__main__": main()
C:\Users\Developer\Canopy\DevDir\aaa.py in main()
78
79 print('Create table test')
---> 80 db.sql_do('drop table if exists test')
81 db.sql_do('create table test ( t1 text, i1 int )')
82
C:\Users\Developer\Canopy\DevDir\aaa.py in sql_do(self, sql, *params)
13
14 def sql_do(self, sql, *params):
---> 15 self._db.execute(sql, params)
16 self._db.commit()
17
AttributeError: database instance has no attribute '_db'
Code
#!/usr/bin/python3
import sqlite3
class database:
def __init__(self, **kwargs):
self.filename = kwargs.get('filename')
self.table = kwargs.get('table', 'test')
def sql_do(self, sql, *params):
self._db.execute(sql, params)
self._db.commit()
def insert(self, row):
self._db.execute('insert into {} (t1, i1) values (?, ?)'.format(self._table), (row['t1'], row['i1']))
self._db.commit()
def retrieve(self, key):
cursor = self._db.execute('select * from {} where t1 = ?'.format(self._table), (key,))
return dict(cursor.fetchone())
def update(self, row):
self._db.execute(
'update {} set i1 = ? where t1 = ?'.format(self._table),
(row['i1'], row['t1']))
self._db.commit()
def delete(self, key):
self._db.execute('delete from {} where t1 = ?'.format(self._table), (key,))
self._db.commit()
def disp_rows(self):
cursor = self._db.execute('select * from {} order by t1'.format(self._table))
for row in cursor:
print(' {}: {}'.format(row['t1'], row['i1']))
def __iter__(self):
cursor = self._db.execute('select * from {} order by t1'.format(self._table))
for row in cursor:
yield dict(row)
#property
def filename(self):
return self._filename
#filename.setter
def filename(self, fn):
self._filename = fn
self._db = sqlite3.connect(fn)
self._db.row_factory = sqlite3.Row
#filename.deleter
def filename(self): self.close()
#property
def table(self): return self._table
#table.setter
def table(self, t): self._table = t
#table.deleter
def table(self): self._table = 'test'
def close(self):
self._db.close()
del self._filename
def main():
db = database(filename = 'test.db', table = 'test')
print('Create table test')
db.sql_do('drop table if exists test')
db.sql_do('create table test ( t1 text, i1 int )')
print('Create rows')
db.insert(dict(t1 = 'one', i1 = 1))
db.insert(dict(t1 = 'two', i1 = 2))
db.insert(dict(t1 = 'three', i1 = 3))
db.insert(dict(t1 = 'four', i1 = 4))
for row in db: print(row)
print('Retrieve rows')
print(db.retrieve('one'), db.retrieve('two'))
print('Update rows')
db.update(dict(t1 = 'one', i1 = 101))
db.update(dict(t1 = 'three', i1 = 103))
for row in db: print(row)
print('Delete rows')
db.delete('one')
db.delete('three')
for row in db: print(row)
if __name__ == "__main__": main()
There is no indention error
I am not able to figure out how to make it work
Any Help ?

in python2.7 properties are less elegant (and this is not too well programmed imho. it is usually good practice to define all members in the constructor; among other things):
import sqlite3
class database:
def __init__(self, **kwargs):
self._set_filename(kwargs.get('filename'))
self._set_table( kwargs.get('table', 'test') )
def sql_do(self, sql, *params):
self._db.execute(sql, params)
self._db.commit()
def insert(self, row):
self._db.execute('insert into {} (t1, i1) values (?, ?)'.format(self._table), (row['t1'], row['i1']))
self._db.commit()
def retrieve(self, key):
cursor = self._db.execute('select * from {} where t1 = ?'.format(self._table), (key,)) print 'SETTER'
return dict(cursor.fetchone())
def update(self, row):
self._db.execute(
'update {} set i1 = ? where t1 = ?'.format(self._table),
(row['i1'], row['t1']))
self._db.commit()
def delete(self, key):
self._db.execute('delete from {} where t1 = ?'.format(self._table), (key,))
self._db.commit()
def disp_rows(self):
cursor = self._db.execute('select * from {} order by t1'.format(self._table))
for row in cursor:
print(' {}: {}'.format(row['t1'], row['i1']))
def __iter__(self):
cursor = self._db.execute('select * from {} order by t1'.format(self._table))
for row in cursor:
yield dict(row)
def _get_filename(self):
return self._filename
def _set_filename(self, fn):
self._filename = fn
self._db = sqlite3.connect(fn)
self._db.row_factory = sqlite3.Row
def _del_filename(self): self.close()
filename = property(_get_filename, _set_filename, _del_filename)
def _get_table(self): return self._table
def _set_table(self, t): self._table = t
def _del_table(self): self._table = 'test'
table = property(_get_table, _set_table, _del_table)
def close(self):
self._db.close()
del self._filename
def main():
db = database(filename = 'test.db', table = 'test')
print('Create table test')
db.sql_do('drop table if exists test')
db.sql_do('create table test ( t1 text, i1 int )')
print('Create rows')
db.insert(dict(t1 = 'one', i1 = 1))
db.insert(dict(t1 = 'two', i1 = 2))
db.insert(dict(t1 = 'three', i1 = 3))
db.insert(dict(t1 = 'four', i1 = 4))
for row in db: print(row)
print('Retrieve rows')
print(db.retrieve('one'), db.retrieve('two'))
print('Update rows')
db.update(dict(t1 = 'one', i1 = 101))
db.update(dict(t1 = 'three', i1 = 103))
for row in db: print(row)
print('Delete rows')
db.delete('one')
db.delete('three')
for row in db: print(row)
if __name__ == "__main__": main()

Related

Transferring Classes/Tables from a module to a main function:

recently I have been trying to recreate lua's Table module in python:
class Table():
def __init__(self):
try:
self.Size = enumerate(self)
except:
self.Size = 0
def size(query):
index = 0
for v in query.__dict__.items():
index+=1
return index
def create(query, items=None, t=None):
if items == None and t == None:
class temp():
def __init__(self):
self.Size = Table.size(self)
globals()[query] = temp
elif items != None and t == None:
class test():
def add_child(self, child, val):
setattr(self, child, val)
Size = 6
globals()[query] = test
_ = items.split(',')
Table.create('tempe')
for _z in _:
_f = _z.split('=')
setattr(tempe,_f[0],_f[1])
msg = ('v',str(Table.size(test)+1))
setattr(test,''.join(msg),tempe)
elif t == 'child' and query is not None and type(query) == type:
_ = items.split(',')
Table.create('tempe')
for _z in _:
_f = _z.split('=')
setattr(tempe, _f[0], _f[1])
msg = ('v',str(Table.size(query)+1))
setattr(query,''.join(msg),tempe)
else:
pass
def insert(query, items):
Table.create(query, items, 'child')
def remove(query, item):
temp = ('v', str(item))
item = ''.join(temp)
for k in query.__dict__.items():
for m in k:
if m == item:
del m
def pairs(query,func):
index = 0
for _ in query.__dict__.items():
index+=1
if index > query.Size:
for out in _:
if type(out) == type:
i = index-query.Size
v = out
func(i,v)
Now on its own, that works fine. But now I'm trying to put it into a seperate file so I can do:
from Resources import Table, #other stuff
Table.create('test', 'var1 = 10, var2=Hello World!, var3 = 69')
def pr(i,v):
print(f'{i} = [var1 = {v.var1}, var2 = {v.var2}, var3 = {v.var3}]')
pairs(test,pr)
If I ran that not as a module, I would get:
#1 = [var1 = 10, var2 = Hello World!, var3 = 69]
However when its in a separate file, 'test' does not become a variable.
Any advice/tips are apprecianted.

sqlite3.OperationalError: no such table?

import sqlite3
class Database1:
def __init__(self,**args):
self.filename = args.get('filename')
self.table = args.get('table','test')
def sql_do(self,sql,*params):
self._db.execute(sql,params)
def insert(self,row):
self._db.execute('insert into {}(t1,i1)values(?,?)'.format(self._table),(row['t1'],row['i1']))
def retrieve(self,key):
cursor = self._db.execute('select * from {} where i1 = ?'.format(self._table),(key,))
return dict(cursor.fetchone())
def update(self,row):
self._db.execute('update {} set t1 = ? where i1 = ?'.format(self._table),(row['t1'],row['i1']))
def delete(self,key):
self._db.execute('delete from {} where i1 = ?'.format(self._table))
def __iter__(self):
cs = self._db.execute('select * from {} order by i1'.format(self._table))
for i in cs:
yield dict(i) #no dict
#property
def filename(self): return self._filename
#filename.setter
def filename(self,fn):
self._filename = fn
self._db = sqlite3.connect(fn)
self._db.row_factory = sqlite3.Row
#filename.deleter
def filename(self): self.close()
#property
def table(self): return self._table
#table.setter
def table(self,T): self._table = T
#table.deleter
def table(self): self._table = "test"
def close(self):
self._db.close()
del self._filename
def main():
db = Database1(filename = "dbfile.db",table = "test")
db.sql_do('drop table if exists dbfile')
db.sql_do('create table dbfile(t1 text,i1 int)')
print('Insert data')
db.insert(dict(t1 = 'one',i1 = 1))
db.insert(dict(t1 = 'two',i1 = 2))
db.insert(dict(t1 = 'three',i1 = 3))
for disp in db: print(disp)
print('Retrieve data')
print(db.retrieve(1),db.retrieve(2),db.retrieve(3))
print('Updateed data')
db.update(dict(t1 = 'amir',i1 = 1))
db.update(dict(t1 = 'reza',i1 = 2))
for disp in db: print(disp)
print('deleteed data')
db.delete(3)
db.delete(1)
for disp in db: print(disp)
main()
Why Error?
Traceback (most recent call last):
File "c:\Users\Computer Parsian\Desktop\Untitled-1.py", line 76, in <module>
main()
File "c:\Users\Computer Parsian\Desktop\Untitled-1.py", line 57, in main
db.insert(dict(t1 = 'one',i1 = 1))
File "c:\Users\Computer Parsian\Desktop\Untitled-1.py", line 12, in insert
self._db.execute('insert into {}(t1,i1)values(?,?)'.format(self._table),(row['t1'],row['i1']))
sqlite3.OperationalError: no such table: test
Your Error is because you have named the table dbfile when creating the table as per
db.sql_do('drop table if exists dbfile')
db.sql_do('create table dbfile(t1 text,i1 int)')
You subsequently try to insert data into a table named test which doesn't exist as the only table is dbfile.
Additionally the you have omitted the parameter for the bind in delete you have :-
self._db.execute('delete from {} where i1 = ?'.format(self._table))
I believe that the following, is along the lines of what you want (see comments for changes applied) :-
import sqlite3
class Database1:
def __init__(self,**args):
self.filename = args.get('filename')
self.table = args.get('table','test')
def sql_do(self,sql,*params):
self._db.execute(sql,params)
def insert(self,row):
self._db.execute('insert into {}(t1,i1)values(?,?)'.format(self._table),(row['t1'],row['i1']))
def retrieve(self,key):
cursor = self._db.execute('select * from {} where i1 = ?'.format(self._table),(key,))
return dict(cursor.fetchone())
def update(self,row):
self._db.execute('update {} set t1 = ? where i1 = ?'.format(self._table),(row['t1'],row['i1']))
def delete(self,key):
self._db.execute('delete from {} where i1 = ?'.format(self._table),(key,)) #<<<<< Amended
def __iter__(self):
cs = self._db.execute('select * from {} order by i1'.format(self._table))
for i in cs:
yield dict(i) #no dict
#property
def filename(self): return self._filename
#filename.setter
def filename(self,fn):
self._filename = fn
self._db = sqlite3.connect(fn)
self._db.row_factory = sqlite3.Row
#filename.deleter
def filename(self): self.close()
#property
def table(self): return self._table
#table.setter
def table(self,T): self._table = T
#table.deleter
def table(self): self._table = "test"
def close(self):
self._db.close()
del self._filename
def main():
table = "test"
db = Database1(filename = "dbfile.db",table = table) #<<<<< Optional use the single value previously defined
db.sql_do('drop table if exists ' + table) #<<<<< Amended
db.sql_do('create table ' + table + '(t1 text,i1 int)') #<<<<< Amended
print('Insert data')
db.insert(dict(t1 = 'one',i1 = 1))
db.insert(dict(t1 = 'two',i1 = 2))
db.insert(dict(t1 = 'three',i1 = 3))
for disp in db: print(disp)
print('Retrieve data')
print(db.retrieve(1),db.retrieve(2),db.retrieve(3))
print('Updateed data')
db.update(dict(t1 = 'amir',i1 = 1))
db.update(dict(t1 = 'reza',i1 = 2))
for disp in db: print(disp)
print('deleteed data')
db.delete(3)
db.delete(1)
for disp in db: print(disp)
main()
Running this results in :-
Insert data
{'t1': 'one', 'i1': 1}
{'t1': 'two', 'i1': 2}
{'t1': 'three', 'i1': 3}
Retrieve data
{'t1': 'one', 'i1': 1} {'t1': 'two', 'i1': 2} {'t1': 'three', 'i1': 3}
Updateed data
{'t1': 'amir', 'i1': 1}
{'t1': 'reza', 'i1': 2}
{'t1': 'three', 'i1': 3}
deleteed data
{'t1': 'reza', 'i1': 2}
Process finished with exit code 0

ValueError: filedescriptor out of range in select() while using thrift?

I'm tring to provide a remote server by thrift, and below is my server-side trial:
from test_thrift.test_server.TestService import Iface,Processor
from thrift.Thrift import TType,TException
from thrift.Thrift import TProcessor
from thrift.transport import TSocket
from thrift.protocol import TBinaryProtocol
from thrift.server import TNonblockingServer
port = int(config["server"]["port"])
handler = SmbService()
processor = Processor(handler)
socket = TSocket.TServerSocket(port=port)
server = TNonblockingServer.TNonblockingServer(processor, socket)
server.setNumThreads(100)
server.serve()
At my client-side, for every request I will create a new connect and close it after got response from server.
from thrift.transport.TSocket import TTransportException
from thrift.Thrift import TException
from thrift.protocol import TBinaryProtocol, TCompactProtocol
from thrift.transport import TTransport
from thrift.transport import TSocket
from thrift import Thrift
from test_thrift.test_server import TestService
class SmbClient(object):
def __init__(self):
try:
self.tsocket = TSocket.TSocket(settings.THRIFT_HOST, settings.THRIFT_PORT_PRODUCT)
self.transportFactory = TTransport.TFramedTransportFactory()
self.transport = self.transportFactory.getTransport(self.tsocket)
self.protocol = TBinaryProtocol.TBinaryProtocol(self.transport)
self.client = TestService.Client(self.protocol)
self.transport.open()
except Thrift.TException as e:
self.logger.info(e)
class BaseService(object):
def __init__(self):
self.commonLogger = logging.getLogger('ads')
self.header = "header111"
def search_ads_list(self, request, account_id):
self.smbClient.client.getFBAdsByAccount(param1, param2)
def __enter__(self):
self.smbClient = SmbClient()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.smbClient.transport.close()
ech request call is like this:
with BaseService() as BaseSingleService:
status, data, info = BaseSingleService.search_ads_list(
request, account_id)
The actual amount of requests from client are not big enough , but after period of time. I got error like :
Traceback (most recent call last):
File "/home/xxx/xxx/src/smb_thrift_server.py", line 2200, in <module>
server.serve()
File "/home/xxx/xxx/venv3/lib/python3.5/site-packages/thrift/server/TNonblockingServer.py", line 350, in serve
self.handle()
File "/home/xxx/xxxx/venv3/lib/python3.5/site-packages/thrift/server/TNonblockingServer.py", line 310, in handle
rset, wset, xset = self._select()
File "/home/luban/smb_thrift_server/venv3/lib/python3.5/site-packages/thrift/server/TNonblockingServer.py", line 302, in _select
return select.select(readable, writable, readable)
ValueError: filedescriptor out of range in select()
Why error happended as I've closed the client connect each time after receiving the response?
update TestService codes below:
#
# Autogenerated by Thrift Compiler (0.9.1)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py:new_style
#
from thrift.Thrift import TType, TMessageType, TException, TApplicationException
from .ttypes import *
from thrift.Thrift import TProcessor
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol, TProtocol
try:
from thrift.protocol import fastbinary
except:
fastbinary = None
class Iface(object):
"""..."""
def getFBAdsByAccount(self, header, account_id, effective_status, access_token):
"""
Parameters:
- header
- account_id
- effective_status
- access_token
"""
pass
"""..."""
class Client(Iface):
def __init__(self, iprot, oprot=None):
self._iprot = self._oprot = iprot
if oprot is not None:
self._oprot = oprot
self._seqid = 0
def getFBAdsByAccount(self, header, account_id, effective_status, access_token):
"""
Parameters:
- header
- account_id
- effective_status
- access_token
"""
self.send_getFBAdsByAccount(header, account_id, effective_status, access_token)
return self.recv_getFBAdsByAccount()
def send_getFBAdsByAccount(self, header, account_id, effective_status, access_token):
self._oprot.writeMessageBegin('getFBAdsByAccount', TMessageType.CALL, self._seqid)
args = getFBAdsByAccount_args()
args.header = header
args.account_id = account_id
args.effective_status = effective_status
args.access_token = access_token
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush()
def recv_getFBAdsByAccount(self):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = getFBAdsByAccount_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.success is not None:
return result.success
if result.e is not None:
raise result.e
raise TApplicationException(TApplicationException.MISSING_RESULT, "getFBAdsByAccount failed: unknown result");
class Processor(Iface, TProcessor):
def __init__(self, handler):
self._handler = handler
self._processMap = {}
self._processMap["getFBAdsByAccount"] = Processor.process_getFBAdsByAccount
def process(self, iprot, oprot):
(name, type, seqid) = iprot.readMessageBegin()
if name not in self._processMap:
iprot.skip(TType.STRUCT)
iprot.readMessageEnd()
x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' % (name))
oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid)
x.write(oprot)
oprot.writeMessageEnd()
oprot.trans.flush()
return
else:
self._processMap[name](self, seqid, iprot, oprot)
return True
def process_getFBAdsByAccount(self, seqid, iprot, oprot):
args = getFBAdsByAccount_args()
args.read(iprot)
iprot.readMessageEnd()
result = getFBAdsByAccount_result()
try:
result.success = self._handler.getFBAdsByAccount(args.header, args.account_id, args.effective_status, args.access_token)
except test_thrift.common.ttypes.ServerException as e:
result.e = e
oprot.writeMessageBegin("getFBAdsByAccount", TMessageType.REPLY, seqid)
result.write(oprot)
oprot.writeMessageEnd()
oprot.trans.flush()
class getFBAdsByAccount_args(object):
"""
Attributes:
- header
- account_id
- effective_status
- access_token
"""
thrift_spec = (
None, # 0
(1, TType.STRUCT, 'header', (test_thrift.common.ttypes.RequestHeader, test_thrift.common.ttypes.RequestHeader.thrift_spec), None, ), # 1
(2, TType.STRING, 'account_id', None, None, ), # 2
(3, TType.LIST, 'effective_status', (TType.STRING,None), None, ), # 3
(4, TType.STRING, 'access_token', None, None, ), # 4
)
def __init__(self, header=None, account_id=None, effective_status=None, access_token=None,):
self.header = header
self.account_id = account_id
self.effective_status = effective_status
self.access_token = access_token
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.header = test_thrift.common.ttypes.RequestHeader()
self.header.read(iprot)
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.STRING:
self.account_id = iprot.readString();
else:
iprot.skip(ftype)
elif fid == 3:
if ftype == TType.LIST:
self.effective_status = []
(_etype24, _size21) = iprot.readListBegin()
for _i25 in range(_size21):
_elem26 = iprot.readString();
self.effective_status.append(_elem26)
iprot.readListEnd()
else:
iprot.skip(ftype)
elif fid == 4:
if ftype == TType.STRING:
self.access_token = iprot.readString();
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('getFBAdsByAccount_args')
if self.header is not None:
oprot.writeFieldBegin('header', TType.STRUCT, 1)
self.header.write(oprot)
oprot.writeFieldEnd()
if self.account_id is not None:
oprot.writeFieldBegin('account_id', TType.STRING, 2)
oprot.writeString(self.account_id)
oprot.writeFieldEnd()
if self.effective_status is not None:
oprot.writeFieldBegin('effective_status', TType.LIST, 3)
oprot.writeListBegin(TType.STRING, len(self.effective_status))
for iter27 in self.effective_status:
oprot.writeString(iter27)
oprot.writeListEnd()
oprot.writeFieldEnd()
if self.access_token is not None:
oprot.writeFieldBegin('access_token', TType.STRING, 4)
oprot.writeString(self.access_token)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.items()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class getFBAdsByAccount_result(object):
"""
Attributes:
- success
- e
"""
thrift_spec = (
(0, TType.STRUCT, 'success', (test_thrift.common.ttypes.ResponseListMap, test_thrift.common.ttypes.ResponseListMap.thrift_spec), None, ), # 0
(1, TType.STRUCT, 'e', (test_thrift.common.ttypes.ServerException, test_thrift.common.ttypes.ServerException.thrift_spec), None, ), # 1
)
def __init__(self, success=None, e=None,):
self.success = success
self.e = e
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 0:
if ftype == TType.STRUCT:
self.success = test_thrift.common.ttypes.ResponseListMap()
self.success.read(iprot)
else:
iprot.skip(ftype)
elif fid == 1:
if ftype == TType.STRUCT:
self.e = test_thrift.common.ttypes.ServerException()
self.e.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('getFBAdsByAccount_result')
if self.success is not None:
oprot.writeFieldBegin('success', TType.STRUCT, 0)
self.success.write(oprot)
oprot.writeFieldEnd()
if self.e is not None:
oprot.writeFieldBegin('e', TType.STRUCT, 1)
self.e.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.items()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)

Python Mysql Class error

I'm trying to use this sql class https://github.com/nestordeharo/mysql-python-class to interact with mysql Local database ( server with easydevser, mysql version MySQL 5.7.10 ),but i'm always get an error msg when i try to make a select.
Here is the mysql class:
import MySQLdb, sys
from collections import OrderedDict
class MysqlPython(object):
"""
Python Class for connecting with MySQL server and accelerate development project using MySQL
Extremely easy to learn and use, friendly construction.
"""
__instance = None
__host = None
__user = None
__password = None
__database = None
__session = None
__connection = None
def __new__(cls, *args, **kwargs):
if not cls.__instance or not cls.__database:
cls.__instance = super(MysqlPython, cls).__new__(cls,*args,**kwargs)
return cls.__instance
## End def __new__
def __init__(self, host='localhost', user='root', password='', database=''):
self.__host = host
self.__user = user
self.__password = password
self.__database = database
## End def __init__
def __open(self):
try:
cnx = MySQLdb.connect(self.__host, self.__user, self.__password, self.__database)
self.__connection = cnx
self.__session = cnx.cursor()
except MySQLdb.Error as e:
print "Error %d: %s" % (e.args[0],e.args[1])
## End def __open
def __close(self):
self.__session.close()
self.__connection.close()
## End def __close
def select(self, table, where=None, *args, **kwargs):
result = None
query = 'SELECT '
keys = args
values = tuple(kwargs.values())
l = len(keys) - 1
for i, key in enumerate(keys):
query += "`"+key+"`"
if i < l:
query += ","
## End for keys
query += 'FROM %s' % table
if where:
query += " WHERE %s" % where
print(query)
## End if where
self.__open()
self.__session.execute(query, values)
number_rows = self.__session.rowcount
number_columns = len(self.__session.description)
if number_rows >= 1 and number_columns > 1:
result = [item for item in self.__session.fetchall()]
else:
result = [item[0] for item in self.__session.fetchall()]
self.__close()
return result
## End def select
def update(self, table, where=None, *args, **kwargs):
query = "UPDATE %s SET " % table
keys = kwargs.keys()
values = tuple(kwargs.values()) + tuple(args)
l = len(keys) - 1
for i, key in enumerate(keys):
query += "`"+key+"` = %s"
if i < l:
query += ","
## End if i less than 1
## End for keys
query += " WHERE %s" % where
self.__open()
self.__session.execute(query, values)
self.__connection.commit()
# Obtain rows affected
update_rows = self.__session.rowcount
self.__close()
return update_rows
## End function update
def insert(self, table, *args, **kwargs):
values = None
query = "INSERT INTO %s " % table
if kwargs:
keys = kwargs.keys()
values = tuple(kwargs.values())
query += "(" + ",".join(["`%s`"] * len(keys)) % tuple (keys) + ") VALUES (" + ",".join(["%s"]*len(values)) + ")"
elif args:
values = args
query += " VALUES(" + ",".join(["%s"]*len(values)) + ")"
self.__open()
self.__session.execute(query, values)
self.__connection.commit()
self.__close()
return self.__session.lastrowid
## End def insert
def delete(self, table, where=None, *args):
query = "DELETE FROM %s" % table
if where:
query += ' WHERE %s' % where
values = tuple(args)
self.__open()
self.__session.execute(query, values)
self.__connection.commit()
# Obtain rows affected
delete_rows = self.__session.rowcount
self.__close()
return delete_rows
## End def delete
def select_advanced(self, sql, *args):
od = OrderedDict(args)
query = sql
values = tuple(od.values())
self.__open()
self.__session.execute(query, values)
number_rows = self.__session.rowcount
number_columns = len(self.__session.description)
if number_rows >= 1 and number_columns > 1:
result = [item for item in self.__session.fetchall()]
else:
result = [item[0] for item in self.__session.fetchall()]
self.__close()
return result
## End def select_advanced
## End class
Here is the part of my code when i made the instance and use a select method:
db = MysqlPython(host='localhost', user='root', password='', database='mgdeal')
conditional_query = 'categorie = %s '
result = db.select('table 2', conditional_query, 'nom', 'url', categorie='Lego')
Then i get the followings error
SELECT `nom`,`url`FROM table 2 WHERE categorie = %s
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table 2 WHERE categorie = 'Lego'' at line 1")
Do you have any idea
I found the issue on the code, It's coming from this part for the select method.
query += 'FROM %s' % table
must be replace by
query += 'FROM `%s`' % table

how to block the loops when storing in a database?

I have got a problem with my current script where I'm working on the keyboard event for xbmc. When I'm pressing on the enter button of the keyboard, the code will keep firing by re-fetching the same values from the XML tags which it will keep doing it over and over for number of times and it will keep storing the same values in the database when there are few values from the XML tags called 'display-name'.
Here's the code:
import xbmc
import xbmcgui
import xbmcaddon
import os
import urllib2
import StringIO
import sqlite3
from sqlite3 import dbapi2 as database
from xml.etree import ElementTree
class Channel:
def __init__(self):
self.__display_name = None
self.__icon = None
self.__programs = []
def get_display_name(self):
return self.__display_name
def get_icon(self):
return self.__icon
def get_programs(self):
return self.__programs
def set_display_name(self, value):
self.__display_name = value
def set_icon(self, value):
self.__icon = value
def set_programs(self, value):
self.__programs = value
def del_display_name(self):
del self.__display_name
def del_icon(self):
del self.__icon
def del_programs(self):
del self.__programs
display_name = property(get_display_name, set_display_name, del_display_name, "display_name's docstring")
icon = property(get_icon, set_icon, del_icon, "icon's docstring")
programs = property(get_programs, set_programs, del_programs, "programs's docstring")
class Programme:
def __init__(self):
self.__start = None
self.__stop = None
self.__title = None
self.__sub_title = None
self.__desc = None
self.__category = []
self.__credits = []
self.__icon = None
self.__episode_num = None
def get_episode_num(self):
return self.__episode_num
def set_episode_num(self, value):
self.__episode_num = value
def del_episode_num(self):
del self.__episode_num
def get_start(self):
return self.__start
def get_stop(self):
return self.__stop
def get_title(self):
return self.__title
def get_sub_title(self):
return self.__sub_title
def get_desc(self):
return self.__desc
def get_category(self):
return self.__category
def get_credits(self):
return self.__credits
def get_icon(self):
return self.__icon
def set_start(self, value):
self.__start = value
def set_stop(self, value):
self.__stop = value
def set_title(self, value):
self.__title = value
def set_sub_title(self, value):
self.__sub_title = value
def set_desc(self, value):
self.__desc = value
def set_category(self, value):
self.__category = value
def set_credits(self, value):
self.__credits = value
def set_icon(self, value):
self.__icon = value
def del_start(self):
del self.__start
def del_stop(self):
del self.__stop
def del_title(self):
del self.__title
def del_sub_title(self):
del self.__sub_title
def del_desc(self):
del self.__desc
def del_category(self):
del self.__category
def del_credits(self):
del self.__credits
def del_icon(self):
del self.__icon
start = property(get_start, set_start, del_start, "start's docstring")
stop = property(get_stop, set_stop, del_stop, "stop's docstring")
title = property(get_title, set_title, del_title, "title's docstring")
sub_title = property(get_sub_title, set_sub_title, del_sub_title, "sub_title's docstring")
desc = property(get_desc, set_desc, del_desc, "desc's docstring")
category = property(get_category, set_category, del_category, "category's docstring")
creditss = property(get_credits, set_credits, del_credits, "credits's docstring")
icon = property(get_icon, set_icon, del_icon, "icon's docstring")
episode_num = property(get_episode_num, set_episode_num, del_episode_num, "episode_num's docstring")
class Credits:
def __init__(self):
self.__type = None
self.__role = None
self.__name = None
def get_type(self):
return self.__type
def get_role(self):
return self.__role
def get_name(self):
return self.__name
def set_type(self, value):
self.__type = value
def set_role(self, value):
self.__role = value
def set_name(self, value):
self.__name = value
def del_type(self):
del self.__type
def del_role(self):
del self.__role
def del_name(self):
del self.__name
type = property(get_type, set_type, del_type, "type's docstring")
role = property(get_role, set_role, del_role, "role's docstring")
name = property(get_name, set_name, del_name, "name's docstring")
class MyClass(xbmcgui.WindowXML):
def __new__(cls):
return super(MyClass, cls).__new__(cls, 'script-tvguide-mainmenu.xml', ADDON.getAddonInfo('path'))
def onInit(self):
pass
def load_channel(self, elem):
channel = Channel()
for elem in elem.getchildren():
if elem.tag == 'display-name':
channel.set_display_name(elem.text)
elif elem.tag == 'icon':
channel.set_icon(elem.attrib['src'])
return channel
def load_programme(self, elem):
programme = Programme()
programme.set_start(elem.attrib['start'])
programme.set_stop(elem.attrib['stop'])
for elem in elem.getchildren():
if elem.tag == 'title':
programme.set_title(elem.text)
elif elem.tag == 'sub-title':
programme.set_title(elem.text)
elif elem.tag == 'desc':
programme.set_desc(elem.text)
elif elem.tag == 'category':
categories = programme.get_category()
categories.append(elem.text)
elif elem.tag == 'episode-num':
programme.set_episode_num(elem.text)
elif elem.tag == 'credits':
creditss = programme.get_credits()
creditss.append(self.load_credits(elem))
elif elem.tag == 'icon':
programme.set_icon(elem.attrib['src'])
return programme
def load_credits(self, elem):
creditss = Credits()
for elem in elem.getchildren():
if elem.tag == 'actor':
creditss.set_name(elem.text)
creditss.set_type('actor')
elif elem.tag == 'presenter':
creditss.set_name(elem.text)
creditss.set_type('presenter')
elif elem.tag == 'director':
creditss.set_name(elem.text)
creditss.set_type('director')
return credits
def onAction(self, action):
if action == ACTION_ENTER:
#OPEN THE XML SOURCE
url = ADDON.getSetting('ontv.url')
req = urllib2.Request(url)
response = urllib2.urlopen(req)
data = response.read()
response.close()
profilePath = xbmc.translatePath(os.path.join('special://userdata/addon_data/script.tvguide', ''))
if os.path.exists(profilePath):
profilePath = profilePath + 'source.db'
con = database.connect(profilePath)
cur = con.cursor()
cur.execute('CREATE TABLE programs(id TEXT, channel TEXT, title TEXT, start_date TIMESTAMP, end_date TIMESTAMP, description TEXT)')
con.commit()
con.close
tv_elem = ElementTree.parse(StringIO.StringIO(data)).getroot()
channels = {}
for elem in tv_elem.getchildren():
if elem.tag == 'channel':
channels[elem.attrib['id']] = self.load_channel(elem)
elif elem.tag == 'programme':
# get channel
channel = channels[elem.attrib['channel']]
# load program in channel
channel.get_programs().append(self.load_programme(elem))
# Print the loaded data
for channel_key in channels:
channel = channels[channel_key]
print channel.get_display_name() + ' :: ' + channel.get_icon() + ' :: Total programs = ' + str(len(channel.get_programs()))
display_name = channel.get_display_name()
profilePath = xbmc.translatePath(os.path.join('special://userdata/addon_data/script.tvguide', ''))
profilePath = profilePath + 'source.db'
con = sqlite3.connect(profilePath)
cur = con.cursor()
if not display_name in cur:
cur.execute("INSERT INTO programs(id, channel)" + " VALUES(?, ?)", [display_name, 0])
con.commit()
cur.close
print 'Channels store into database are now successfully!'
Here's the xml logs: http://xbmclogs.com/show.php?id=143587
Here's the database: http://testbox.elementfx.com/source.db
And here's the xml file: http://ontv.dk/xmltv/c81e728d9d4c2f636f067f89cc14862c
I only want to write the values in a database without keep re-fetching the same values over and over when I get the values from the XML tags.
Do you know how I can stop re-fetching the same values over and over when I store them in a database without keep running like a loop?

Categories