def GuardarEvento(Info):
    titulo, gratuito, precio, larga_duracion, fecha, fecha_final, hora, url = Info
    # Inicializo el error a 0
    error = 0
    # Convierto cada parámetro al formato necesario
    try:
        gratuito = int(gratuito)
    except ValueError:
        gratuito = 0
    try:
        precio = int(precio)
    except ValueError:
        precio = 0
    fecha = datetime.strptime(fecha.split()[0] + " " + hora, '%Y-%m-%d %H:%M')
    fecha_final = datetime.strptime(fecha_final, '%Y-%m-%d %H:%M:%S.%f')
    duracion = str(fecha_final - fecha)
    try:
        larga_duracion = int(larga_duracion)
    except ValueError:
        larga_duracion = 0
    # Compruebo si dicha actividad ya está en la base de datos
    try:
        event = Actividad.objects.get(titulo=titulo)
    except Actividad.DoesNotExist:
        # Si no está, la guardo en la base de datos
        event = Actividad(titulo=titulo, gratuito=gratuito, precio=precio,
                        fecha=fecha, duracion=duracion, 
                        larga_duracion=larga_duracion, url_inf_adicional=url,
                        num_visitas=0)
        event.save()
    return error
def actividades(request):
    if request.method =="POST":
        nombre = request.POST.get('nombre')
        horario = request.POST.get('horario')
        actividad = Actividad(nombre=nombre, horario=horario)
        actividad.save()

    respuesta= "ACTIVIDADES"
    apuntados = Actividad.objects.all()
    respuesta += '<ul>'
    for apuntado in apuntados:
        respuesta += '<li><a href="' + str(apuntado.id) + '">' + apuntado.nombre + '</a>'
    respuesta += "</ul>"

    context = {'contenido': respuesta}
    return render(request, 'actividades.html', {'context': context})
def actividades(request):
    if request.method == "POST":
        nombre = request.POST.get('nombre')
        horario = request.POST.get('horario')
        actividad = Actividad(nombre=nombre, horario=horario)
        actividad.save()

    respuesta = "ACTIVIDADES"
    apuntados = Actividad.objects.all()
    respuesta += '<ul>'
    for apuntado in apuntados:
        respuesta += '<li><a href="' + str(
            apuntado.id) + '">' + apuntado.nombre + '</a>'
    respuesta += "</ul>"

    context = {'contenido': respuesta}
    return render(request, 'actividades.html', {'context': context})
Example #4
0
 def characters (self, content):
     if self.ID_EVENTO:
         self.Evento = Actividad(id_evento=content)
         self.ID_EVENTO = False
     elif self.TITULO:
         self.Evento.titulo = content
         self.TITULO = False
     elif self.GRATUITO:
         if content == "1":
             self.Evento.gratis = True
         self.GRATUITO = False
     elif self.FECHA_EVENTO:
         self.Evento.fecha = content[:9]
         self.FECHA_EVENTO = False
     elif self.HORA_EVENTO:
         self.Evento.hora = content
         self.HORA_EVENTO = False
     elif self.EVENTO_LARGA_DURACION:
         if content == "1":
             self.Evento.largo = True
         self.EVENTO_LARGA_DURACION = False
     elif self.CONTENT_URL:
         self.Evento.url = content.replace('#amp#', '&')
         self.CONTENT_URL = False
     elif self.TIPO:
         try:
             self.Evento.tipo_evento = content.split('/')[3]
         except IndexError:
             self.Evento.tipo_evento = "Sin categoría"
         self.TIPO = False
         # TIPO es el ultimo elemento que lee, guardamos
         # puede haber problema con la fecha, que debe ignorar
         # ese evento se descarta
         try:
             self.Evento.save()
         except ValidationError:
             pass
Example #5
0
def actualizar(request):
    #fichero = open('datos.txt','r')  
    #soup = fichero.read()
    #fichero.close()
    recurso  = "http://datos.madrid.es/portal/site/egob/menuitem.ac61933d6ee3c31"
    recurso += "cae77ae7784f1a5a0/?vgnextoid=00149033f2201410VgnVCM100000171f5a0"
    recurso += "aRCRD&format=xml&file=0&filename=206974-0-agenda-eventos-cultura"
    recurso += "les-100&mgmtid=6c0b6d01df986410VgnVCM2000000c205a0aRCRD"
    url = urllib2.urlopen(recurso)
    soup = url.read()
    soup = BeautifulSoup(soup)
    variable = soup.find_all('contenido') 
    for cont in variable:
        id_evento = cont.find(nombre="ID-EVENTO")
        id_evento = int(id_evento.string)
        print id_evento
        titulo = cont.find(nombre = "TITULO") 
        tipo = cont.find(nombre = "GRATUITO")
        if tipo.string == "1":
            tipo = "Gratis"
        elif tipo.string == "0":
            tipo = "No Gratis"
        else:
            tipo = "No INFO"
        fecha= cont.find(nombre="FECHA-EVENTO")
        hora = cont.find(nombre="HORA-EVENTO")		
        larga_duracion = cont.find(nombre="EVENTO-LARGA-DURACION")
        if larga_duracion == None:
            larga_duracion = "NO INFO" 
        elif larga_duracion.string == "1":
            larga_duracion = "SI"
        elif larga_duracion.string == "0":
            larga_duracion = "NO"
        url = cont.find(nombre="CONTENT-URL")
        fecha_fin = cont.find(nombre = "FECHA-FIN-EVENTO")
        fecha_ini = cont.find(nombre = "FECHA-EVENTO")
        hora = hora.string
        fecha_fin = fecha_fin.string
        hora = parser.parse(hora)
        final = parser.parse(fecha_fin)
        duracion = str(final-hora)
        try:
            duracion = duracion.split(' ')[2]
        except:
            duracion = duracion
        duracion = datetime.datetime.strptime(duracion, '%H:%M:%S')
        try:
            if precio.string == None:
                precio = "No hay info"
            else:
                precio = precio.string       
        except:    
            precio = "No hay info"
        hora = str(hora).split(" ")[1]
        fecha = fecha.string
        fecha = fecha.split(" ")[0]
        try:
            activ = Actividad.objects.get(id_evento = id_evento)
        except:
            actividad = Actividad(id_evento = id_evento,titulo = titulo.string, tipo = tipo, precio = precio, 
		                          fecha = fecha, hora = hora, duracion = duracion, 
                                  larga_duracion = larga_duracion,url = url.string, seleccionado = 0,puntos = 0)
            actividad.save()
    return HttpResponseRedirect("http://127.0.0.1:1234/todas")
Example #6
0
    def save(self, commit=True):
        if not commit:
            raise NotImplementedError(
                "Can't create Flujo without database save")

        proyecto = super(AsignarFlujoProyectoForm, self).save(commit=True)

        lista_completa = PlantillaFlujo.objects.all()
        seleccionados = self.cleaned_data['flujos']
        print "self save %s" % self.cleaned_data['flujos']

        lc_nombres = []
        for i in lista_completa:
            lc_nombres.append(i.nombre)

        ls_nombres = []
        for i in seleccionados:
            ls_nombres.append(i.nombre)

        la_nombres = []
        for i in Flujo.objects.filter(proyecto=proyecto):
            la_nombres.append(i.nombre)

        print "lc %s" % lc_nombres
        print "ls %s" % ls_nombres
        print "la %s" % la_nombres

        for s in ls_nombres:
            if s not in la_nombres:
                nuevo_flujo = Flujo(nombre=s, proyecto=proyecto)

                plantilla_flujo = PlantillaFlujo.objects.get(nombre=s)
                for act in plantilla_flujo.actividades.all():
                    estado1 = Estado(nombre="To do")
                    estado1.save()
                    estado2 = Estado(nombre="Doing")
                    estado2.save()
                    estado3 = Estado(nombre="Done")
                    estado3.save()

                    actividad = Actividad(nombre=act.nombre, orden=act.orden)
                    actividad.save()
                    actividad.estados.add(estado1)
                    actividad.estados.add(estado2)
                    actividad.estados.add(estado3)

                    actividad.save()
                    nuevo_flujo.save()
                    nuevo_flujo.actividades.add(actividad)

                nuevo_flujo.save()
                print "Creado nuevo flujo"

        user_stories = []
        en_uso = []
        for a in la_nombres:
            user_stories = []
            print "result %s" % UserStory.objects.filter(
                flujo__nombre=a).filter(proyecto=proyecto).exclude(
                    estado='Descartado')
            user_stories.append(
                UserStory.objects.filter(flujo__nombre=a).filter(
                    proyecto=proyecto).exclude(estado='Descartado'))
            if len(
                    UserStory.objects.filter(flujo__nombre=a).filter(
                        proyecto=proyecto).exclude(estado='Descartado')) != 0:
                en_uso.append(Flujo.objects.get(nombre=a, proyecto=proyecto))

        print "user_stories %s" % user_stories
        print "en_uso %s" % en_uso

        for c in lc_nombres:
            if c in la_nombres and c not in ls_nombres:
                flujo_pro = Flujo.objects.get(nombre=c, proyecto=proyecto)
                # flujo_pro.proyecto = None
                # flujo_pro.save()
                if flujo_pro not in en_uso:
                    flujo_pro.delete()

        #

        return proyecto
Example #7
0
    def endElement (self, name):

        todas = Actividad.objects.all()

        if self.inContent:
            self.theContent = normalize_whitespace(self.theContent)
        
        if self.atributo == 'TITULO':
            for fila in todas:
                if fila.titulo == self.theContent:
                    self.repetido = 1
            if self.repetido == 0:
                self.titulo = self.theContent

        elif self.atributo == 'GRATUITO' and self.repetido == 0:
            if self.theContent == '1':
                self.precio = 'Gratis'
            else:
                if self.precio == "":
                    self.precio = '-----'

        elif self.atributo == 'PRECIO' and self.repetido == 0:
            self.precio = self.theContent

        elif self.atributo == 'EVENTO-LARGA-DURACION' and self.repetido == 0:
            if self.theContent == '1':
                self.larga_dur = 'Si'
            else:
                self.larga_dur = 'No'

        elif self.atributo == 'FECHA-EVENTO' and self.repetido == 0:
            self.fecha = self.theContent.split(' ')[0].replace('-', ' ')
            self.fecha = datetime.strptime(self.fecha, '%Y %m %d')

        elif self.atributo == 'HORA-EVENTO' and self.repetido == 0:
            self.hora = self.theContent

        elif self.atributo == 'CONTENT-URL' and self.repetido == 0:
            self.url = self.theContent
            urlDescriptor = urllib2.urlopen(self.url)
            html = urlDescriptor.read()
            urlDescriptor.close()
            soup = BeautifulSoup(html)
            tag = soup.find("a", {"class":"punteado"})
            if tag == None:
                self.url = 'No disponible'
            else:
                self.url = tag.attrs['href']

        elif self.atributo == 'TIPO':
            if self.theContent.find('/') == -1:
                self.inContent = 0
            else:   
                if self.repetido == 0:
                    self.tipo = self.theContent.split('/')[3]
                    actividad = Actividad(titulo=self.titulo, tipo=self.tipo, precio=self.precio, fecha = self.fecha, hora = self.hora, larga_duracion=self.larga_dur, url = self.url, fecha_seleccion="2000-01-01")
                    actividad.save()
                    self.titulo = ""
                    self.tipo = ""
                    self.gratis = ""
                    self.precio = ""
                    self.fecha = ""
                    self.hora = ""
                    self.larga_dur = ""
                    self.url = ""
                else:
                    self.repetido = 0

        if self.inContent:
            self.inContent = 0
            self.theContent = ""
Example #8
0
class MyHandler( xml.sax.ContentHandler ):

    def __init__(self):
        self.ID_EVENTO = False
        self.TITULO = False
        self.TIPO = False
        self.GRATUITO = False
        self.FECHA_EVENTO = False
        self.FECHA_FIN_EVENTO = False
        self.HORA_EVENTO = False
        self.EVENTO_LARGA_DURACION = False
        self.CONTENT_URL = False
        self.Evento = Actividad

    def startElement(self, tag, attributes):
        if tag == 'atributo':
            if attributes.getValue("nombre") == 'ID-EVENTO':
                self.ID_EVENTO = True
            elif attributes.getValue("nombre") == 'TITULO':
                self.TITULO = True
            elif attributes.getValue("nombre") == 'TIPO':
                self.TIPO = True
            elif attributes.getValue("nombre") == 'GRATUITO':
                self.GRATUITO = True
            elif attributes.getValue("nombre") == 'FECHA-EVENTO':
                self.FECHA_EVENTO = True
            elif attributes.getValue("nombre") == 'HORA-EVENTO':
                self.HORA_EVENTO = True
            elif attributes.getValue("nombre") == 'EVENTO-LARGA-DURACION':
                self.EVENTO_LARGA_DURACION = True
            elif attributes.getValue("nombre") == 'CONTENT-URL':
                self.CONTENT_URL = True
   
    def characters (self, content):
        if self.ID_EVENTO:
            self.Evento = Actividad(id_evento=content)
            self.ID_EVENTO = False
        elif self.TITULO:
            self.Evento.titulo = content
            self.TITULO = False
        elif self.GRATUITO:
            if content == "1":
                self.Evento.gratis = True
            self.GRATUITO = False
        elif self.FECHA_EVENTO:
            self.Evento.fecha = content[:9]
            self.FECHA_EVENTO = False
        elif self.HORA_EVENTO:
            self.Evento.hora = content
            self.HORA_EVENTO = False
        elif self.EVENTO_LARGA_DURACION:
            if content == "1":
                self.Evento.largo = True
            self.EVENTO_LARGA_DURACION = False
        elif self.CONTENT_URL:
            self.Evento.url = content.replace('#amp#', '&')
            self.CONTENT_URL = False
        elif self.TIPO:
            try:
                self.Evento.tipo_evento = content.split('/')[3]
            except IndexError:
                self.Evento.tipo_evento = "Sin categoría"
            self.TIPO = False
            # TIPO es el ultimo elemento que lee, guardamos
            # puede haber problema con la fecha, que debe ignorar
            # ese evento se descarta
            try:
                self.Evento.save()
            except ValidationError:
                pass
Example #9
0
def add(request, recurso1):
    recurso = int(recurso1.split('/')[0])
    #recurso = recurso1.split('/')[0]
    print 'recurso' + str(recurso)
    i=1;
    longi= len(recurso1.split('/')[1:])
    recurso2 = '/'
    
    while (i<= longi):        
        recurso2 += '/' + recurso1.split('/')[i]
        i+=1
    print recurso2
    actividades = list(Actividad.objects.filter(user=request.user))
    aux = False
    if( len(list(Actividad.objects.all())) == 10):
        aux = True    
    for fila in actividades:
        if (fila.ide == lista[recurso]['id']):
            aux = True
    if(aux == False):
        act = Actividad()
        act.user = request.user
        act.titulo = lista[recurso]['titulo']
        act.tipo = lista[recurso]['tipo']
        try: 
            act.gratuito = int(lista[recurso]['gratuito'])
        except KeyError:
            act.precio = int(lista[recurso]['precio'])
        act.fecha = lista[recurso]['fecha'][2] + '/' + lista[recurso]['fecha'][1] + '/' + lista[recurso]['fecha'][0] 
        act.hora = lista[recurso]['hora']
        act.duracion = int(lista[recurso]['duracion'])
        act.url = lista[recurso]['url']
        act.ide = lista[recurso]['id']
        act.save()
    if (recurso2 == '//29'):
        return HttpResponseRedirect('/')
    else:
        aux= '/' + recurso2
        return HttpResponseRedirect(aux)         
Example #10
0
    def endElement(self, name):
        if name == 'contenido':
            if self.contador2 ==200000:
                self.contador2 = self.contador2
            else:
                
                self.name = ""
                self.inItem = False
                self.contador2 = self.contador2+1
        elif self.inItem:
            if name == 'atributo' and self.CurrentData == 'TITULO':
                self.titulo = self.theContent
                self.inContent = False
                self.theContent = ""
            if name == 'atributo' and self.CurrentData == 'PRECIO':
                self.precio = self.theContent
                self.inContent = False
                self.theContent = ""
            if name == 'atributo' and self.CurrentData == 'FECHA-EVENTO':
                self.fecha = self.theContent.split(" ")[0]  ##quito la hora de aqui por que siempre es 00:00
                self.inContent = False
                self.theContent = ""
            if name == 'atributo' and self.CurrentData == 'HORA-EVENTO':
                self.hora = self.theContent
                self.inContent = False
                self.theContent = ""
            if name == 'atributo' and self.CurrentData == 'FECHA-FIN-EVENTO':
                self.duracion = self.theContent
                self.inContent = False
                self.theContent = ""
            if name == 'atributo' and self.CurrentData == 'EVENTO-LARGA-DURACION':
                self.eslargo = int(self.theContent)
                self.inContent = False
                self.theContent = ""
            if name == 'atributo' and self.CurrentData == 'CONTENT-URL-ACTIVIDAD':
                self.urlinfo = self.theContent 
                self.inContent = False
                self.theContent = ""
            if name == 'atributo' and self.CurrentData == 'TIPO':
                self.tipo = self.theContent

                if self.precio == "":
                    self.precio = "gratuito"

                if len(self.fecha)==10 and len(self.hora)==5: #aveces da una fecha mal, solo guarda si es correcta

                    add=True
                    for actividad in actividades:
                        if actividad.titulo == self.titulo:
                            actividad.fechamod = fechamod #pone la fecha de modificacion
                            actividad.save()
                            add=False

                    if add:

                        a=Actividad(titulo=self.titulo, tipo = self.tipo, precio = self.precio, 
                                    fecha=self.fecha, hora=self.hora, duracion = self.duracion, 
                                    eslargo = self.eslargo, urlinfo = self.urlinfo[12:len(self.urlinfo)], fechamod = fechamod)
                        a.save()

                self.inContent = False
                self.theContent= ""
                inicializar(self)  #inicializa todas las variables
def RegisterUser():
    #Si intentan hacer GET a ésta vista mandamos http 403
    if request.method == 'GET':
        return abort(403)
    elif request.method == 'POST':
        data = request.get_data(parse_form_data=False, as_text=True)
        parsedData = data.split(',')
        name = parsedData[0]
        usuario = parsedData[1]
        clave = parsedData[2]
        grupo = parsedData[3]
        claveCifrada = hash_password(clave)

        try:

            inscrito = db_session.query(Grupo).filter(
                Grupo.idgrupo == grupo
            ).first(
            )  #Checamos si existe el grupo que ingresó el usuario, si no le regresamos un mensaje de error
            if (inscrito != None):
                validaUsuario = db_session.query(RegistroAlumno).filter(
                    RegistroAlumno.usuario == usuario).first()
                if (validaUsuario == None):
                    nuevoRegistro = RegistroAlumno(usuario=usuario,
                                                   contraseña=claveCifrada)
                    db_session.add(nuevoRegistro)
                    db_session.commit()
                    idRegistro = db_session.query(RegistroAlumno).filter(
                        RegistroAlumno.usuario == usuario).filter(
                            RegistroAlumno.contraseña == claveCifrada).first()
                    idAl = idRegistro.idregistroalumno
                    nuevoAlumno = Alumno(idregistroalumno=idAl, nombre=name)
                    db_session.add(nuevoAlumno)
                    db_session.commit()
                    idAlumno = db_session.query(Alumno).filter(
                        Alumno.idregistroalumno == idAl).first()
                    grupAlu = GrupoAlumno(idgrupo=grupo,
                                          idalumno=idAlumno.idalumno)
                    db_session.add(grupAlu)
                    db_session.commit()
                    newAct = Actividad(idgrupo=grupo,
                                       idalumno=idAlumno.idalumno)
                    db_session.add(newAct)
                    db_session.commit()
                    return redirect(
                        request.path
                    )  #Si llega hasta aquí se registró con éxito el usuario
                else:
                    #Si llega a éste punto entonces mandamos error al usuario de que ya existe el usuario que ingresó
                    flash("El usuario ya existe")
                    return redirect(request.path)
            else:
                flash(
                    "El grupo no existe"
                )  #Si llega a éste punto entonces el grupo que introdujo no existe y le mandamos un mensaje

                return redirect(request.path)

        except:
            db_session.rollback()
            raise
            return removeSession()