Update Sqlite3 in Python 3 - python

I have an object oriented function to update an inventory table, but when having execute the function by clicking the button it does not update and crashes the program, can anyone see me an error in this function? I am selecting the product to update in a QtableWidget
def editarProd(self):
cursor = banco.conexao.cursor()
query = """SELECT E.IDPRODUTO,
E.CODBARRA, E.PRODUTO,
C.CATEGORIA, printf("%.2f",E.ESTOQUE),
printf("%.2f",E.ESTOQUE_MIN), printf("%.2f",E.VALOR_CUSTO),
printf("%.2f",E.VALOR_VENDA), printf("%.2f",E.VALOR_VENDA-E.VALOR_CUSTO) AS "LUCRO",
F.FORNECEDOR
FROM ESTOQUE E
INNER JOIN FORNECEDOR F
ON E.ID_FORNECEDOR = F.IDFORNECEDOR
INNER JOIN CATEGORIA C
ON E.ID_CATEGORIA = C.IDCATEGORIA
ORDER BY E.PRODUTO"""
result = cursor.execute(query)
for row_number in enumerate(result):
if row_number[0] == self.listaprodutos.currentRow():
data = row_number[1]
IdProd = data[0]
codbarra = self.codigotext.text()
produto = self.produtotext.text()
estoque = self.estoquetext.text()
estoquemin = self.estoquemintext.text()
valorcusto = self.precocustotext.text()
valorvenda = self.precovendatext.text()
Forn = self.fornecedorcomboBox.currentData()
Cat = self.categoriacomboBox.currentData()
try:
cursor.execute = (f"""UPDATE ESTOQUE
SET CODBARRA ='{codbarra}',
PRODUTO ='{produto}',
ESTOQUE = {estoque},
ESTOQUE_MIN = {estoquemin},
VALOR_CUSTO = {valorcusto},
VALOR_VENDA = {valorvenda},
ID_CATEGORIA = {Cat},
ID_FORNECEDOR = {Forn}
WHERE IDPRODUTO = {IdProd}""")
banco.conexao.commit()
self.LoadDatabase ( )
self.limparcampos ( )
except Exception:
msg = QMessageBox ( )
msg.setText ( "Preencha os Campos" )
msg.setWindowTitle ( "Dados não inseridos!" )
msg.setStandardButtons ( QMessageBox.Ok | QMessageBox.Cancel )
msg.exec_ ( )

I solved my problem with some changes and it is working perfectly.
Follows the code.
def editarProd(self):
try:
cursor = banco.conexao.cursor()
query = ("""SELECT IDPRODUTO, CODBARRA, PRODUTO,
ID_CATEGORIA, ESTOQUE,
ESTOQUE_MIN, VALOR_CUSTO,
VALOR_VENDA, ID_FORNECEDOR
FROM ESTOQUE
ORDER BY PRODUTO""")
result = cursor.execute(query)
for row_number in enumerate(result):
if row_number[0] == self.listaprodutos.currentRow():
data = row_number[1]
IdProd = data[0]
codbarra = self.codigotext.text()
produto = self.produtotext.text()
estoque = self.estoquetext.text()
estoquemin = self.estoquemintext.text()
valorcusto = self.precocustotext.text()
valorvenda = self.precovendatext.text()
Forn = self.fornecedorcomboBox.currentData()
Cat = self.categoriacomboBox.currentData()
cursor.execute ( f"""UPDATE ESTOQUE SET CODBARRA='{codbarra}',
PRODUTO='{produto}',
ESTOQUE={estoque},
ESTOQUE_MIN={estoquemin},
VALOR_CUSTO={valorcusto},
VALOR_VENDA={valorvenda},
ID_CATEGORIA={Cat},
ID_FORNECEDOR={Forn}
WHERE IDPRODUTO={IdProd}""")
banco.conexao.commit()
self.LoadDatabase()
except Exception:
print('Erro!')

Related

Qr reading with Opencv in real time Error "cv2.error: opencv(4.7.0)"

I was developing an application to log in and out times using a Qr.
The system runs but when it is sent to register the hours the camera turns on and after a while this error appears.
invalid qr code source points (expected: 'contourarea(src_points) > 0.0'), where > 'contourarea(src_points)' is 0 > must be greater than > '0.0' is 0.
This is the part of the code as I have done where the error occurs
while (capture.isOpened()):
_,frame = capture.read()
if (cv2.waitKey(1)== ord('s')):
break
qrDetector = cv2.QRCodeDetector()
data,bbox, rectifiedImage = qrDetector.detectAndDecode(frame)
fecha = date.today()
now = datetime.now()
h=now.time()
**if len(data) > 0:** #LINEA DONDE SALTA EL ERROR
arr = data.replace("\'", "\"")
arreglo = json.loads(arr)
cedula = arreglo["Cedula"]
nombre = arreglo["Nombre"]
sql ='SELECT asi_id,asi_estado FROM asistencia WHERE asi_id = (select MAX(asi_id)from asistencia WHERE asi_cedula = %s)'
cursor.execute(sql,(cedula,))
datos = cursor.fetchone()
id = datos[0]
estado = datos[1]
if(cedula == cedula and estado == None or estado != "Entrada" ):
asistencia.lbestado.setText("Entrada")
estado1 = "Entrada"
sqli = 'INSERT INTO asistencia(asi_cedula,asi_nombre,asi_hora_e,asi_fecha,asi_estado)VALUES(%s,%s,%s,%s,%s)'
datos = (cedula,nombre,h,fecha,estado1)
cursor.execute(sqli,datos)
db.connection.commit()
else:
asistencia.lbestado.setText("Salida")
estado2 = "Salida"
sql2 = 'UPDATE asistencia SET asi_hora_s = %s, asi_estado = %s WHERE asi_cedula = %s AND asi_id = %s'
d2 = (h,estado2,cedula,id)
cursor.execute(sql2,d2)
db.connection.commit()
winsound.Beep(f,d)
time.sleep(2)
else:
image = qimage2ndarray.array2qimage(frame)
asistencia.lbvista.setPixmap(QPixmap.fromImage(image))
The objective is to keep the camera on all the time until the user decides to exit by closing the application.

can't adapt type 'data'

I have data class:
class data:
def __init__(self, ReadTime, Concentration_PM10, Concentration_SO2, Concentration_O3, Concentration_NO2, Concentration_CO, AQI_PM10,
AQI_SO2,AQI_O3, AQI_NO2, AQI_CO, AQI_AQIIndex, AQI_ContaminantParameter, AQI_State, AQI_Color ):
self.ReadTime = ReadTime
self.Concentration_PM10 = Concentration_PM10
self.Concentration_SO2 = Concentration_SO2
self.Concentration_O3 = Concentration_O3
self.Concentration_NO2 = Concentration_NO2
self.Concentration_CO = Concentration_CO
self.AQI_PM10 = AQI_PM10
self.AQI_SO2 = AQI_SO2
self.AQI_O3 = AQI_O3
self.AQI_NO2 = AQI_NO2
self.AQI_CO = AQI_CO
self.AQI_AQIIndex = AQI_AQIIndex
self.AQI_ContaminantParameter = AQI_ContaminantParameter
self.AQI_State = AQI_State
self.AQI_Color = AQI_Color
I'm sending a request to an api and populating the variables into a list.:
list = []
for i in result:
list.append( data(i['ReadTime'], i['Concentration']['PM10'], i['Concentration']['SO2'],i['Concentration']['O3'],
i['Concentration']['NO2'],i['Concentration']['CO'],i['AQI']['PM10'],
i['AQI']['SO2'],i['AQI']['O3'],i['AQI']['NO2'],i['AQI']['CO'],i['AQI']['AQIIndex'],i['AQI']['ContaminantParameter'],
i['AQI']['State'],i['AQI']['Color']))
then I want to insert this list into a table in PostgreSQL but I get error "can't adapt type 'data'"
list_record = ", ".join(["%s"] * len(list))
query_insert= (f"INSERT INTO hava_kalitesi (ReadTime, Concentration_PM10, Concentration_SO2, Concentration_O3, Concentration_NO2, Concentration_CO, AQI_PM10, AQI_SO2, AQI_O3, AQI_NO2, AQI_CO, AQI_AQIIndex, AQI_ContaminantParameter,AQI_State,AQI_Color) VALUES {list_record}"
)
cursor.execute(query_insert,list)

In Odoo 10,how can I specify a data in create_date,create_uid,instead of value in system,when I use method named 'create' to create a record

I create new record with the method named create() in local database with data pulled away from remote database.As we all know,there are four normal fields in Odoo such as create_date,write_date,create_uid,write_uid.I want these data to be in a remote database,but when I use method named create() to create the record,these data are the data at the time of local creation and not the remote data.
For example,in remote database,the creat_date is '2019-10-11',I can't change the value that is finally written to the local database even if I pass the value of the remote database into the dictionary.Finally,the value of field named create_date is '2019-12-03' rather than '2019-10-11'.The '2019-12-03' is the date now.The situation is similar for other fields such as write_date,create_uid,write_uid.
Please help me,thanks to everyone who thought about this question.
Following is my code.
The Class Model
class ReportRentalIncomeFromProperty(models.Model):
_name = 'report.rental.income.from.property'
_description = 'The report about the income from property rental'
_order = 'product_id, start_date'
# create_date = fields.Datetime('Created on')
create_uid = fields.Char('Created by')
# write_date = fields.Datetime('Last Modified on')
write_uid = fields.Char('Last Contributor')
product_id = fields.Many2one('product.product', 'Property House')
area_id = fields.Many2one('res.country.area', 'City')
district_id = fields.Many2one('res.country.district', 'District')
town_id = fields.Many2one('res.country.town', 'Town')
road_name = fields.Char('Road')
start_date = fields.Date('Start Date')
end_date = fields.Date('End Date')
should_pay = fields.Float('Should Pay')
real_pay = fields.Float('Real Pay')
balance_pay = fields.Float('Balance Pay')
rental_compliance_rate = fields.Float('Rental Compliance Rate(%)', group_operator="avg")
company_id = fields.Many2one('res.company', string='Company')
parent_company_id = fields.Many2one('res.company', related='company_id.parent_id', store=True,
string='Parent Company')
actual_business = fields.Many2many(
'rh.commercial.activities',
'house_rental_rent_income_business_db',
'actual_business_id',
'commercial_activities_id',
string='Actual business')
The function to pull away remote data to create new record in local database.
#api.multi
def synchronization_contract_performance_rate(self):
self.env['report.rental.income.from.property'].search([]).unlink()
product_dict = {}
A_product = self.env['product.product'].search([])
for a in A_product:
product_dict[a.name] = a.id
activities_dict = {}
D_activities = self.env['rh.commercial.activities'].search([])
for d in D_activities:
activities_dict[d.name] = d.id
address_dict = {}
i = 0
address_model_list = ['res.country.area', 'res.country.district', 'res.country.town']
address_field_list = ['area_id', 'district_id', 'town_id']
for addr in address_model_list:
C_address = self.env[addr].search([])
addr_dict = {}
for c in C_address:
addr_dict[c.name] = c.id
address_dict[i] = addr_dict
i += 1
record_list_1 = self.company_recursive_func()
for list_1 in record_list_1:
database = list_1[0]
link_url = list_1[1]
if link_url.startswith('http://'):
_uri = link_url.replace('http://', '')
my_odoo = odoorpc.ODOO(_uri, port=48080)
if link_url.startswith('https://'):
_uri = link_url.replace('https://', '')
my_odoo = odoorpc.ODOO(_uri, port=443, protocol='jsonrpc+ssl')
username = list_1[2]
password = list_1[3]
my_odoo.login(database, username, password)
company_id = list_1[4]
company_code = list_1[5]
product_actual_business_dict = {}
A_product_actual_business_ids = my_odoo.env['product.product'].search([])
A_product_actual_business = my_odoo.execute('product.product', 'read', A_product_actual_business_ids,
['actual_business'])
for a in A_product_actual_business:
name_list = []
for b in my_odoo.execute('rh.commercial.activities', 'read', a.get('actual_business'), ['name']):
name_list.append(b.get('name'))
product_actual_business_dict[a.get('id')] = name_list
remote_ids = my_odoo.env['report.rental.income.from.property'].search([])
remote_data_dict = my_odoo.execute('report.rental.income.from.property', 'read', remote_ids, ['product_id',
'start_date',
'create_date',
'create_uid',
'write_date',
'write_uid',
'end_date',
'should_pay',
'balance_pay',
'real_pay',
'rental_compliance_rate',
'area_id',
'road_name',
'district_id',
'town_id'])
for data in remote_data_dict:
remote_product_name = data.get('product_id')[1]
product_id = product_dict.get(remote_product_name + '(' + company_code + ')',
None)
if product_id:
i = 0
address_id_list = []
for address_field in address_field_list:
if data.get(address_field):
remote_address_name = data.get(address_field)[1]
local_address_id = address_dict[i].get(remote_address_name, None)
address_id_list.append(local_address_id)
else:
address_id_list.append(None)
i += 1
ids_list = []
find_names = product_actual_business_dict.get(data.get('product_id')[0])
for find_name in find_names:
id = activities_dict.get(find_name, None)
if id:
ids_list.append(id)
value = {
'product_id': product_id,
'area_id': address_id_list[0],
'district_id': address_id_list[1],
'town_id': address_id_list[2],
'road_name': data['road_name'],
'start_date': data['start_date'],
'end_date': data['end_date'],
'should_pay': data['should_pay'],
'real_pay': data['real_pay'],
'create_date': data['create_date'],
'create_uid': data['create_uid'][1],
'write_date': data['write_date'],
'write_uid': data['write_uid'][1],
'balance_pay':data['balance_pay'],
'rental_compliance_rate': data['rental_compliance_rate'],
'company_id': company_id,
'actual_business': [(6, 0, ids_list)]
}
self.env['report.rental.income.from.property'].create(value)
my_odoo.logout()
You can change standart odoo fields after you create your record with sql query
property_id = self.env['report.rental.income.from.property'].create(value)
self.env.cr.execute("UPDATE report_rental_income_from_property SET create_date='%s', create_uid=%s, write_date='%s', write_uid=%s WHERE id=%s" %
(value['create_date'], value['create_uid'], value['write_date'], value['write_uid'], property_id))

Python syntax error in class definition [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am new to Python I got an error at class def line. I am not sure what mistake I have done. Please check it and let me know.
class contactservices():
def GetDirectorySearchList(userId:int, searchKey,result:ContactResultSet):
ret = RETURN_CODE.RECORD_NOT_EXISTS
cursor = connections['default'].cursor()
rows =""
invalid syntax (contactservices.py, line 15)
Thanks in advance.
Full Code:
from django.db import connections
from api.enums import RETURN_CODE
from api.user.contactmodel import ContactModel
from api.user.contactmodel import DirectoryModel
from api.user.resultset import ContactResultSet
from api.datalayer.dbservices import dbservices
class contactservices():
"""Get Directory Search of a specific user"""
def GetDirectorySearchList(userId:int, searchKey, result:ContactResultSet):
ret = RETURN_CODE.RECORD_NOT_EXISTS
cursor = connections['default'].cursor()
rows =""
try:
#user triple quote for multiline string.
msqlquery = """SELECT a.id, username, first_name, last_name, firm,email,extension, extpassword,start_date,expiry_date,status,presence_status
,aliasname,picturepath,statusupdatedate
FROM ocktopi_login a where (first_name LIKE '%%""" + str(searchKey) + "%%' OR last_name LIKE '%%" + str(searchKey) + "%%' OR aliasname LIKE '%%" + str(searchKey) + "%%') AND id NOT IN (select contact from usercontactmapping where user = """ + str(userId) + ") and id <> " + str(userId) + "";
#cursor.execute(msqlquery)
rows = dbservices.query_to_dicts(msqlquery)
ret = RETURN_CODE.RECORD_EXISTS
except Exception as e:
ret = RETURN_CODE.RECORD_ERROR
#We dont have a way to map with column name . So only solution is column index.Changed to dictory using a method now.
directorylist = list()
for row in rows:
directory = DirectoryModel()
directory.Id = row['id']
directory.Username = row['username']
directory.FirstName = row['first_name']
directory.LastName = row['last_name']
directory.Firm = row['firm']
directory.Email = row['email']
directory.Extension = row['extension']
directory.Status = row['status']
directory.PresenceStatus = row['presence_status']
directory.AliasName = row['aliasname']
directory.Picturepath = row['picturepath']
directorylist.append(directory)
result.ReturnCode = int(ret)
return directorylist
"""Get Contact Details of a specific user"""
def GetContactList(userId:int, result:ContactResultSet):
ret = RETURN_CODE.RECORD_NOT_EXISTS
cursor = connections['default'].cursor()
rows =""
try:
#user triple quote for multiline string.
msqlquery = """SELECT a.id, username, first_name, last_name, firm,email,extension, extpassword,start_date,expiry_date,status,presence_status
,aliasname,picturepath,statusupdatedate
FROM ocktopi_login a inner join usercontactmapping b on a.id=b.contact and a.id <> """ + str(userId) + " and b.user= " + str(userId) + "";
rows = dbservices.query_to_dicts(msqlquery)
ret = RETURN_CODE.RECORD_EXISTS
except Exception as e:
ret = RETURN_CODE.RECORD_ERROR
#We dont have a way to map with column name . So only solution is column index.Changed to dictory using a method now.
contactlist = list()
for row in rows:
contact = ContactModel()
contact.Id = row['id']
contact.Username = row['username']
contact.FirstName = row['first_name']
contact.LastName = row['last_name']
contact.Firm = row['firm']
contact.Email = row['email']
contact.Extension = row['extension']
contact.Status = row['status']
contact.PresenceStatus = row['presence_status']
contact.AliasName = row['aliasname']
contact.Picturepath = row['picturepath']
contactlist.append(contact)
result.ReturnCode = int(ret)
return contactlist
"""Add user contact"""
def AddUserContact(userId:int, contactId:int):
ret = 0
cursor = connections['default'].cursor()
rows =""
try:
msqlquery = """insert into usercontactmapping (user,contact) values(%s, %s)""";
cursor.execute(msqlquery,(userId, contactId))
ret = cursor.rowcount
return ret
except Exception as e:
ret = -1
finally:
cursor.close()
return ret
"""Remove user contact"""
def RemoveUserContact(userId:int, contactId:int):
ret = 0
cursor = connections['default'].cursor()
rows =""
try:
msqlquery = """delete from usercontactmapping where user=%s and contact=%s""";
cursor.execute(msqlquery,(userId, contactId))
ret = cursor.rowcount
return ret
except Exception as e:
ret = -1
finally:
cursor.close()
return ret
Try:
def GetDirectorySearchList(userId, searchKey,result):
ret = RETURN_CODE.RECORD_NOT_EXISTS
cursor = connections['default'].cursor()
rows = ""
Annotations such as userId:int don't work in Python 2.7.
Also make sure the code is indented properly.

writing to data to excel

I have data that I need to export to excel, I just don't know how to go about it, here's the view I'm using, I've commented out my attempts.A push to the right direction will be greatly appreciated.
def month_end(request):
"""
A simple view that will generate a month end report as a PDF response.
"""
current_date = datetime.now()
context = {}
context['month'] = current_date.month
context['year'] = current_date.year
context['company'] = 3
if request.method == 'POST':
context['form'] = MonthEndForm(user=request.user, data=request.POST)
if context['form'].is_valid():
#from reportlab.pdfgen import canvas
#import ho.pisa as pisa
context['month_no'] = int(context['form'].cleaned_data['month'])
context['company'] = context['form'].cleaned_data['company']
context['year'] = context['form'].cleaned_data['year']
context['month'] = datetime(context['year'], context['month_no'], 1).strftime('%B')
sql = '''SELECT "campaign_provider"."originator" as originator, "campaign_provider"."cost",
"campaign_receivedmessage"."network_id",
COUNT("campaign_provider"."originator") AS "originator_count",
"shortcode_network"."network"
FROM "campaign_receivedmessage"
LEFT OUTER JOIN "shortcode_network" ON ("shortcode_network"."id" = "campaign_receivedmessage"."network_id")
LEFT OUTER JOIN "campaign_provider" ON ("campaign_receivedmessage"."provider_id" = "campaign_provider"."id")
WHERE ("campaign_provider"."company_id" = %s
AND EXTRACT('month' FROM "campaign_receivedmessage"."date_received") = %s)
GROUP BY "campaign_provider"."originator", "campaign_provider"."cost", "campaign_receivedmessage"."network_id", "shortcode_network"."network"
ORDER BY "campaign_provider"."originator", "campaign_receivedmessage"."network_id" ASC
''' % (context['company'].id, context['month_no'])
context['rec_messages']= []
cursor = connection.cursor()
cursor.execute(sql)
data = cursor.fetchall()
for row in data:
dict = {}
desc = cursor.description
for (name, value) in zip(desc, row) :
dict[name[0]] = value
try:
dict['share'] = RevenueShare.objects.get(company=context['company'], priceband=dict['cost'], network=dict['network_id']).customer_share
dict['revenue'] = dict['originator_count'] * dict['share']
except:
dict['share'] = 0
dict['revenue'] = 0
context['rec_messages'].append(dict)
#context['rec_messages'] = ReceivedMessage.objects.filter(provider__company__id=context['company'].id, date_received__month=context['month_no'], date_received__year=context['year']).values('provider__originator', 'provider__cost', 'network').annotate(originator_count=Count('provider__originator')).order_by('provider__originator')
context['ret_messages'] = SentMessage.objects.filter(campaign__providers__company__id=context['company'].id, date_sent__month=context['month_no'], date_sent__year=context['year']).values('campaign__title').annotate(campaign_count=Count('campaign__title')).order_by('campaign__title')
context['revenue_share'] = RevenueShare.objects.filter(company=context['company'].id)
context['total_rec'] = 0
context['total_ret'] = 0
context['total_value'] = 0
context['total_cost'] = 0
context['queries'] = connection.queries
for message in context['rec_messages']:
context['total_rec'] += message['originator_count']
context['total_value'] += message['revenue']
for message in context['ret_messages']:
message['price'] = 0.175
message['cost'] = message['campaign_count'] * message['price']
context['total_ret'] += message['campaign_count']
context['total_cost'] += message['cost']
context['total'] = context['total_value'] - context['total_cost']
context['loaded_report'] = "yes"
data.append((context['data']))
data.append(('Orginator', 'cost', 'network_id', 'originator_count', 'network'))
file_name = '%s' % ('reports')
return generate_csv(file_name, data)
#template_data = render_to_string('reports/month_end_pdf.html', RequestContext(request, context))
#csv_data = StringIO.StringIO()
#csv_data.seek()
#simple_report = ExcelReport()34
#simple_report.addSheet("TestSimple")
#simple_report.writeReport(csv_data)
#response = HttpResponse(simple_report.writeReport(),mimetype='application/ms-excel')
#response['Content-Disposition'] = 'attachment; filename=simple_test.xls'
#return response
return render_to_response('reports/month_end.html', RequestContext(request, context))
#return render_to_response('reports/rfm_models.html', RequestContext(request, context))
#template_data = render_to_string('reports/month_end_pdf.html', RequestContext(request, context))
#pdf_data = StringIO.StringIO()
#pisa.CreatePDF(template_data, pdf_data, link_callback=fetch_resources)
#pdf_data.seek(0)
#response = HttpResponse(pdf_data, mimetype='application/pdf')
#response['Content-Disposition'] = 'attachment; filename=%s_%s_%s.pdf' % (context['company'].name.lower().replace(' ', '_'), context['month'].lower()[:3], context['year'])
if 'form' not in context.keys():
context['form'] = MonthEndForm(user=request.user, data=context)
return render_to_response('reports/month_end.html', RequestContext(request, context))
Have a look to xlwt http://pypi.python.org/pypi/xlwt
You could directly write CSV from MySQL records,
import csv
csv_writer = csv.writer(open(FILENAME,'w'), delimiter=',',quotechar="'")
data = cursor.fetchall()
for row in data:
csv_writer.writerow(row)
Full example at
http://snipplr.com/view/11970/simple-csv-dump-script/
SELECTQ="SELECT * FROM category"
FILENAME="dump.csv"
import MySQLdb
import csv
db = MySQLdb.connect(host="localhost", user="root", passwd="", db="sakila")
dump_writer = csv.writer(open(FILENAME,'w'), delimiter=',',quotechar="'")
cursor = db.cursor()
cursor.execute(SELECTQ)
result = cursor.fetchall()
for record in result:
dump_writer.writerow(record)
db.close()

Categories