Discover Bluetooth devices on Android with Kivy - python

I want to implement Bluetooth on Android with Kivy.
I succeeded in finding if BT is activated, finding paired BT devices , and now I want to discover non-paired devices (in order to try to pair one of them). But I'm stuck, my onBroadcast method seems to never been called. Here is the complete code that I have for now
from kivy.app import App
from jnius import autoclass
import kivy
from android.broadcast import BroadcastReceiver
from android import activity, mActivity
import sys
from kivy.utils import platform
if platform == 'android':
BluetoothAdapter = autoclass('android.bluetooth.BluetoothAdapter')
BluetoothDevice = autoclass('android.bluetooth.BluetoothDevice')
PythonActivity = autoclass('org.kivy.android.PythonActivity')
REQUEST_CODE_ENABLE_BLUETOOTH = 0
class BluetoothApp(App):
def build(self):
print("*Bluetooth Début du programme 2")
self.layout = Builder.load_string(kv)
self.myData = []
if kivy.utils.platform == 'android':
activity.bind(on_activity_result=self.on_activity_result)
self.get_BT_devices()
else:
print('Works just on Android')
sys.exit()
self.layout.data = [item for item in self.myData]
print (self.myData)
print (kv)
print(self.layout.data)
return self.layout
def get_BT_devices(self):
# New method
BTAdapter = BluetoothAdapter.getDefaultAdapter()
if BTAdapter == None:
print("* Bluetooth inexistant!")
self.myData.append({"text": "Bluetooth inexistant!"})
else:
if not BTAdapter.isEnabled():
print("* Bluetooth non activé!")
self.myData.append({"text": "Bluetooth non activé"})
Intent = autoclass('android.content.Intent')
activeBlueTooth = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
print (f"activeBluetooth {activeBlueTooth}")
print("* Demande activation Bluetooth...")
mActivity.startActivityForResult(activeBlueTooth, REQUEST_CODE_ENABLE_BLUETOOTH)
else:
print("* Bluetooth activé")
self.myData.append({"text": "Bluetooth activé"})
# Obtenir la liste des périphèriques appairés
self.myData.append({"text": "Paired Devices"})
devices = BTAdapter.getBondedDevices()
print (f"devices {devices}")
for device in devices:
print(f" device {device}")
if (device.getAlias() == None):
print (f" name = {device.getName()}")
self.myData.append({"text": f"address {device.getAddress()}\nname {device.getName()}\n"})
else:
print (f" alias = {device.getAlias()}")
self.myData.append({"text": f"address {device.getAddress()}\nalias {device.getAlias()}\n"})
# Rechercher les périphériques non appairés
self.myData.append({"text": "Unpaired Devices"})
myReceiver = BroadcastReceiver(self.onBroadcast, actions = ['BluetoothDevice.ACTION_FOUND', 'BluetoothAdapter.ACTION_DISCOVERY_STARTED', 'BluetoothAdapter.ACTION_DISCOVERY_FINISHED'])
print (f"myReceiver {myReceiver}")
myReceiver.start()
print ("après le start")
def on_activity_result(self, requestCode, resultCode, intent):
# Appelé par mActivity.startActivityForResult(activeBlueTooth, REQUEST_CODE_ENABLE_BLUETOOTH)
if (requestCode != REQUEST_CODE_ENABLE_BLUETOOTH):
print(f"onActivityResult pas Bluetooth... {requestCode}")
return
if (resultCode == PythonActivity.RESULT_OK):
print("* Bluetooth activé")
else:
print("* Bluetooth toujours non activé !")
def onBroadcast(self, context, intent):
# Appelé par Broadcastreceiver
print(f"*BT* On receive context{context}", flush = True)
print(f"*BT* On receive intent {intent}", flush = True)
sys.stdout.flush()
if __name__ == '__main__':
kv = '''
RecycleView:
data: []
viewclass: 'Label'
RecycleBoxLayout:
default_size_hint: 1, 1
orientation: 'vertical'
'''
BluetoothApp().run()

Related

Tkinter window destroyed but program doesn't terminate

While creating a tkinter GUI application, I created a window with a button to close the program and terminate the script, but when I used it, the program did close but the script was still running in the background and I was unable to start the program again.
I have tried several different functions to close the program, but nothing has worked. Here are some of my attempts:
def Cerrar():
summary.destroy()
No = customtkinter.CTkButton(summary, text="Cerrar", command=Cerrar,width=10)
or
No = customtkinter.CTkButton(summary, text="Cerrar", command=lambda:Cerrar(),width=10)
or
No = customtkinter.CTkButton(summary, text="Cerrar", command=lambda:summary.destroy(),width=10)
here is the window im having a problem with:
def Analisis():
global resumen,cuantia,summary,refuerzo
Denom_Malla = "{}-{}".format(Malla.get(),Separacion.get())
denominacion_mallas = ["4-25","4-20","4-15","4.5-15","5-15","5.5-15",
"6-15","6.5-15","7-15","7.5-15","8-15","8.5-15",
"4-12.5","4-10","4-7.5","4.5-7.5","5-7.5","5.5-7.5",
"6-7.5","6.5-7.5","7-7.5","7.5-7.5","8-7.5","8.5-7.5"]
if Denom_Malla in denominacion_mallas:
fc = int(Fc.get())
fy_malla = int(Fy_Malla.get())
fy_barra = int(Fy_Barra.get())
mu = float(Mu.get())
H = float(h.get())
Rec = float(rec.get())
malla = Malla.get()
separacion = Separacion.get()
denom_barra = int(Denom_Barra.get())
resumen, cuantia_calculada, d, Rn, cuantia_min, cuantia_diseño, As,Sep_Barra = Calculo_Losa(fc, fy_malla, fy_barra, mu, H, Rec, malla, separacion, denom_barra)
root.destroy()
if resumen == None:
root_losas(lista_fc.index(str(fc)),lista_fy.index(str(fy_malla)),lista_fy.index(str(fy_barra)),lista_mallas.index(malla),lista_denombarra.index(str(denom_barra)),mu,H,Rec,lista_separacion.index(str(separacion)))
else:
summary = customtkinter.CTk()
summary.title("Resumen")
summary.minsize(width=300,height=150)
customtkinter.CTkLabel(summary, text="Momento Último calculado es de: {} KN-m".format(mu)).grid(row=0,column=0,columnspan=2)
customtkinter.CTkLabel(summary, text="La cuantía calculada es de: {}".format(round(cuantia_diseño,4))).grid(row=1,column=0,columnspan=2)
customtkinter.CTkLabel(summary, text="Para la losa se necesita una malla {}".format(resumen)).grid(row=2,column=0,columnspan=2)
customtkinter.CTkLabel(summary, text="Desea realizar otro análisis?").grid(row=3,column=0,columnspan=2)
customtkinter.CTkLabel(summary, text="En que tipo de refuerzo desea guardar: ").grid(row=2,column=3)
refuerzo = customtkinter.StringVar(value=lista_refuerzo[0])
refuerzo_Box = customtkinter.CTkOptionMenu(summary, variable=refuerzo, values=lista_refuerzo, width=100)
refuerzo_Box.grid(row=3,column=3,padx=15)
refuerzo_Box.configure(cursor="hand2")
Yes = customtkinter.CTkButton(summary, text="Analizar", command=lambda:Siguiente(fc,fy_malla,fy_barra,malla,denom_barra,mu,H,Rec,separacion),width=10)
Yes.grid(row=4,column=0)
Yes.configure(cursor="hand2")
Guardar = customtkinter.CTkButton(summary, text="Guardar", command=lambda:Save(fc,fy_malla,mu,1,H,Rec,d,Rn,cuantia_calculada,cuantia_min,cuantia_diseño,As,malla,separacion,denom_barra,Sep_Barra,resumen))
Guardar.grid(row=4,column=3,pady=15)
Guardar.configure(cursor="hand2")
No = customtkinter.CTkButton(summary, text="Cerrar", command=Cerrar,width=10)
No.grid(row=4,column=1)
No.configure(cursor="hand2")
summary.mainloop()
else:
tk.messagebox.showerror(title="Error Malla", message="La denominacion de la malla elegida no está registrada.")
`

Unable to complete operation on element with key none

I'm practicing with an algorithm that generates a random number that the user needs, then keeps trying until it hits. But PySimpleGUI produces an error saying: Unable to complete operation on element with key None.
import randomimport PySimpleGUI as sg
class ChuteONumero:
def init(self):
self.valor_aleatorio = 0
self.valor_minimo = 1
self.valor_maximo = 100
self.tentar_novamente = True
def Iniciar(self):
# Layout
layout = [
[sg.Text('Seu chute', size=(39, 0))],
[sg.Input(size=(18, 0), key='ValorChute')],
[sg.Button('Chutar!')],
[sg.Output(size=(39, 10))]
]
# Criar uma janela
self.janela = sg.Window('Chute o numero!', Layout=layout)
self.GerarNumeroAleatorio()
try:
while True:
# Receber valores
self.evento, self.valores = self.janela.Read()
# Fazer alguma coisa com os vaalores
if self.evento == 'Chutar!':
self.valor_do_chute = self.valores['ValorChute']
while self.tentar_novamente == True:
if int(self.valor_do_chute) > self.valor_aleatorio:
print('Chute um valor mais baixo')
break
elif int(self.valor_do_chute) < self.valor_aleatorio:
print('Chute um valor mais alto!')
break
if int(self.valor_do_chute) == self.valor_aleatorio:
self.tentar_novamente = False
print('Parabéns, você acertou!')
break
except:
print('Não foi compreendido, apenas digite numeros de 1 a 100')
self.Iniciar()
def GerarNumeroAleatorio(self):
self.valor_aleatorio = random.randint(
self.valor_minimo, self.valor_maximo)
chute = ChuteONumero()
chute.Iniciar()
I expected a layout to open, but it does not open.
Revised your code ...
import random
import PySimpleGUI as sg
class ChuteONumero:
def __init__(self):
self.valor_aleatorio = 0
self.valor_minimo = 1
self.valor_maximo = 100
self.tentar_novamente = True
def Iniciar(self):
# Layout
layout = [
[sg.Text('Your kick', size=(39, 0))],
[sg.Input(size=(18, 0), key='ValorChute')],
[sg.Button('Kick!')],
[sg.Output(size=(39, 10))]
]
# Create a window
self.janela = sg.Window('Guess The Number!', layout)
self.GerarNumeroAleatorio()
while True:
# Receive amounts
evento, valores = self.janela.read()
if evento == sg.WIN_CLOSED:
break
# Do something with the values
elif evento == 'Kick!':
try:
valor_do_chute = int(valores['ValorChute'])
except ValueError:
print('Not understood, just type numbers from 1 to 100')
continue
if valor_do_chute > self.valor_aleatorio:
print('Guess a lower value')
elif valor_do_chute < self.valor_aleatorio:
print('Kick a higher value!')
if valor_do_chute == self.valor_aleatorio:
sg.popup_ok('Congratulations, you got it right!')
break
self.janela.close()
def GerarNumeroAleatorio(self):
self.valor_aleatorio = random.randint(self.valor_minimo, self.valor_maximo)
chute = ChuteONumero()
chute.Iniciar()

How to send and receive messages between processes in Python (through channels)?

I am trying to implement a simple program in which there are several processes that concurrently communicate with each other by sending and receiving messages. In the program, there are 4 participants (each of which corresponds to a process) and communicate with each other as follows:
P1 sends P2 some_message then P2 sends P3 another_message then P3 sends P4 a_message. Based on the messages each participant receives, they perform a specific action.
Obviously, when, for instance, P1 sends P2 a message, P2 is receiving that message from P1, so they are paired.
I have found different approaches none of which are suitable as they seem to be complicated for I am looking for. For example,
Python MPI which has a restriction of "There are not enough slots available in the system". There are a few ways suggested to sort out the issue but the solutions are a bit complicated.
Socket programming which mostly suits server and client scenario. But my program doesn't have a server. I also checked this answer, which is again based on socket programming.
My question is that isn't there any simpler approach than the above ones so that I can implement what I explained? Is it possible to create communication channels in Python fairly similar to the ones in Golang?
This code I wrote a while ago to get to grips with os.pipe - it is self contained but not "minimally reproducible" since I don't have the time to redo it. It uses tkinter Uis to simulate processes and sends and receives data between them. Note that the code was written only for my private purpose.
"""Test run of the use of pipes between processes.
.. processes are control, startup , send and receive.
.. pipes from control to startup and send
.. pipe from startup to send
.. pipe from send to receive
.. startup, user input of run mode
... prompt, timer (seconds) or number of runs
.. send, user input of data
.. receive, display of data received
. each process operates independently of, and in isolation from, the other processes until data is transferred through pipes
"""
# fr read file descriptor
# fw write file descriptor
# wbs write bytes
# snb string length of output filled with 0 to write as header
# bsnb for number of bytes written, needed for read
# maxbuf number of bytes of header, 4 digits, max 9999 characters in a string/byte literal
# onb output number of bytes
# dbs data read in bytes
import tkinter as tk
from os import pipe as ospipe
from os import read as osread
from os import write as oswrite
from os import close as osclose
from datetime import datetime as dt
from time import monotonic as clock
from functools import partial
BG = '#fa4'
TBG = '#fe8'
SndBG = '#f91'
BLK = '#000'
STOP = '#d30'
START = '#0b0'
start = clock()
def timer(halt):
tm = int(clock())
if int(tm - start) > halt:
return True
else: return False
def piperead(r):
maxbuf = 4
onb = osread(r,maxbuf)
oi = int(onb.decode())
dbs = osread(r,oi).decode() # bytes to string
osclose(r)
return dbs
def pipewrite(w,s):
wbs = bytes(s, encoding='utf-8')
snb = str(len(s)).zfill(4)
bsnb = bytes(snb, encoding='utf-8')
wbs = bsnb + wbs
oswrite(w,wbs)
osclose(w)
def setpipe(process, sub=None, vars=None):
fdr, fdw = ospipe()
if sub: process(fdw,proc=(sub,vars))
else: process(fdw)
return piperead(fdr)
class Sloop():
def __init__(sl, pipewrite=None):
sl.fw = pipewrite
sl.w = tk.Tk()
sl.w.geometry('400x200-100+80')
sl.w.overrideredirect(1)
sl.w['bg'] = BG
uifnt = sl.w.tk.call('font', 'create', 'uifnt', '-family','Consolas', '-size',11)
sl.lvb = tk.Button(sl.w, bg=BLK, activebackground=BG, relief='flat', command=sl.stop)
sl.lvb.pack()
sl.lvb.place(width=15,height=15, x=380,y=10)
sl.sndb = tk.Button(sl.w,bg=SndBG,activebackground=BG,fg=TBG, text=chr(11166), command=sl.send)
sl.sndb.pack()
sl.sndb.place(width=25,height=25, x=20,y=160)
sl.tlbl = tk.Label(sl.w,bg=BG, text='write data to send...')
sl.tlbl.pack()
sl.tlbl.place(x=20,y=20)
sl.t = tk.Text(sl.w,bg=TBG)
sl.t.pack()
sl.t.place(width=300,height=100, x=20,y=45)
sl.t.focus_set()
sl.w.mainloop()
def send(sl):
sl.output = sl.t.get('1.0','end')
if sl.output != '\n':
pipewrite(sl.fw,sl.output)
sl.close()
else:
sl.error()
def error(sl):
def _clearlbl(ev):
sl.erlbl.destroy()
sl.erlbl = tk.Label(sl.w,bg=TBG,text='there is nothing to send')
sl.erlbl.pack()
sl.erlbl.place(x=20,y=160)
sl.t.focus_set()
sl.t.bind('<KeyPress>',_clearlbl)
def stop(sl):
pipewrite(sl.fw,'stop')
sl.close()
def close(sl):
sl.w.destroy()
class Rloop():
def __init__(rl, pipefread=None):
rl.fr = pipefread
rl.w = tk.Tk()
rl.w.geometry('400x200-100+320')
rl.w.overrideredirect(1)
rl.w['bg'] = BG
uifnt = rl.w.tk.call('font', 'create', 'uifnt', '-family','Consolas', '-size',10)
rl.lvb = tk.Button(rl.w, bg=BLK, activebackground=BG, relief='flat', command=rl.close)
rl.lvb.pack()
rl.lvb.place(width=15,height=15, x=380,y=10)
rl.tlbl = tk.Label(rl.w,bg=BG, text='received...')
rl.tlbl.pack()
rl.tlbl.place(x=20,y=20)
rl.t = tk.Text(rl.w,bg=TBG)
rl.t['font'] = uifnt
rl.t.pack()
rl.t.place(width=300,height=100, x=20,y=45)
rl.t.focus_set()
rl.receive()
rl.w.mainloop()
def receive(rl):
rec = piperead(rl.fr)
if rec != 'stop':
rl.t.insert('end', '\n'.join([str(dt.now()), rec]))
else: rl.close()
def close(rl):
rl.w.destroy()
class Startup():
def __init__(su, pipefwrite=None):
su.fw = pipefwrite
su.mode = ''
su.w = tk.Tk()
su.w.geometry('400x200-100+500')
su.w.overrideredirect(1)
su.w['bg'] = BG
uifnt = su.w.tk.call('font', 'create', 'uifnt', '-family','Consolas', '-size',11)
su.lvb = tk.Button(su.w, bg=BLK, activebackground=BG, relief='flat', command=su.stop)
su.lvb.pack()
su.lvb.place(width=15,height=15, x=380,y=10)
su.sndb = tk.Button(su.w,bg=SndBG,activebackground=BG,fg=TBG, text=chr(11166), command=su.send)
su.sndb.pack()
su.sndb.place(width=25,height=25, x=20,y=160)
su.title = tk.Label(su.w,bg=BG, text='Modes to continue data input')
su.title.pack()
su.titley = 10
su.title.place(x=20,y=su.titley)
su.ysp = 20
su.margin = 200
ptxt = 'prompt'
su.pb = tk.Button(su.w,bg=BG, activebackground=BG, text=ptxt, relief='flat', cursor='hand2', command=partial(su._get,e=None, nm='su.pb', ent=None))
tmtxt = ' timer '
su.tmb = tk.Button(su.w,bg=BG, activebackground=BG, text=tmtxt, relief='flat', cursor='hand2', command=partial(su._enter,ent='su.tmb'))
rntxt = ' runs '
su.rnb = tk.Button(su.w,bg=BG, activebackground=BG, text=rntxt, relief='flat', cursor='hand2', command=partial(su._enter,ent='su.rnb'))
su.pb.pack()
su.pby = su.titley + 1.5*su.ysp
su.pb.place(x=25,y=su.pby)
su.tmb.pack()
su.tmby = su.pby + 2*su.ysp
su.tmb.place(x=25,y=su.tmby)
su.rnb.pack()
su.rnby = su.pby + 4*su.ysp
su.rnb.place(x=25,y=su.rnby)
su.formd = {'su.pb':su.pb, 'su.tmb':su.tmb, 'su.rnb':su.rnb}
su.w.mainloop()
def _able(su,nm):
for key in su.formd:
if nm[0:4] not in key:
su.formd[key]['state'] = 'disabled'
else:
su.formd[key]['state'] = 'normal'
def _enter(su,ent):
if ent == 'su.tmb':
tmtxt = 'seconds'
su.tmlbl = tk.Label(su.w,bg=BG, text=tmtxt)
su.tment = tk.Entry(su.w,bg=TBG)
su.tmlbl.pack()
su.tment.pack()
tmlbly = su.tmby
su.tmlbl.place(x=su._margin(tmtxt), y=tmlbly)
su.tment.place(x=su.margin, y=tmlbly)
su.tment.focus_set()
su.tment.bind('<Return>', partial(su._get,nm='su.tment', ent=su.tment))
su.formd = su.formd | {'su.tmlbl':su.tmlbl, 'su.tment':su.tment}
elif ent == 'su.rnb':
rntxt = 'number'
su.rnlbl = tk.Label(su.w,bg=BG, text=rntxt)
su.rnent = tk.Entry(su.w,bg=TBG)
su.rnlbl.pack()
su.rnent.pack()
rnlbly = su.rnby
su.rnlbl.place(x=su._margin(rntxt), y=rnlbly)
su.rnent.place(x=su.margin, y=rnlbly)
su.rnent.focus_set()
su.rnent.bind('<Return>', partial(su._get,nm='su.rnent', ent=su.rnent))
su.formd = su.formd | {'su.rnlbl':su.rnlbl, 'su.rnent':su.rnent}
def _get(su,e,nm,ent):
if nm == 'su.pb':
su._able('su.pb')
su.mode = 'prompt,'+'1'
else:
su._able(nm)
for key in su.formd:
if key == nm:
if 'tm' in key: modestr = 'timer'
elif 'rn' in key: modestr = 'runs'
su.formd[key]['bg']=BG
su.mode = ','.join([modestr,str(ent.get())])
break
def _margin(su,txt):
return su.margin-(len(txt)*8)
def send(su):
pipewrite(su.fw,su.mode)
su.close()
def stop(su):
pipewrite(su.fw,'stop')
su.close()
def close(su):
su.w.destroy()
class Control():
def __init__(c, pipefwrite=None, proc=None):
c.fw = pipefwrite
c.proc = proc
if c.proc:
c.proc = proc[0]
if proc[1]:
c.procv = proc[1]
else:
c.procvl = None
c.procd = {'start':c._strtui, 'prompt':c._prui, 'timer':c._tmui, 'runs':c._rnui}
c.w = tk.Tk()
c.w.geometry('100x200-60+80')
c.w.overrideredirect(1)
c.w['bg'] = BG
uifnt = c.w.tk.call('font', 'create', 'uifnt', '-family','Consolas', '-size',11)
c.lvb = tk.Button(c.w, bg=BLK, activebackground=BG, relief='flat', command=c.stop)
c.lvb.pack()
c.lvb.place(width=15,height=15, x=80,y=10)
c.title = tk.Label(c.w,bg=BG, text='pipe test\nControl')
c.title.pack()
c.title.place(x=5,y=5)
c.stpclr = tk.Label(c.w,bg=STOP)
c.stpclr.pack()
stpy = 160
c.stpclr.place(width=7,height=7,x=2,y=stpy+10)
c.stopb = tk.Button(c.w, bg=BG, text='stop', cursor='hand2', relief='flat', activebackground=BG, command=c.stop)
c.stopb.pack()
c.stopb.place(x=10,y=160)
c.procd[c.proc]()
c.w.mainloop()
def _strtui(c):
c.strtclr = tk.Label(c.w,bg=START)
c.strtclr.pack()
strty = 60
c.strtclr.place(width=7,height=7,x=2,y=strty+10)
c.startb = tk.Button(c.w, bg=BG, text='start', cursor='hand2', relief='flat', activebackground=BG, command=c.strtup)
c.startb.pack()
c.startb.place(x=10,y=strty)
def __write(c,s):
pipewrite(c.fw,s)
c.close()
def _prui(c):
prb = tk.Button(c.w,bg=TBG, text='--- next ---', activebackground=BG, relief='flat',cursor='hand2', command=partial(c.__write,'prompt'))
prb.pack()
prb.place(x=10,y=80)
def __confirm(c):
cb = tk.Button(c.w, bg=TBG, text='confirm', activebackground=BG, relief= 'flat', cursor='hand2', command=partial(c.__write,'confirm'))
cb.pack()
cb.place(x=20,y=120)
def _tmui(c):
tmt = ''.join(['run for\n',str(c.procv),' seconds'])
tmlbl = tk.Label(c.w,bg=BG, text=tmt)
tmlbl.pack()
tmlbl.place(x=10,y=80)
c.__confirm()
def _rnui(c):
rnt = ''.join(['run\n ',str(c.procv),' times'])
rnlbl = tk.Label(c.w,bg=BG, text=rnt)
rnlbl.pack()
rnlbl.place(x=10,y=80)
c.__confirm()
def strtup(c):
pipewrite(c.fw,'startup')
c.close()
def stop(c):
pipewrite(c.fw,'stop')
c.close()
def close(c):
c.w.destroy()
def once():
fr, fw = ospipe()
Sloop(fw)
Rloop(fr)
def many(mkey,mint=1):
"""modes are ('prompt',1), ('timer',secs), ('runs',runs)
"""
if mkey == 'timer':
rec = setpipe(Control,sub='timer',vars=mint)
if rec == 'confirm':
while not timer(mint):
once()
return True
elif rec == 'stop':
return False
elif mkey == 'runs':
rec = setpipe(Control,sub='runs',vars=mint)
if rec == 'confirm':
for r in range(mint):
once()
return True
elif rec == 'stop':
return False
elif mkey == 'prompt':
quit = False
while not quit:
once()
rec = setpipe(Control,sub='prompt')
if rec != 'prompt':
quit = True
return True
def testui():
incontrol = True
while incontrol:
rec = setpipe(Control,sub='start')
if rec == 'startup':
rec = setpipe(Startup)
if rec != 'stop':
modes, p, ns = rec.partition(',')
incontrol = many(modes,int(ns))
else:
incontrol = False
if __name__ == '__main__':
testui()

Automatic Rollbacks SQLALCHEMY

I am getting Rollbacks automatically.
Here is my code:
#socketio.on('update2')
def update_table_infocorp(trigger):
checknotprocess = Infocorp.query.filter(Infocorp.Procesado == False)
for row in checknotprocess:
getidentityuser = Usuarios.query.filter(Usuarios.id_user == row.id_user).first()
getidentityconsulta = Consolidado.query.filter(Consolidado.id_user == row.id_user and
(Consolidado.numdocumento == getidentityuser.numdocumento)).first()
if not getidentityconsulta:
# print("No se encontro la consulta relacionada al usuario.")
test = True
else:
sentinelresult = getsentinel(getidentityuser.tipodocumento, getidentityuser.numdocumento, row.id_consulta,
getidentityconsulta.solicitudes_id)
print(getidentityconsulta.solicitudes_id)
print(getidentityuser.tipodocumento)
if sentinelresult == True:
continue
else:
print("Ocurrio un error")
resultadoquery = Infocorp.query.filter(Infocorp.Procesado == True)
datatransform = InfocorpSchema(many=True)
datatransformresult = datatransform.dump(resultadoquery)
emit('nuevatableinfocorp', datatransformresult, broadcast=True)
And those are my logs:
I hope you will be able to help me because it is affecting other systems that use the same database.

Kivy reload Buttons(via function)on app startup

Hi i'm pretty new with python and kivy , im trying to do a simple "to do" app.. My code looks horrible, i know, and im sorry for that..
I have a table in sqlite3 with some information stored in it. I would like to call a function that query this table on app start up. I can't figure out how to make it work.. Here is my code
Python:
import sqlite3
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.togglebutton import ToggleButton
from kivy.clock import Clock
from kivy.uix.floatlayout import FloatLayout
from functools import partial
class GetLinksButton(Button):
def get_caption(self):
# DEFINIZIONE CHE SI POTREBBE FARE IN KV .. CREAZIONE POPUP CON 2 BOTTONI E TEXTINPUT
content = BoxLayout(orientation='vertical')
txt = TextInput(text = "",focus=False,multiline=False,size_hint=(1,0.2),font_size= 40)
content.add_widget(txt)
mybutton = Button(text='Add',size_hint=(1,0.2),font_size=20)
mybutton2 = Button(text='Close',size_hint=(1,0.2),font_size=20)
content.add_widget(mybutton)
content.add_widget(mybutton2)
mypopup = Popup(title = 'Add item to list',
content = content,
size_hint = (1, 0.4),
auto_dismiss = False,
).open()
def saveTxt(tt):
mypopup.dismiss() # FUNZIONE CHIAMATA, CHIUSURA POPUP
try:
self.set_caption(txt.text) # CHIAMA FUNZIONE DI CREAZIONE BOTTONE CON ARG IL CAPTURE DEL TESTO IN TEXTBOX
except:
pass
mybutton.bind(on_press = saveTxt) # CHIAMA FUNZIONE DI CAPTURE DEL TESTO E CHIUSURA POPUP
txt.bind(on_text_validate = saveTxt)# CHIAMA FUNZIONE DI CAPTURE DEL TESTO E CHIUSURA POPUP
mybutton2.bind(on_press = mypopup.dismiss)
# FUNZIONE CHIAMATA PER INSERIMENTO NUOVO BOTTONE IN TABELLA LOCALTB
def btn_db(self,st):
#con = None
elementList =[]
print "stringa dentro a dtn_db "+ st
try:
con = sqlite3.connect('localdb.db')
cur = con.cursor()
cur.execute("insert into localtb (Item, State) values ( ?, ?)",(st, 0))
con.commit()
cur.execute("select * from localtb")
data = cur.fetchall()
con.close()
for x in data:
print x
elementList.append(x[0])
except:
print "non va"
w = str(elementList)
return w
# CREAZIONE BOTTONE DA INPUTO DI TESTO , TEXT BUTTON == INPUT INSERITO IN BOX
def set_caption(self,stringa):
string = stringa[0].upper()+stringa[1:].lower()
print string, " stringa prima del for"
# DA SISTEMARE CICLO "INUTILE"
#for i in range(1):
link_button = LinkButton(
text = string)
print "tra for e add_widget"
self.links_grid.add_widget(link_button)
print string," strinda PRIMA call a btn_db"
self.btn_db(string) # CALL A FUNZIONE PER INSERIRE IL BOTTONE IN TABELLA LOCALE (LOCALTB)
print string," strinda DOPO call a btn_db"
class LinkButton(ToggleButton):
# GESTIONE DEL TOGGLE.. QUNANDO SI TOGGLA IL BOTTONE PARTE LA QUERY E INVERTE LO STATO ATTUALE CON L'ALTRO STATO , DA 0 A 1 E VICEVERSA PER IL BOTTONE PREMUTO
def toggleState(self):
#con = None
red = (83,0,0,1)
green = (0,83,0,1)
print self.background_color
if self.background_color == [83,0,0,1]:
self.background_color = green
else:
print "dentro ELSE"
self.background_color = red
elementList =[]
pressed = str(self.text)
print "tasto premuto cambio stato: "+pressed
try:
con = sqlite3.connect('localdb.db')
cur = con.cursor()
cur.execute("update localtb set State = (CASE WHEN State = 0 THEN State + 1 WHEN State = 1 THEN State - 1 end ) WHERE Item = ?",(pressed,)) # ATTENTO ALLA VIRGOLA DOPO PRESSED(SE NON NON FUNZIONA)
con.commit()
cur.execute("select * from localtb")
data = cur.fetchall()
con.close()
for x in data:
print x
elementList.append(x[0])
except:
print "non va"
w = str(elementList)
return w
class SmsButton(Button):
# PROVE DI RELOAD SESSIONE PRECENDETE- FALLITE.
def reloadSession(self):
try:
con = sqlite3.connect('localdb.db')
cur = con.cursor()
cur.execute("select * from localtb")
data = cur.fetchall()
con.close()
for x in data:
reload_Element = str(x[0])
if x[1] == 0:
print "in if: ", x[1]
link_button = LinkButton(text = reload_Element,background_color = [83,0,0,1])
else:
print "in else: ", x[1]
link_button = LinkButton(text = reload_Element,background_color = [0,83,0,1])
self.links_grid.add_widget(link_button)
except Exception as inst:
print inst.args
print "non va"
class Test(App):
pass
if __name__ == '__main__':
Test().run()
KV:
#:kivy 1.9.1
MyRootasdasd:
rows: 1
RightArea:
<MyRootasdasd#GridLayout>:
#rows: 1
#RightArea:
<RightArea#GridLayout>:
cols: 1
size_hint_x: 0.3
spacing: '1dp'
ScrollView:
LinksGrid:
id: links_grid
BoxLayout:
size_hint: (1,0.08)
GetLinksButton:
links_grid: links_grid
SmsButton:
links_grid: links_grid
<LinksGrid#GridLayout>:
cols: 2
spacing: '.5dp'
size_hint_y: None
height: self.minimum_height
<SmsButton>:
size_hint_y: 1
text: 'SMS'
on_press: self.reloadSession()
<GetLinksButton>:
size_hint_y: 1
text: 'Get links'
on_press: self.get_caption()
<LinkButton>:
color: (0, 0, 0, 1) #COLORE TESTO
background_normal: '' # RESET DELLA TINTA (STRINGA, quindi carica un immagine non un colore)
background_color: (83, 0, 0, 1) #COLORE SFONDO -> qui sotto la call alla classe che gestisce il toggle del bottone
on_release: self.toggleState()
size_hint_y: None
height: '80dp'
some pieces of code are unused don't worry about it.
Function i need to call is reloadSession that query table and then with the information retrieved create n buttons...
As you can see, in the SmsButton class(in KV) call that function(ON_PRESS), i need to do the same thing but automatically on app start up... How can i do that??
Sorry for my bad english and coding.. Im new, im trying a lot of stuff, i would appreciate your help.
Thank you.
Yvan.
EDIT: removed unused code
EDIT : #bj0
thanks for the tips.. i've tryied to use build function in alla the way i know. but it doesnt work ...i get this error
("'Test' object has no attribute 'links_grid'",)
the code im using now is this..
class Test(App):
def build(self):
try:
con = sqlite3.connect('localdb.db')
cur = con.cursor()
cur.execute("select * from localtb")
data = cur.fetchall()
con.close()
for x in data:
reload_Element = str(x[0])
if x[1] == 0:
print "in if: ", x[1]
link_button = LinkButton(text = reload_Element,background_color = [83,0,0,1])
else:
print "in else: ", x[1]
link_button = LinkButton(text = reload_Element,background_color = [0,83,0,1])
self.links_grid.add_widget(link_button)
except Exception as inst:
print inst.args
print "non va"
obviously Test class has no links_grid attribute.. but how can i solve this problem ?
Thanks again

Categories

Resources