Beispiel #1
0
 def POST(self): 
     form = formularioFractal() 
     
     form.validates()  # Validamos el formulario para obtener los valores del usuario (y si tuvieramos algun validador lo ejecutaría!)
     
     html = """
     <html>
       <head>
         <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
         <title>Ejemplo de Formulario Enviado</title>
         <link rel="stylesheet" href="static/comun.css">
         <link rel="stylesheet" href="static/moonchild.css">
         <link rel="stylesheet" href="static/formulario.css">
       </head>
       <body>
         <h1>Ejemplo de Formulario Enviado</h1>
         
         <p>Esta página es la que gestiona el formulario enviado por el usuario. Si esperabas que ya pintase el fractal, la llevas clara, que eso es parte del siguiente ejercicio.</p>
         
         <p>Aquí solo diremos que el fractal que ha pedido el usuario es el que va desde <code>(%.2f, %.2f)</code> a <code>(%.2f, %.2f)</code>, de <code>%d</code> píxeles de ancho y <code>%d</code> iteraciones de máximo.</p>
         
         <p>¡Que pases un buen día!</p>
       </body>
     </html>""" % (float(form.d.x1), float(form.d.y1), float(form.d.x2), float(form.d.y2), int(form.d.anchura), int(form.d.iteraciones)) 
     
     return html
Beispiel #2
0
	def POST(self):
		form = singUP()

		form.validates()	 # Validamos el formulario para obtener valores del usuario

		if not form.validates():
			return form.render()
		else:
			html = """
			<html>
				<head>
					<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
					<title>Práctica 3</title>
					<link rel="stylesheet" href="static/comun.css">
					<link rel="stylesheet" href="static/formulario.css">
				</head>
				<body>
					<h1>PRÁCTICA 3</h1>

					<p>Resultado formulario</p>
						<p>Nombre: <code>%s</code></p>
						<p>Apellidos: <code>%s</code></p>
						<p>E-mail: <code>%s</code></p>
						<p>Fecha de nacimiento: <code>%s</code> / <code>%s</code> / <code>%s</code></p>
						<p>Direccion: <code>%s</code></p>
						<p>Contrasena: <code>%s</code></p>
						<p>Metodo de pago: <code>%s</code></p>
						<p>Numero de Visa: <code>%s</code></p>
				</body>
			</html> """ % (str(form.d.Nombre), str(form.d.Apellidos), str(form.d.email), str(form.d.Dia), str(form.d.Mes), str(form.d.Ano), str(form.d.Direccion), str(form.d.Contrasena), str(form.d.MetodoDePago), str(form.d.numVisa))

			return html
    def POST(self): 
        form = formulariop() 
        
        form.validates() 
                    
        f = open ("sugerencias.txt", "a")
 	f.write("%s : \n" % (form.d.nombre))
	f.write("%s \n\n --- \n" % (form.d.sugerencia))
 	f.close()
 	f=open("sugerencias.txt")
 	texto = f.read()
 	f.close()
        html = """
        <html>
          <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
            <title>Avanzado</title>
            <link rel="stylesheet" href="static/comun.css">
            <link rel="stylesheet" href="static/moonchild.css">
            <link rel="stylesheet" href="static/formulario.css">
          </head>
          <body>
            <h1>Gracias</h1>
	    <p>En breve se enviara la informacion</p>
            <p>Sugerencias hasta el momento</p>
	    <p>%s</p>
            
          
          </body>
        </html>""" % texto 
        
        return html
Beispiel #4
0
    def POST(self):
        form = self.TestForm();
        form.validates()
        code = form["code"].value
        print code
        stdin = form["stdin"].value

        compiler = Compiler()

        compileHasSucceeded = compiler.compile(code)
        error = ""
        if compileHasSucceeded :
            compiler.run(stdin)
            compiler.clean()
        else:
            error = "compilation has failed"



        return self.render.free(
            code,
            error,
            compiler.compileSdtout,
            stdin,
            compiler.runStdout
        )
Beispiel #5
0
 def POST(self): 
     form = formularioFractal() 
     
     form.validates()  # Validamos el formulario para obtener los valores del usuario (y si tuvieramos algun validador lo ejecutaría!)
     
     if (form.d.paleta == "azules"):
         paleta = [(255, 255, 255), (173, 205, 244), (255, 255, 255)]
         nColores = 15
     elif (form.d.paleta == "bn"):
         paleta = [(0, 0, 0), (255, 255, 255)]
         nColores = 2
     elif (form.d.paleta == "dolor"):
         paleta = [(255, 0, 0), (255, 255, 0), (255, 0, 255), (0, 255, 0), (0, 255, 255), (0, 0, 255)]
         nColores = 6
     elif (form.d.paleta == "dolor2"):
         paleta = [(255, 0, 0), (255, 255, 0), (255, 0, 255), (0, 255, 0), (0, 255, 255), (0, 0, 255)]
         nColores = 18
     elif (form.d.paleta == "grises"):
         paleta = [(0, 0, 0), (255, 255, 255)]
         nColores = 10
       
     nombreFichero = """static/mandelbrot_%f_%f_%f_%f_%d_%d_%s.png""" % (float(form.d.x1), float(form.d.y1), float(form.d.x2), float(form.d.y2), int(form.d.anchura), int(form.d.iteraciones), str(form.d.paleta))
     
     
     # Sistema de caché
     fechaActual = time()
     borraFicherosAntiguos("static/", "mandelbrot_", fechaActual - 24 * 60 * 60) # Ojo, esto es un poco borrico, porque se ejecuta cada vez que se sirve la página. Lo suyo sería asegurarnos que no se ejecuta, por ejemplo, nada más que una vez cada 10 minutos. Se puede hacer con un fichero con la ultima vez que se hizo el borrado y evitando otros borrados antes de que pasen los 10 minutos, pero no vamos a complicar más este código
     
     encontradoEnCache = "NO"
     # Si no existe (cacheado en el directorio static), lo renderizamos 
     if not os.path.isfile(nombreFichero):
         renderizaMandelbrotBonito(float(form.d.x1), float(form.d.y1), float(form.d.x2), float(form.d.y2), int(form.d.anchura), int(form.d.iteraciones), nombreFichero, paleta, nColores);
     else:
         encontradoEnCache = "SI"
         
     
     html = """
     <html>
       <head>
         <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
         <title>Fractal Generado</title>
         <link rel="stylesheet" href="static/comun.css">
         <link rel="stylesheet" href="static/moonchild.css">
         <link rel="stylesheet" href="static/formulario.css">
       </head>
       <body>
         <h1>Fractal Generado</h1>
         
         <p>Esta página es la que gestiona el formulario enviado por el usuario renderizando un fractal de Mandelbrot. Los datos del fractal son: desde <code>(%.2f, %.2f)</code> a <code>(%.2f, %.2f)</code>, de <code>%d</code> píxeles de ancho, <code>%d</code> iteraciones de máximo y la paleta <code>%s</code>.</p>
         
         <p>El fichero <code>%s</code> se ha encontrado en cache.</p>
         
         <p class="pImg">
           <img src="/%s" />
         </p>
       </body>
     </html>""" % (float(form.d.x1), float(form.d.y1), float(form.d.x2), float(form.d.y2), int(form.d.anchura), int(form.d.iteraciones), str(form.d.paleta), encontradoEnCache, nombreFichero)
     
     return html
Beispiel #6
0
 def POST(self):
     form = myform()
     form.validates()
     content = form['content'].value
     returnDict = parseContent(content)
     returnJson = json.dumps(returnDict['text'])
     statistics = json.dumps(returnDict['statistics'])
     return render.edit(returnJson, statistics)
Beispiel #7
0
 def POST(self):
   i = web.input()
   form = myform()
   form.validates()
   returnDict = str(i.parsedText)
   print "ok"
   returnDict = json.loads(returnDict)
   returnJson = json.dumps(returnDict['text'])
   statistics = json.dumps(returnDict['statistics'])
   return render.edit(returnJson, statistics)
	def POST(self):
 		form = myform()
		form.validates()
		
		nombre = str(form["nombre"].value);
		numerosSerie=str(form["serie"].value);
		numerosSerie = [int(x) for x in numerosSerie.split(',')]
		
		self.insertarSerie(nombre,numerosSerie)
		seriesLista = self.getSerieAll();
		
		return render.grafico(form, seriesLista)
Beispiel #9
0
	def POST(self):
 		form = myform()
		form.validates()
		
		nombre = str(form["nombre"].value)
		x = ast.literal_eval(form["x"].value)
		y = ast.literal_eval(form["y"].value)
		
		punto = Punto(nombre,x,y)
		idPunto = self.insertarPunto(punto)
		
		puntosAll = self.getPuntosAll();
		return render.mapa(form, puntosAll)
Beispiel #10
0
 def POST(self, name):
     form = fractalForm()
     
     palet = [(255, 255, 255), (173, 205, 244), (255, 255, 255)]
     nColors = 15
             
     if form.validates():
         if (form.d.palet == "blue"):
             palet = [(255, 255, 255), (173, 205, 244), (255, 255, 255)]
             nColors = 15
         elif (form.d.palet == "bw"):
             palet = [(0, 0, 0), (255, 255, 255)]
             nColors = 2
         elif (form.d.palet == "random"):
             palet = [(255, 0, 0), (255, 255, 0), (255, 0, 255), (0, 255, 0), (0, 255, 255), (0, 0, 255)]
             nColors = 6
         elif (form.d.palet == "random2"):
             palet = [(255, 0, 0), (255, 255, 0), (255, 0, 255), (0, 255, 0), (0, 255, 255), (0, 0, 255)]
             nColors = 18
         elif (form.d.palet == "gray"):
             palet = [(0, 0, 0), (255, 255, 255)]
             nColors = 10
         
         fileName = "static/mandelbrot.png"
         
         renderizaMandelbrotBonito(float(form.d.x1), float(form.d.y1), float(form.d.x2), float(form.d.y2), int(form.d.wide), int(form.d.iterations), fileName, palet, nColors);
         
         
         return render.formtest(form, fileName)
     
     else:
         return render.formtest(form)
    def POST(self):
        form = login2()
        if not form.validates():
            return form.render()
        usuario = form.d.usuario
        password = form.d.contrasenia

        nuevo = db0[usuario].split("|")

        if password == nuevo[2]:

            return """<html><body>
			<form name="input" action="/accederDBM" method="post">
			<p> %s te has logueado con la contrasenia %s </p>
			<a href="../periodico/%s"> Vuelve a portada</a>
			</form>
			</body></html>
			""" % (
                usuario,
                password,
                usuario,
            )
        else:
            return """<html><body>
			<form name="input" action="/accederDBM" method="post">
			<p> Contrasenia %s incorrecta </p>
			<a href="../periodico/"> Vuelve a portada</a>
			</form>
			</body></html>
			""" % (
                password
            )
Beispiel #12
0
 def POST(self):
     form = my_form()
     form.validates()
     s = form['textfield'].value
     print "text was %s" % (s)
     if session.uid:
         anUser = MongoElements(databaseTable)
         anUser.alreadyLoggedIn(session.uid)
         if str(s):
             anUser.addTask(s)
         else:
             print "ceva e in neregula [" +s + "]"
         currentUser = anUser.getMe()
         return render.tutorial(form, currentUser['userEmail'], currentUser['tasks'])
     else:
         return "use login to log in"
Beispiel #13
0
    def POST(self):
	usuario = comprueba_identificacion () 
	form = form_pract4()
	if not form.validates():
	   return render.datos (usuario = usuario, form = form)
	else:
	    try:
		db=dbm.open(form.d.DNI, 'r')
		
		nombre=db['Nombre']
		apellidos=db['Apellidos']
		dia=db['Dia']
		mes=db['Mes']
		anio=db['Anio']
		nacimiento= dia + '/' + mes + '/' + anio
		dni=db['DNI']
		visa=db['VISA']
		email=db['email']
		direccion=db['Direccion']
		contrasenia=db['Contrasenia']
		pago=db['pago']
		
		db.close()	
	    
		return render.vista(form=form, usuario=usuario, nombre=nombre, apellidos=apellidos, nacimiento=nacimiento, dni=dni, visa=visa, email=email, direccion=direccion, contrasenia=contrasenia, pago=pago)
	    except:
		return render.inicio(form=form, usuario=usuario, mensaje="Usuario no existente en la base de datos.")
Beispiel #14
0
 def POST(self):
     form = novel_form() 
     if not form.validates(web.input(_method="POST")): 
         return render_to_response("admin/add_novel", {
             "form": form,
         })
     else:
         args = web.input(_method="post", rid=None)
         next = "/tuoshui_admin/checkall"
         if args.rid:
             next = "/tuoshui_admin/checkall_recommends"
         del args.rid
         # 获得type
         args.type = get_type_by_url(args.url)
         if not args.type:
             return "type_error"
         ret = self.db.add_novel(args)
         if ret[0] is True:
             rid = web.input(_method="get", rid=None).rid
             # 修改推荐小说的状态
             if rid:
                 self.db.update_recommend_status(rid)
             raise web.seeother(next)
         else:
             return ret
Beispiel #15
0
	def POST(self):
		usuario = check_identification ()

		form = registro_form()
		
		if not form.validates():
			return render.registro (usuario = usuario, form = form)
		else:
			birth = form.d.dia + '/' + form.d.mes + '/' + form.d.anio
			pack_registro = {"nombre": form.d.nombre,
									"apellidos": form.d.apellidos,
									"email": form.d.email,
									"birth": birth,
									"password": form.d.password
									}
			coll.insert(pack_registro)

			#user.insert(pack_registro)

			#cursor = user.find()
			#for doc in cursor:
			#	print (doc['nombre'], doc['apellidos'])

			formi = login_form()
		return render.login(usuario = usuario, form = formi, mensaje = "Usuario registrado correctamente") 
Beispiel #16
0
 def POST(self):
     form = gift_form()
     if not form.validates():
         return render.add({'form':form})
     else:
         db.insert('gift', name=form.name.value, detail=form.detail.value)
         web.seeother('/list')
Beispiel #17
0
    def POST(self): 

        form = self.create_form()
        if not form.validates(): 
            return g_render.form(form)
        else:
            return self.make_config_xml(form)
Beispiel #18
0
	def POST(self): 
		form = myform() 
		if not form.validates(): 
			return render.formtest(form)
		else:
			searchvalue = form['Search'].value
			alllocation = ['New York City','Seattle','San Francisco', 'Boston', 'Austin', 'Chicago']
			alllocation.append(str(form['Location'].value))
			map_osm = folium.Map(location=[40.84706,-96.064453], zoom_start=4)
			for i in range(len(alllocation)):
				locgit = alllocation[i].replace(' ', '+')

				url = 'https://jobs.github.com/positions.json?description=' + searchvalue + '&location=' + locgit

				r = requests.get(url)
				resp = r.json()

				htmlinput = urllib.quote(alllocation[i])
				url2 = 'http://nominatim.openstreetmap.org/search?q=' + htmlinput + '&format=json'
				jsonResponse = simplejson.load(urllib.urlopen(url2))
				lati = jsonResponse[0]['lat']
				longi = jsonResponse[0]['lon']

				map_osm.simple_marker([lati, longi], popup='Number of ' + str(searchvalue) + ' jobs in ' + alllocation[i] + ': ' + str(len(resp)))

			mapurl = str(time.time()).replace('.','') + '.html'
			map_osm.create_map(path = 'static/' + mapurl)

			return render.mapoutput(mapurl, searchvalue)
    def POST(self2):
        form = register_form()
        if not form.validates():

            site_name = 'DAI - Desarrollo de Aplicaciones para internet'
            author = 'Ernesto Serrano'
            license = '2014 Copyleft'
            subtitle = 'Practica 4'
            page = 'register'
            logged_in = ses._initializer['logged_in']
            user = ses._initializer['user']


            return render.ejercicio_04(**locals())
        else:

            db = dbm.open('dbm', 'c')

            email = form.d.email

            for i in form.d:
                db[email+'_'+i] = str(form.d[i])

            site_name = 'DAI - Desarrollo de Aplicaciones para internet'
            author = 'Ernesto Serrano'
            license = '2014 Copyleft'
            subtitle = 'Practica 4'
            page = 'registered'
            logged_in = ses._initializer['logged_in']
            user = ses._initializer['user']
            firstname = form.d.firstname
            lastname = form.d.lastname


            return render.ejercicio_04(**locals())
Beispiel #20
0
	def POST(self):
		form = login()
		
		if not form.validates():
			mytemplate=Template(filename='editar.html')
			return mytemplate.render(form=form)
			
		else:
			
			try:
				conn=pymongo.MongoClient()
			except pymongo.errors.ConnectionFailure, e:
				print "Could not connect to MongoDB: %s" % e 
			
			
			db = conn['usuarios']
			collection = db.my_collection
				
			doc = {'usuario': form.d.Nombre, 'apellidos': form.d.Apellidos, 'DNI': form.d.DNI, 'email': form.d.email, 'fecha_nacimiento': form.d.dia_nacimiento+'/'+form.d.mes_nacimiento+'/'+form.d.anio_nacimiento, 'direccion': form.d.direccion, 'pago': form.d.FormaPago, 'visa': form.d.NumeroVISA, 'password': form.d.Contrasenia}

			collection.insert(doc)
			
			fu=login4()
			f2=login2()
			mytemplate=Template(filename='prueba.html')
			consulta = list(db.my_collection.find({"usuario": form.d.Nombre}))
			return mytemplate.render(consulta=consulta, form=f2, fu=fu)
    def request(self):
        # check for login
        if not session.logged_in:
            return WebOpenIDLoginRequired(self.query)

        form = WebOpenIDChangePasswordForm()

        if self.method == 'POST':
            if form.validates(self.query):
                password_manager.set(self.query['password'])

                session['no_password'] = False

                return web.found(
                    homedomain(web.ctx) + web.url('/account'))

        web.header('Content-type', 'text/html')
        return render.password(
            home_url=homedomain(web.ctx) + web.url('/'),
            logged_in=session.logged_in,
            logout_url=homedomain(web.ctx) + web.url('/account/logout'),
            change_password_url=homedomain(web.ctx) + web.url(
                '/account/change_password'),
            no_password=session.get('no_password', False),
            form=form,
        )
Beispiel #22
0
	def POST(self):
		usuario = comprueba_identificacion () 
		form = form_pract4()
	
		if not form.validates():
			return render.datos (usuario = usuario, form = form, vista1=sesion.vista1, vista2=sesion.vista2, vista3=sesion.vista3)
		else:
			try:
		
				cursor=coll.find({"DNI":form.d.DNI})
				nombre = cursor[0]["Nombre"]
				apellidos = cursor[0]["Apellidos"]
				dni = cursor[0]["DNI"]
				email = cursor[0]["email"]
				contrasenia = cursor[0]["Contrasenia"]
				dia = cursor[0]["Dia"]
				mes = cursor[0]["Mes"]
				anio = cursor[0]["Anio"]
				nacimiento = dia + '/' + mes + '/' + anio
				visa = cursor[0]["VISA"]
				direccion = cursor[0]["Direccion"]
				pago = cursor[0]["pago"]
		
				return render.vista(form=form, usuario=usuario, nombre=nombre, apellidos=apellidos, nacimiento=nacimiento, dni=dni, visa=visa, email=email, direccion=direccion, contrasenia=contrasenia, pago=pago, vista1=sesion.vista1, vista2=sesion.vista2, vista3=sesion.vista3)

			except:
				return render.inicio(form=form, usuario=usuario, mensaje="Usuario no existente en la base de datos.", vista1=sesion.vista1, vista2=sesion.vista2, vista3=sesion.vista3)
Beispiel #23
0
 def POST(self):
     form = addform()
     if not form.validates():
         users = model.get_users()
         return render.index(users, form)
     model.new_user(form.d.login,
                    form.d.password,
                    form.d.prefix,
                    form.d.firstname,
                    form.d.lastname,
                    form.d.email,
                    form.d.phone,
                    form.d.addr1,
                    form.d.addr2,
                    form.d.city,
                    form.d.state,
                    form.d.country,
                    form.d.zip,
                    form.d.approved)
     mailfrom = "rhn-newuser-request@localhost"
     mailto = "root@localhost"
     subject = "New User Added"
     message = "The following user has requested access: %s" % (form.d.login) 
     web.sendmail(mailfrom, mailto, subject, message)
     return "Thank you, an email will be sent for Approval."
	def POST(self): 
		form = form_datos() 
        
		if not form.validates():
			return render.registro(form = form)
		else:
			existe = existe_usuario(form.d.usuario)
			usuario = form.d.usuario
	
			if existe:
				form = form_acceso()
				return render.login(form = form, mensaje = "Registro fallido. Ya existe el usuario '"+usuario+"'")
			else:			

				db = anydbm.open(form.d.usuario, 'c')
			
				db['usuario'] = form.d.usuario
				db['password'] = form.d.password
				db['nombre'] = form.d.nombre
				db['apellidos'] = form.d.apellidos
				db['correo'] = form.d.correo
				db['visa'] = form.d.visa
				db['dia'] = form.d.dia
				db['mes'] = form.d.mes
				db['anio'] = form.d.anio
				db['direccion'] = form.d.direccion
				db['pago'] = form.d.pago

				db.close()

				form = form_acceso()
				return render.login(form = form, mensaje = "Registro del usuario '"+usuario+"' realizado correctamente.")
Beispiel #25
0
	def POST(self):
		form = myform()
		form.validates()
		
		contenido = str(form["contenido"].value);
		direccion = str(form["direccion"].value);
		radio =  str(form["radio"].value);
		centro = str(geocoder.google(direccion).lat) + "," + str(geocoder.google(direccion).lng)
		buscarTweets(contenido, direccion, radio)
		tweetsDB = tweetCol.find({"contenido" : contenido, "direccion" : direccion,"radio" : radio} )
		tweets = []
		for t in tweetsDB:
			tweets.append(t)
			
		series = hacerConteo(contenido);
		return render.app(form,centro,tweets,series)
Beispiel #26
0
	def POST(self):
		form = self.login_form()
		if not form.validates():
			return render.login(session.user, form)
		else:
			session.user = form['username'].value
			return render.login(session.user, form)
Beispiel #27
0
	def POST(self):
		usuario = comprueba_identificacion () 
		form = formu_nombre()
	
		if not form.validates():
			return render.datos (usuario = usuario, form = form, vista1=sesion.vista1, vista2=sesion.vista2, vista3=sesion.vista3)
		else:
			try:
		
				cursor=coll.find({"nombre":form.d.nombre})
				enero = cursor[0]["enero"]
				febrero = cursor[0]["febrero"]
				marzo = cursor[0]["marzo"]
				abril = cursor[0]["abril"]
				mayo = cursor[0]["mayo"]
				junio = cursor[0]["junio"]
				julio = cursor[0]["julio"]
				agosto = cursor[0]["agosto"]
				septiembre = cursor[0]["septiembre"]
				octubre = cursor[0]["octubre"]
				noviembre = cursor[0]["noviembre"]
				diciembre = cursor[0]["diciembre"]
		
				return render.mashup(usuario=usuario, enero=enero, febrero=febrero, marzo=marzo, abril=abril, mayo=mayo, junio=junio, julio=julio, agosto=agosto, septiembre=septiembre, octubre=octubre, noviembre=noviembre, diciembre=diciembre, vista1=sesion.vista1, vista2=sesion.vista2, vista3=sesion.vista3)

			except:
				return render.inicio(form=form, usuario=usuario, mensaje="Usuario no existente en la base de datos.", vista1=sesion.vista1, vista2=sesion.vista2, vista3=sesion.vista3)
    def request(self):
        return_to = self.query.get('return_to', web.ctx.homedomain + web.url('/account'))

        data = filter(lambda item: item[0] not in ['password'], self.query.items())

        form = WebOpenIDLoginForm(password_manager)()

        session['no_password'] = False

        if self.method == 'POST':
            try:
                if form.validates(self.query):
                    session.login()
                    data.append(('logged_in', True))
                    return web.found(return_to + '?' + web.http.urlencode(dict(data)))

            except PasswordManager.NoPassword:
                session['no_password'] = True
                session.login()
                data.append(('logged_in', True))
                return web.found(return_to + '?' + web.http.urlencode(dict(data)))

        web.header('Content-type', 'text/html')
        return render.login(
                logged_in=session.logged_in,
                login_url=web.ctx.homedomain + web.url('/account/login'),
                logout_url=web.ctx.homedomain + web.url('/account/logout'),
                change_password_url=web.ctx.homedomain + web.url('/account/change_password'),
                no_password=session.get('no_password', False),
                form=form,
                query=data,
            )
Beispiel #29
0
	def POST(self, web):
		form = myform()
		if not form.validates():
			return Output().pageReturnError("To be able to post you need to add image!")
		else:
			self._cache.setNotUpdated(0)
			return upload().get(web, self._db, 0)
Beispiel #30
0
	def POST(self):
		
		form = login3()
		
		if not form.validates():
			mytemplate=Template(filename='log.html')
			return mytemplate.render(form=form)
		else:
			
			user = form.d.Nombre
			pas = form.d.Contrasenia
			
			try:
				conn=pymongo.MongoClient()
			except pymongo.errors.ConnectionFailure, e:
				print "Could not connect to MongoDB: %s" % e 
			
			
			db = conn['usuarios']
			collection = db.my_collection
			
		
			if db.my_collection.find({'password':form.d.Contrasenia,'usuario':form.d.Nombre}).count() == 1:

				fo = login2()
				fu = login4()
				mytemplate=Template(filename='principal.html')
				session.usuario = form.d.Nombre
				session.pagina = 'log'	
				session.pagantes = ''
				return mytemplate.render(fo=fo, user=user, fu=fu)
			else:
				mytemplate=Template(filename='log.html')
				return mytemplate.render(form=form)
Beispiel #31
0
 def POST(self):
     form = myform()
     if not form.validates(
     ):  # recoge todas las variables y construye una estructura de datos, también comprueba si se cumplen los validadores que me haya creado
         return render.formtest(form)
     else:
         base = web.input()
         db = anydbm.open('db', 'c')
         db["nombre"] = str(base.nombre)
         db["apellidos"] = str(base.apellidos)
         db["dni"] = str(base.dni)
         db["correo"] = str(base.correo)
         db["dia"] = str(base.dia)
         db["mes"] = str(base.mes)
         db["anio"] = str(base.anio)
         db["direccion"] = str(base.direccion)
         db["passw"] = str(base.passw)
         db["passw2"] = str(base.passw2)
         db["forma_pago"] = str(base.forma_pago)
         db["numero_visa"] = str(base.numero_visa)
         db.close()
         return "Felicidades %s %s te has registrado satisfactoriamente." % (
             form.d.nombre, form['apellidos'].value)
Beispiel #32
0
    def POST(self):
		usuario = comprueba_identificacion () 
		form = form_pract3()
	
		if not form.validates():
			 return render.insercion (usuario = usuario, form = form, vista1=sesion.vista1, vista2=sesion.vista2, vista3=sesion.vista3)
		else:
			 nombres = {"Nombre": form.d.Nombre,
				    "Apellidos": form.d.Apellidos,
				    "Dia": form.d.dia,
				    "Mes": form.d.mes,
				    "Anio": form.d.anio,
				    "DNI": form.d.DNI,
				    "VISA": form.d.VISA,
				    "email": form.d.email,
				    "Direccion": form.d.Direccion,
				    "Contrasenia": form.d.Contrasenia,
				    "pago": form.d.pago 
			 }
			 coll.remove({"DNI":form.d.DNI})
			 coll.insert(nombres)
			 
			 return render.inicio(usuario=usuario, form=form, mensaje='Los datos han sido insertados correctamente',vista1=sesion.vista1, vista2=sesion.vista2, vista3=sesion.vista3)
Beispiel #33
0
    def POST(self):
        form = form_datos()

        if not form.validates():
            return render.registro(form=form)
        else:
            existe = existe_usuario(form.d.usuario)
            usuario = form.d.usuario

            if existe:
                form = form_acceso()
                return render.login(
                    form=form,
                    mensaje="Registro fallido. Ya existe el usuario '" +
                    usuario + "'")
            else:

                db = anydbm.open(form.d.usuario, 'c')

                db['usuario'] = form.d.usuario
                db['password'] = form.d.password
                db['nombre'] = form.d.nombre
                db['apellidos'] = form.d.apellidos
                db['correo'] = form.d.correo
                db['visa'] = form.d.visa
                db['dia'] = form.d.dia
                db['mes'] = form.d.mes
                db['anio'] = form.d.anio
                db['direccion'] = form.d.direccion
                db['pago'] = form.d.pago

                db.close()

                form = form_acceso()
                return render.login(form=form,
                                    mensaje="Registro del usuario '" +
                                    usuario + "' realizado correctamente.")
Beispiel #34
0
    def POST(self):
        form = registro()
        ses = web.ctx.session
        if not form.validates():
            return plantillas.index(
                title="Modificando ejercicio4.2",
                asignatura="Iniciando MODIFICACION ponga bien los datos",
                mofi="/modif",
                form=form,
                nombre=ses.get('usuario'))
        else:
            conn = pymongo.MongoClient()
            db = conn.mydb
            usuarios = db.usuarios
            usuario = {
                "Nombre": form['Nombre'].value,
                "Contrasenia": form['Contrasenia'].value,
                "Apellidos": form['Apellidos'].value,
                "dia": form['Fecha De Nacimiento dia'].value,
                "mes": form['Fecha De Nacimiento MES'].value,
                "anio": form['Fecha De Nacimiento ANIO'].value,
                "email": form['Correo Electronico'].value,
                "Direccion": str(form['Direccion'].value),
                "Forma de pago": form['Forma de pago'].value,
                "visa": form['N. VISA'].value
            }

            #Remuevo el antiguo ses.get('usuario') 			usuarios.remove({"usuario":ses.usuario})
            usuarios.remove({"Nombre": ses.get('usuario')})

            #Inserto el nuevo
            usuarios.insert(usuario)
            ses.usuario = form['Nombre'].value
            conn.close()
            return plantillas.index(title="practica 4(a)",
                                    asignatura="Modificacion realizada!!",
                                    nombre=ses.get('usuario'))
Beispiel #35
0
    def POST(self):
        ses = web.ctx.session
        form = charts()
        if ses.get('usuario', True):
            if not form.validates():
                return plantillas.index(
                    title="BIENVENIDO",
                    asignatura='Introducir datos correctamente',
                    form=form,
                    nombre=ses.get('usuario'),
                    grafica1="si")
            else:
                #web.header('Content-Type', 'text/html; charset=utf-8')
                Ingresos = []
                Ingresos.insert(1, form['Enero'].value)
                Ingresos.insert(2, form['Febrero'].value)
                Ingresos.insert(3, form['Marzo'].value)
                Ingresos.insert(4, form['Abril'].value)
                Ingresos.insert(5, form['Mayo'].value)
                Ingresos.insert(6, form['Junio'].value)
                Ingresos.insert(7, form['Julio'].value)
                Ingresos.insert(8, form['Agosto'].value)
                Ingresos.insert(9, form['Septiembre'].value)
                Ingresos.insert(10, form['Octubre'].value)
                Ingresos.insert(11, form['Noviembre'].value)
                Ingresos.insert(12, form['Diciembre'].value)
                Ingresos.insert(13, form['Anio'].value)
                return plantillas.index(
                    title="BIENVENIDO",
                    asignatura='Grafica realizada con EXITO',
                    nombre=ses.get('usuario'),
                    grafica=Ingresos)

        form = login()
        return plantillas.index(title="BIENVENIDO",
                                asignatura="PRACTICA 4(A)",
                                form=form)
    def POST(self):

        form = form_acceso()
        if not form.validates():
            return render.login(form=form)

        entrada = web.input()
        usuario = entrada.usuario
        password = entrada.password

        existe = existe_usuario(usuario)

        if existe == 0:
            return render.login(form=form,
                                mensaje="El usuario introducido no existe.")
        else:
            if password == comprueba_password(usuario):
                sesion.usuario = usuario
                return web.seeother('/')  # Redirige a inicio
            else:
                form = form_acceso()
                return render.login(
                    form=form,
                    mensaje="Los datos introducidos no son correctos.")
Beispiel #37
0
    def POST(self):
        form = myform()
        if not form.validates():
            return render.formtest(form)
        else:
            tmp = web.input()
            op = tmp['query']
            string = tmp['textfield']
            event = LoadEventInfo(string)
            tmp = event['stime']
            lockertime.acquire()
            stime = datetime.strptime(tmp, '%Y-%m-%dT%H:%M:%SZ')
            lockertime.release()

            if op == 'event':
                return json.dumps(event)

            if op == 'machinetag':
                print event['id']
                idtable = QueryPhotobyId(event['id'])
                time.sleep(0.5)
                return json.dumps(idtable)

            if op == 'title':
                ttable = QueryPhotobyTitle(event['id'], event['title'], stime)
                time.sleep(1)
                return json.dumps(ttable)
            if op == 'geo':
                gtable = QueryPhotobyGeo(event['id'],
                                         (event['lat'], event['lng']), stime)
                time.sleep(1.5)
                return json.dumps(gtable)
            if op == 'final':
                time.sleep(2)
                ftable = QueryFinalPhotos(event['id'])
                return json.dumps(ftable)
Beispiel #38
0
	def POST(self):
		form=registerForm
		if not form.validates():
			raise web.seeother('/#formdidnotvalidate')
		name=form.d.name
		number=form.d.number
		code=form.d.code

		###### security checks ######
		if not number.isdigit():
			raise web.seeother('/#numberdidnotvalidate')
		if not code=="cats":
			raise web.seeother('/#invalidsecuritycode')

		try:
			message = client.messages.create(body="Thanks for registering with us!",
				to="+1" + str(number),
				from_="+16103475899")
		except Exception as e:
			raise web.seeother('/#invalidnumber')

		db.insert('users', name=name, phone=number)
		db.insert('statuses', phone=number, status="I just joined Future SMS!", name=name)
		raise web.seeother('/demo')
Beispiel #39
0
    def POST(self, convo_id):
        force_login(sess)
        convo_id = int(convo_id)

        allowed = bool(
            db.select('convos',
                      what='1',
                      where='id = $cid and (id1 = $id or id2 = $id)',
                      vars={
                          'cid': convo_id,
                          'id': sess.user_id
                      }))
        if not allowed:
            return 'convo not found'

        form = self._form()
        if not form.validates():
            return 'fill everything in'

        db.insert('messages',
                  convo_id=convo_id,
                  sender=sess.user_id,
                  content=form.d.content)
        raise web.seeother('/convo/%d' % convo_id)
Beispiel #40
0
    def POST(self, name=None):
        sess = session.get_session()
        force_login(sess)

        form = self._form()
        if not form.validates():
            raise web.seeother('/password?msg=bad input')

        logintoken = convert_to_logintoken(sess.user_id)

        if logintoken:
            data = {
                "old_password": form.d.old,
                "new_password": form.d.pwd1,
                "new_password2": form.d.pwd2,
                "logintoken": logintoken
            }

            data = api_request("api/profile/pwd", "POST", data)
            if data['status'] == 200:
                raise web.seeother('/password')
            else:
                msg = data['error_code']
                raise web.seeother('/password?msg=%s' % msg)
Beispiel #41
0
    def POST(self):
        global user_ids
        form = self.myform()
        msg = ""
        err = ""

        if not form.validates():
            err = "Invalid fields."
        #Prevent those h4x0rs from trying to create user names
        #that might elevate their privellages.
        elif "=" in form.d.user or "&" in form.d.user or ";" in form.d.user:
            err = "Invalid characters in username."
        else:
            if form.d.user in user_db:
                err = "User already registered."
            else:
                #Set the password and role: only non-admin "users" can be created
                #through the web interface
                user_db[form.d.user] = [
                    hashlib.sha1(form.d.password).hexdigest(), user_ids, "user"
                ]
                user_ids += 1
                msg = "User registered."
        return render.generic(self.nullform(), "", msg, err)
Beispiel #42
0
    def GET(self): 

        # post requests are more complicated, they have 2 possible paths...
        # either the form is valid or not, reember that the view is different
        form = myform() 

        # if it's not valid, do the same as the get request, just return the form
        # however, in this case, the data user submitted is *still bound to the form*, so 
        # results will pre-populate 
        # the form.render() method includes error text AND fills out previous results
        if not form.validates(): 
            return render.basicform(form)
        else:
            variables = {
            
                'Index_drug': str(form['Index_drug'].value).upper(),
                'Comparator': str(form['Comparator'].value),
                'Druglist': str(form['Druglist'].value).upper(),           
                'Option_1': (1 if form['Option_1'].checked else 0),
                'Option_2': (1 if form['Option_2'].checked else 0),
            
            }
            result=calculate_burden.check_medlist(variables)
            return render.results(result['matched_drugs'],result['list_by_drug'],result['list_by_ae'],result['annotation_by_drug'],result['ae_score'],result['drug_score'],result['ae_total'],result['mods_p450'],result['subs_p450'])
 def POST(self):
     global pngindex
     pngindex += 1
     form = myform()
     if not form.validates():
         return render.formtest(form, "desc")
     else:
         # form.d.boe and form['boe'].value are equivalent ways of
         # extracting the validated arguments from the form.
         #return "Grrreat success! chromatic number: %s, conituity: %s, intersect: %s, overlap: %s, desc: %s " % \
         shutil.copy(os.path.join("pngs", pngs[pngindex]),
                     "static/temp.png")
         print pngindex, pngs[pngindex], pngs[0]
         writeToCSV(pngs[pngindex],form['ideal'].value,form['chromatic number'].value,form['continuity'].value,\
         form['intersect'].value,form['overlap'].value,form['description'].value)
         desc = "desc"
         try:
             desc = json.load(
                 open(os.path.join("jsons", pngs[pngindex][:-8] +
                                   ".json")))['Caption']
         except:
             print os.path.join("jsons",
                                pngs[pngindex][:-8] + ".json"), "error"
         return render.formtest(form, desc)
Beispiel #44
0
    def POST(self):
        form = self._form()
        if not form.validates():
            return 'bad input'

        if not all(form.d.email, form.d.password, form.d.name,
                   form.d.username):
            return 'you have to enter an email, a password, and a username'

        if email_exists(form.d.email):
            return 'email already exists'

        if username_exists(form.d.username):
            return 'username already exists'

        user_id = create_user(form.d.email,
                              form.d.password,
                              name=form.d.name,
                              username=form.d.username)
        if not user_id:
            return 'couldn\'t create user'

        login_user(sess, user_id)
        raise web.seeother('/dashboard')
    def POST(self):
        form = form_datos()

        if not form.validates():
            return render.registro(form=form)
        else:
            existe = existe_usuario(form.d.usuario)
            usuario = form.d.usuario

            if existe > 1:
                form = form_acceso()
                return render.login(
                    form=form,
                    mensaje="Registro fallido. Ya existe el usuario '" +
                    usuario + "'")
            else:
                doc = {
                    "usuario": form.d.usuario,
                    "password": form.d.password,
                    "nombre": form.d.nombre,
                    "apellidos": form.d.apellidos,
                    "correo": form.d.correo,
                    "visa": form.d.visa,
                    "dia": form.d.dia,
                    "mes": form.d.mes,
                    "anio": form.d.anio,
                    "direccion": form.d.direccion,
                    "pago": form.d.pago
                }

                col.insert(doc)

                form = form_acceso()
                return render.login(form=form,
                                    mensaje="Registro del usuario '" +
                                    usuario + "' realizado correctamente.")
Beispiel #46
0
 def POST(self):
     form = loginform()
     if not form.validates():
         return render.login(form)
     else:
         return web.seeother('/page_one')
Beispiel #47
0
    def POST_query(self, args):
        form = request()
        if not form.validates():
            return "Failure. Did you select an option for all the fields?"
        sym = form['symbol'].value
        start_string = form['startdate'].value
        end_string = form['enddate'].value

        date_format = "%Y-%m-%d"
        start = datetime.strptime(start_string,
                                  date_format).strftime("%Y-%m-%d")
        end = datetime.strptime(end_string, date_format).strftime("%Y-%m-%d")

        msb = mysqlmodel.MySqlBase()
        msb.connect()

        start_time = time.time()
        records = msb.get_by_sym_range2(sym, start, end)
        if len(records) == 0:
            message = "Zero records returned. Perhaps the date range is incorrect?"
            return render.error(message)
        records_unsorted = []
        print "number records: %s" % (len(records))
        for r in records:
            temp = r
            temp['date'] = datetime.strptime(str(temp['date']), "%Y-%m-%d")
            records_unsorted.append(temp)

        records_processed = sorted(records_unsorted, key=lambda k: k['date'])
        elapsed_time = (time.time() - start_time)

        y_max = 0.0
        y_min = 0.0
        data = []
        for q in records_processed:
            temp = float(q['price_adj_close'])
            data.append(temp)
            if temp > y_max:
                y_max = temp

        y_min = y_max

        for d in records_processed:
            temp = float(d['price_adj_close'])
            if temp < y_min:
                y_min = temp

        difference = float(y_max - y_min)
        difference = float(difference / 2)

        y_min_foo = y_min - difference
        y_max_foo = y_max + difference

        if y_min_foo < 0:
            y_min_foo = 0

        chart = SimpleLineChart(1000, 300, y_range=[y_min_foo, y_max_foo])

        chart.add_data(data)
        chart.set_colours(['0000FF'])
        #	chart.fill_linear_stripes(Chart.CHART, 0, 'CCCCCC', 0.1, 'FFFFFF', 0.2)
        #	chart.set_grid(0, 25, 5, 5)

        #	y_max_output = y_max + difference
        #	left_axis = range(y_min_foo, y_max_foo, 1.00)
        #	left_axis[0] = y_min

        left_axis = []
        label = y_min_foo
        delta_y = 1.00
        derp = float(y_max_foo - y_min_foo)
        #	if derp > 15.0:
        delta_y = derp / (10.00)

        while y_min_foo < y_max_foo:
            left_axis.append(y_min_foo)
            y_min_foo = y_min_foo + delta_y

        if len(left_axis) < 10:
            left_axis.append(y_min_foo)

        lines = len(left_axis) - 1
        chart.set_grid(0, lines, 1, 1)

        x_labels = []

        for t in records_processed:
            label = (self.getMonth(t['date'].month), t['date'].year)
            if not label in x_labels:
                x_labels.append(label)

        chart.set_axis_labels(Axis.LEFT, left_axis)
        chart.set_axis_labels(Axis.BOTTOM, x_labels)
        list_len = float(len(x_labels))
        top = float(1)
        stripe_len = float(top / list_len)
        chart.fill_linear_stripes(Chart.CHART, 0, 'CCCCCC', stripe_len,
                                  'FFFFFF', stripe_len)
        imgURL = chart.get_url()

        return render.results(sym, records_processed, elapsed_time, imgURL)
Beispiel #48
0
    def POST(self):
        ses = web.ctx.session
        form = buscar()
        if ses.get('usuario', True):
            if not form.validates():
                return plantillas.index(
                    title="BIENVENIDO",
                    asignatura=
                    'Introducir datos correctamente para analizar con el mashup',
                    form=form,
                    nombre=ses.get('usuario'),
                    mashup1="si")
            else:
                #web.header('Content-Type', 'text/html; charset=utf-8')
                datos = [
                ]  #0cadena a buscar,1 anio,2mes,numero 3dia y 4nombre 5valor,6-7-8 igual...
                laFecha = time.localtime(time.time())
                datos.insert(0, form['mashup'].value)
                datos.insert(1, laFecha[0])  #anio
                datos.insert(2, laFecha[1])  #mes
                consumer_key = '8WCVKxZMuLarti1uiPL71VHCX'
                consumer_secret = 'aRehFSGOTdTuUaDXGgGlTVSd2SdnmRFBCneuZlHkvDhBXDkk0U'
                access_token = '490393219-LTGxoqDmWciKFLBxMOaGSog2j20dSPngrQkuoMP1'
                access_token_secret = 'iTyEHiqWe72GvJtD946F5PJpOJh3eUrXCo2Nl3S59a1aH'
                # OAuth process, using the keys and tokens
                auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
                auth.set_access_token(access_token, access_token_secret)
                # Creation of the actual interface, using authentication
                api = tweepy.API(auth)
                # https://dev.twitter.com/docs/api/1.1/get/search/tweets
                contador = 1
                while contador < 8:
                    name_dia = dia(contador - 1)
                    num_dia = buscarnumdia(laFecha[2], laFecha[6],
                                           contador - 1)
                    datos.insert(3 * contador,
                                 num_dia)  #numero de dia  que corresponde
                    datos.insert(3 * contador + 1,
                                 name_dia)  #nombre al qe corresponde
                    cadena = '''%s-%s-%s''' % (laFecha[0], laFecha[1], num_dia)
                    cadena1 = '''%s-%s-%s''' % (laFecha[0], laFecha[1],
                                                num_dia + 1)
                    cuenta = 0
                    for tweets in api.search(q=datos[0],
                                             since=cadena,
                                             until=cadena1):
                        cuenta = cuenta + 1
                    datos.insert(3 * contador + 2, cuenta)  #numero de tweets
                    contador = contador + 1

                return plantillas.index(
                    title="BIENVENIDO",
                    asignatura='mashup realizada con EXITO',
                    nombre=ses.get('usuario'),
                    mashupdata=datos,
                    mashup="si")

        form = login()
        return plantillas.index(title="BIENVENIDO",
                                asignatura="PRACTICA 4(A)",
                                form=form)
Beispiel #49
0
	def POST(self):
		form = formu()
		if not form.validates():
			return plantilla.formulario(form)
		else:
			return "Mensaje enviado correctamente %s %s" % (form.d.nombre, form.d.otro)
Beispiel #50
0
	def POST(self):
		form = form_pract3()
		if not form.validates():
			return plantilla.formulario(form)
		else:
			return "Formulario practica 3 enviado correctamente" #%s %s" % (form.d.nombre, form.d.otro)	
Beispiel #51
0
    def POST(self):
        form = self.getForm()()
        if not form.validates():
            return render.settings(form)

        changes = []
        log.debug("Processing web request for settings changes")

        if form['home'].value != settings.get('location_home'):
            changes.append("Set Home location to %s" % (form['home'].value))
            settings.set('location_home', form['home'].value)

        if form['work'].value != settings.get('location_work'):
            changes.append("Set Work location to %s" % (form['work'].value))
            settings.set('location_work', form['work'].value)

        if form['weatherloc'].value != settings.get('weather_location'):
            changes.append("Set weather location to %s" %
                           (form['weatherloc'].value))
            settings.set('weather_location', form['weatherloc'].value)

        if int(form['snooze'].value) != settings.getInt('snooze_length'):
            changes.append("Set snooze length to %s" % (form['snooze'].value))
            settings.set('snooze_length', form['snooze'].value)

        if int(form['wakeup'].value) != settings.getInt('wakeup_time'):
            changes.append("Set wakeup time to %s" % (form['wakeup'].value))
            settings.set('wakeup_time', form['wakeup'].value)

        if int(form['precancel'].value) != settings.getInt('preempt_cancel'):
            changes.append("Set pre-emptive cancel time to %s seconds" %
                           (form['precancel'].value))
            settings.set('preempt_cancel', form['precancel'].value)

        if form['waketime'].value != settings.get('default_wake'):
            changes.append("Set default wake time to %s" %
                           (form['waketime'].value))
            settings.set('default_wake', form['waketime'].value)

        if form['holidaymode'].checked != (settings.getInt('holiday_mode')
                                           == 1):
            changes.append("Setting holiday mode to %s" %
                           (form['holidaymode'].checked))
            settings.set('holiday_mode',
                         1 if form['holidaymode'].checked else 0)
            if (settings.getInt('holiday_mode') == 1):
                # Just enabled holiday mode, so clear any alarms
                log.debug("Enabling holiday mode, clearing alarms")
                alarm.clearAlarm()
            else:
                # Just disabled holiday mode, so do an auto-setup
                log.debug("Disabling holiday mode, auto-setting alarm")
                alarm.autoSetAlarm()

        if form['weatheronalarm'].checked != (
                settings.getInt('weather_on_alarm') == 1):
            changes.append("Setting weather on alarm to %s" %
                           (form['weatheronalarm'].checked))
            settings.set('weather_on_alarm',
                         1 if form['weatheronalarm'].checked else 0)

        if form['sfx'].checked != (settings.getInt('sfx_enabled') == 1):
            changes.append("Setting SFX to %s" % (form['sfx'].checked))
            settings.set('sfx_enabled', 1 if form['sfx'].checked else 0)

        if form['ttspath'].value != settings.get('tts_path'):
            changes.append("Setting TTS path to %s" % (form['ttspath'].value))
            settings.set('tts_path', form['ttspath'].value)

        text = "Configuring settings:<p><ul><li>%s</li></ul>" % (
            "</li><li>".join(changes))
        # For debugging purposes
        for c in changes:
            log.debug(c)

        return render.confirmation(text)
Beispiel #52
0
	def POST(self, name):
		form = myform("")
		if not form.validates() and not name:
			return render.formtest(form, name,'Invalid input', self.getLog())
		else:
			return render.redir(escapeHashMarks(form.d.input))
Beispiel #53
0
 def POST(self): 
     form = myform() 
     if not form.validates(): 
Beispiel #54
0
 def POST(self):
     form = self.form()
     if not form.validates():
         return render.newsubject(form)
     model.new_subject(form.d.title,form.d.content)
     raise web.seeother('/')      
Beispiel #55
0
 def POST(self):
    form = myform()
    if not form.validates():
        return render.formtest(form)
    else:
        return "Grrreat success! files:%s csv:%s jdf:%s" % (form['files'].value,form['csv'].get_value(),form['jdf'].checked)
Beispiel #56
0
 def showfilter(self, config):
     if 'filter' in config:
         form = buildform('filter', config)
         form.validates(web.input())
         return form
Beispiel #57
0
 def POST(self):
     form = self.form()
     if not form.validates():
         return render.spend(form)
     model.new_spend(form.d.spend_time, form.d.summary)
     raise web.seeother('/')
Beispiel #58
0
 def POST(self):
     form = NameForm()
     if not form.validates():
         return render.index(form)
     name = form.d.Name
     return render.hello(name)
Beispiel #59
0
	def POST(self):
		form = Inputs()
		if not form.validates():
			return render.index(form, HelpContext)
		else:
			#print form.d.Path, form['Analysis'].value, form['Discrimination function'].value, form['size'].value, form['Unit'].value
			try:
			
				if form['Discrimination function'].value == "limitsize":
					IntSize = int(form['size'].value)
				else:
					IntSize = 0
				
				if os.path.isdir(form.d.Path):
					#print RadioUnit
					#print form.d.Path
					FinalQuantity, FileQuantity, EndSize, TotalSize, EndList, Ending, Files, Skipt = DM.disk_monitor(
						form.d.Path.encode('latin-1'), 
						form['Analysis'].value, 
						form['Discrimination function'].value, 
						IntSize, 
						form['Unit'].value.lower()
						)
					
					#print FinalQuantity, FileQuantity, EndSize, TotalSize, EndList
					NewEndSize = GF.conversion_soft(EndSize)
					NewTotalSize = GF.conversion_soft(TotalSize)
					
					#print NewEndSize, NewTotalSize
					StrEndList = []
	
					for Item in EndList:
						TempSize = GF.conversion_soft(Item[1])
						aaa = Item[0]
						#print aaa
						TempStr = '<p><a href="file:///{0}">{0}</a>, Size: {1}</p>' .format(aaa,TempSize)
					
						StrEndList.append(TempStr)
					
					#StrEnd = "".join(StrEndList)
					#print StrEndList
					#print StrEnd
					
					#zzz = json.dumps(StrEndList)
			
					#print json.loads(zzz)
					return render.result(
						FinalQuantity, 
						FileQuantity, 
						NewEndSize, 
						NewTotalSize, 
						StrEndList,
						Ending,
						Files,
						Skipt
						)
						
				else:
					return render.index(form, HelpContext)
				
			except ValueError as e:
				print e
				return render.index(form, HelpContext)