Proyecto

General

Perfil

« Anterior | Siguiente » 

Revisión 276

Programa funcional en pruebas

Ver diferencias:

profEnAula/profEnAula.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx
import ldap
import unicodedata
from xml.etree import ElementTree
import time
import sys,os
#import horarioXml11
listProfesores = []
uidNombre = {}
class buscaProf(wx.Frame):
def __init__(self, *args, **kwds):
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.sizer_1_staticbox = wx.StaticBox(self, -1, "Profesor")
#self.aproxList = wx.TextCtrl(self,style = wx.TE_PROCESS_ENTER)
self.profesores = wx.ListBox(self, -1, choices=[], style=wx.LB_SORT)
self.btBuscar = wx.Button(self, -1, "Refrescar")
self.resultado = wx.StaticText(self, -1, "")
self.btSalir = wx.Button(self, -1, "Salir")
#self.profAula()
self.rellenaProf()
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_LISTBOX, self.buscaAula, self.profesores)
self.Bind(wx.EVT_BUTTON, self.salir, self.btSalir)
#self.Bind(wx.EVT_TEXT, self.desplazaLista, self.aproxList)
ahora = time.localtime()
dia = self.diaSemana(ahora[6])
minutos = int(ahora[3]*60+ahora[4])
self.Bind(wx.EVT_BUTTON, self.profAula(minutos,dia), self.btBuscar)
self.rellenaProf()
#self.profAula(minutos,dia)
def __set_properties(self):
self.SetTitle("Busca Profesor en aulas")
self.SetPosition([1500,0])
#self.aproxList.SetToolTipString("Introduzca la inicial del nombre")
def __do_layout(self):
sizer_1 = wx.StaticBoxSizer(self.sizer_1_staticbox, wx.VERTICAL)
grid_sizer_1 = wx.GridSizer(1, 2, 0, 0)
#sizer_1.Add(self.aproxList,0,wx.ADJUST_MINSIZE, 0)
sizer_1.Add(self.profesores, 5, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 0)
grid_sizer_1.Add(self.btBuscar, 0, wx.ALIGN_BOTTOM, 0)
grid_sizer_1.Add(self.resultado, 0, wx.ALIGN_BOTTOM, 0)
grid_sizer_1.Add(self.btSalir, 0, wx.ALIGN_BOTTOM, 0)
sizer_1.Add(grid_sizer_1, 1, wx.ADJUST_MINSIZE, 0)
self.SetSizer(sizer_1)
self.Layout()
self.SetSize((258, 1322))
def salir(self,evento=None):
self.Close(True)
#Tecla en TxtCtrl selecciona prof de lista
def desplazaLista(self,event):
for i in self.listProfesores:
if i[0] == self.aproxList.GetValue()[0]:
print 'desplazaLista'
self.profesores.SetStringSelection(i)
self.aproxList.SetValue(i)
break
def elCurso(self, minutos, dia):
prof = self.profesores.GetStringSelection().encode('utf-8')
dia = raiz.find(dia + '.txt')
for i in dia:
if i.attrib['nif'] == uidNombre[prof]:
profesor = i.getchildren()
#buscar la hora
for j in profesor:
inicio = j.get('inicio')
fin = j.get('fin')
if int(inicio) <= minutos <= int(fin):
curso = j.getchildren()
for h in curso:#curso son los alumnos co su nie
#para evitar problema con alumnos que no existen
try:
nieAlumno = self.consulta('nie', h.get('nie'))[0]
except:
nieAlumno = [];continue
#print nieAlumno;print 'antes nif'
if nieAlumno:
print 'sin error'
self.cursoAlumno(nieAlumno)
return 1
else:
print 'error'
#Averiguar curso de un alumno dado, busca curso por curso
def cursoAlumno(self,nif):
#COMPROBAR SI SOBRA AQUI Y QUITARLA allcurso = []
for i in self.consulta('cursos',''):
allcurso = []
allcurso.append(self.consulta('alumnocurso',i))
for j in allcurso[0][0]: #LDAP empieza con un usuario vacio, no lo procesamos
if j != '' and j == nif:
self.resultado.SetLabel('Curso: '+i)
#encontrado = True
return j
break
def buscaAula(self, event):
self.resultado.SetLabel('Buscando')
ahora = time.localtime()
dia = self.diaSemana(ahora[6])
minutos = int(ahora[3]*60+ahora[4])
self.elCurso(minutos,dia)
event.Skip()
#Rellenar lista profesores en aula
def profAula(self, minutos, dia):
#self.rellenaProf()
self.profesores.Clear()
nombres1 = []
dia = raiz.find(dia+'.txt')
for i in dia:
profesor = i.getchildren()
#buscar la hora
for j in profesor:
inicio = j.get('inicio')
fin = j.get('fin')
if int(inicio) <= minutos <= int(fin):
for h in uidNombre:
if uidNombre[h] == i.attrib['nif']:
nombres1.append(h)
self.profesores.InsertItems(nombres1,0)
def rellenaProf(self):
allTeacher = []
curso = []
nombres = []
allTeacher.append(self.consulta('profesores',''))
for i in allTeacher[0][0]:
nombre = self.consulta('nombre',i)[0]
nombres.append(nombre)
dni = self.consulta('nif',i)
if dni != []:
if len(dni[0]) == 9:
uidNombre[nombre] = dni[0]#self.consulta('nif',i)[0]
else:
aux=dni[0]
for i in range(9-len(dni[0])):
aux= '0' + aux
uidNombre[nombre] = aux
#self.profesores.InsertItems(nombres,0)
self.listProfesores = nombres
#print self.listProfesores
#Consultas a ldap
def consulta(self,datoResultado,datoUsuario):
datosConsulta = []
# NO SIRVE ? BORRAR cursos = []
tipo = datoResultado
usuarioCurso = datoUsuario
searchScope = ldap.SCOPE_SUBTREE
#opcion de ricardo para ldaps
try:
l = ldap.open("ldap")
username = "cn=admin,ou=People,dc=instituto,dc=extremadura,dc=es"
password = "20-tietar-09"
l.simple_bind(username,password)
except ldap.LDAPError, e:
print e
return "ERRORLDAP"
if tipo == 'cursos':
#cursos
base_dn = 'ou=Group,dc=instituto,dc=extremadura,dc=es'
searchFilter = '(&(objectClass=posixGroup)(groupType=school_class))'
retrieveAttributes = ['cn']
elif tipo == 'alumnocurso':
base_dn= 'ou=Group,dc=instituto,dc=extremadura,dc=es'
searchFilter = '(&(&(objectClass=posixGroup)(groupType=school_class))(cn=' + usuarioCurso + '))'
retrieveAttributes = ['memberUid'] #Extraer miembros
elif tipo == 'profesores':
base_dn = 'ou=Group,dc=instituto,dc=extremadura,dc=es '
searchFilter = "(&(objectClass=posixGroup)(cn=teachers))"
retrieveAttributes = ['memberUid']
elif tipo == 'nombre':#Nombre de usuario
base_dn= 'ou=People,dc=instituto,dc=extremadura,dc=es'
searchFilter = '(uid=' + usuarioCurso +')'
retrieveAttributes = ['cn']
elif tipo == 'nif':
base_dn= 'ou=People,dc=instituto,dc=extremadura,dc=es'
searchFilter = '(uid=' + usuarioCurso +')'
retrieveAttributes = ['employeeNumber']
elif tipo == 'nie':
base_dn= 'ou=People,dc=instituto,dc=extremadura,dc=es'
searchFilter = '(employeeNumber=' + usuarioCurso +')'
retrieveAttributes = ['uid']
else :
pass
try:
ldap_result_id = l.search(base_dn, searchScope, searchFilter, retrieveAttributes)
result_type, result_data = l.result(ldap_result_id)
if tipo == 'cursos':
for i in result_data:
datosConsulta.append(i[1]['cn'][0])
elif tipo == 'alumnocurso' or tipo == 'profesores' :
datosConsulta.append(result_data[0][1]['memberUid'])
elif tipo == 'nombre':
datosConsulta.append(result_data[0][1]['cn'][0])
elif tipo == 'nif':
if result_data[0][1] != {}:
datosConsulta.append(result_data[0][1]['employeeNumber'][0])
elif tipo == 'nie':
if result_data[0][1] != {}:
datosConsulta.append(result_data[0][1]['uid'][0])
else :
pass
except ldap.LDAPError, e:
print e
print "ERRORLDAP"
return datosConsulta
def diaSemana(self,dia):
dias = ['Lunes','Martes','Miercoles','Jueves','Viernes']
return dias[dia]
if __name__ == "__main__":
rDir = os.path.split(sys.argv[0])[0]
arbolxml = ElementTree.parse(rDir+'/horarios.xml')
raiz = arbolxml.getroot()
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = buscaProf(None, -1, "")
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()
profEnAula/Leeme
profEnAula
Muestra una lista con los profesores que están actualmente en clase,
al seleccionar cualquiera de ellos nos dice en que aula está. Requiere
fichero horarios.xml generado por importHorarios.
importHorarios
Extrae los horarios desde los ficheros importados desde rayuela y
los convierte en un xml. Esto es necesario ejecutarlo cada vez que
cambien los horarios. Para su funcionamiento requiere una carpeta
llamada datos colocada donde se ejecute el importHorarios, dentro
estarán los ficheros importados desde rayuela con nombres en minusculas
excepto la 1ª letra en Mayusculas.
profEnAula/importHorarios.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# horarioXml.py
#
# Copyright 2011 Juan Antonio Cristín<programador@informatico>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
from xml.etree import ElementTree
from xml.dom.minidom import parse
import sys,os,time,errno,re
#De linea rayuela crea diccionario
def extraeDatosLineaRayuela(linea,dia):
datos = linea.split("|")
return { "dni_profesor" : datos[0], "nie_alumno" : datos[1], "inicio" : int(datos[2]), "final" : int(datos[3]), "dia": dia}
def transformaArchivos(datosrayuela):
#comprobar que existe dir y q contiene los ficheros y limpiar linea de los for
if os.path.isdir(datosrayuela):
try:
archivosRayuela = os.listdir(datosrayuela)
except:
return 3
print datosrayuela
#Limpiemos las listas de archivos
archivosRayuela = [ archivo for archivo in archivosRayuela if archivo in ["Lunes.txt","Martes.txt","Miercoles.txt","Jueves.txt","Viernes.txt"]]
listaLineas = []
#Procesemos cada archivo de Rayuela
for archivoRayuela in archivosRayuela:
filearchivoRayuela = open(os.path.join(datosrayuela,archivoRayuela), 'r')
while True:
linea = filearchivoRayuela.readline()
if not linea:
break
if linea[:6] == "D.N.I.":
continue
datosLineaRayuela = extraeDatosLineaRayuela(linea,archivoRayuela)
listaLineas.append(datosLineaRayuela)
filearchivoRayuela.close()
return listaLineas
#Parametro indice 6 de tupla resultado de: time.localtime()
def diaSemana(dia):
dias = ['Lunes','Martes','Miercoles','Jueves','Viernes']
return dias[dia]
def main():
dias = []
ahora = time.localtime()
minutoActual = int(ahora[3]*60+ahora[4])
diadeSemana = diaSemana(ahora[6])
arbolxml = ElementTree.parse('horarios.xml')
raiz = arbolxml.getroot()
lineas = transformaArchivos("/media/juancristin/xml/datos")
for i in lineas:
#cada dia un fichero
diaProcesado = i['dia']
# = i['dni_profesor']
nif = i['dni_profesor'][0:9]
inicio = i['inicio']
final = i['final']
niealumno = i['nie_alumno']
inicioFinal = [str(inicio),str(final)]
#nuevo (nodo) fichero de dia
if not diaProcesado in dias:
dia = ElementTree.SubElement(raiz,diaProcesado)
dias.append(diaProcesado)
profesores = []
#nuevo nodo profesor para un dia
if not nif in profesores:
profesores.append(nif)
profesor = ElementTree.SubElement(dia,'profesor',{'nif':nif})
horas = []
#nuevo nodo hora
if not inicioFinal in horas:
alumnos = []
horas.append(inicioFinal)
#comprobar en el nodo si es el 1º hijo
hora = ElementTree.SubElement(profesor,'hora',{'inicio':str(inicio),'fin':str(final)})
#nuevo nodo alumno
if not niealumno in alumnos:
addAlum = ElementTree.SubElement(hora,'alumno')
addAlum.set('nie',niealumno[0:7])
alumnos.append(niealumno)
arbolxml.write('horarios.xml', encoding='UTF-8')
return 0
if __name__ == '__main__': main()

Exportar a: Unified diff