def actividad(request, identificador): if request.method == "POST": nombre = request.POST.get('nombre') grado = request.POST['grado'] actividad = Actividad.objects.get(id=identificador) persona = Persona(nombre=nombre, grado=grado, actividad=actividad) persona.save() try: actividad = Actividad.objects.get(id=identificador) except Actividad.DoesNotExist: return HttpResponse("No existe la actividad " + str(identificador)) respuesta = "La actividad " + actividad.nombre + " tendra lugar el " + str( actividad.horario) #los apuntados respuesta += "<br/></br>Apuntados: <ul>" apuntados = Persona.objects.filter(actividad=actividad) for apuntado in apuntados: respuesta += "<li>" + apuntado.nombre + " , " + apuntado.grado respuesta += "</ul>" if request.user.is_authenticated(): loggeado = '<p>Logeado como ' + request.user.username loggeado += '<br><a href="/logout"><button>Logout</button></a>' else: loggeado = '<p>No estas logeado' loggeado += '<br><a href="/login"><button>Loggeate</button></a>' context = {'contenido': respuesta, 'loggeado': loggeado} return render(request, 'actividad.html', {'context': context})
def actividad(request, identificador): if request.method =="POST": nombre = request.POST.get('nombre') grado = request.POST['grado'] actividad = Actividad.objects.get(id=identificador) persona = Persona(nombre=nombre, grado=grado, actividad=actividad) persona.save() try: actividad = Actividad.objects.get(id=identificador) except Actividad.DoesNotExist: return HttpResponse("No existe la actividad " + str(identificador)) respuesta = "La actividad " + actividad.nombre + " tendra lugar el " + str(actividad.horario) #los apuntados respuesta += "<br/></br>Apuntados: <ul>" apuntados = Persona.objects.filter(actividad=actividad) for apuntado in apuntados: respuesta += "<li>" + apuntado.nombre + " , " + apuntado.grado respuesta += "</ul>" if request.user.is_authenticated(): loggeado = '<p>Logeado como ' + request.user.username loggeado += '<br><a href="/logout"><button>Logout</button></a>' else: loggeado = '<p>No estas logeado' loggeado += '<br><a href="/login"><button>Loggeate</button></a>' context = {'contenido': respuesta, 'loggeado': loggeado} return render(request, 'actividad.html', {'context': context})
async def get_scenario(scenario_id: int) -> Scenario: return Scenario(id=scenario_id, titel='Asperger Syndrome: School inclusion', descr='**The scenario**\n\nMartin is an 10 year old boy with a level 2 Asperger Syndrome, ' + 'a type of autism.\nThe ethical decision is about whether Martin shall attend a ' + 'regular school ' + 'with an inclusion concept or a special school.', background_info='**Asperger syndrome - general information**\n\n' + 'Asperger syndrome (AS) is a milder autism spectrum disorder. AS is a lifelong ' + 'developmental disorder that includes differences or challenges in social ' + 'communication skills, fine and gross motor skills, speech, and intellectual ' + 'ability. The severity of autism is categorized as\n' + '* 1 - high–functioning,\n' + '* 2 – moderately severe and\n' + '* 3 – severe', decision_options=[DecisionOption(id='1', titel='What is the best choice for Martin?', descr='Shall Martin attend a regular school with ' + 'inclusion concept or a special school?')], personas=PersonaComposition( mandatory=[Persona(id=1, name='Martin, child with Asperger syndrome', descr='Martin is 10 years old with level 2 AS.'), Persona(id=2, name='Martin\'s parents', descr='- The family has modest income, only the father is employed\n' + '- Financial problems are associated with Martin\'s medical and ' + 'therapy expensed.'), Persona(id=3, name='Helen - teacher', descr='- She is perceived as patient, persistent and grateful.\n' + '- She is a good communicator, creative and inventing method to ' + 'help a child master the skills required by the curriculum ' + 'plan.')]) )
def post(self, user_id): a_user = User.get_by_key_name(user_id) if not a_user: print 'OMG' return # raise webob.exc.HTTPNotFound() type = self.request.GET.get('account_type') id = self.request.GET.get('account_id') persona = Persona(key_name='%s-%s' % (a_user.key(), type), id=id, type=type, parent=a_user) persona.put() if not type in a_user.personas: a_user.personas.append(type) a_user.put() return webapp2.redirect_to('personas', user_id=user_id)
def post(self): nombreP = cgi.escape(self.request.get('nombre')) edadP = int(cgi.escape(self.request.get('edad'))) emailP = cgi.escape(self.request.get('email')) personaNueva = Persona(parent = agendaKey('agendaORT')) personaNueva.nombre = nombreP personaNueva.edad = edadP personaNueva.email = emailP key = personaNueva.put() self.redirect('/listarPersonas')
def send_reminders(): """Send all open reminder emails""" for persona in Persona.query(): # Compile list of movements p_movements = Movement.query(Movement.members == persona.key) movements = list() for m in p_movements: # The email should be sent if the start date of the next cycle less the cycle buffer equals the current date if (m.get_cycle_startdate(m.get_next_cycle()) - m.get_cycle_buffer()) - datetime.date.today() == datetime.timedelta(days=0): n_goals = persona.get_goals(m.key).count() movements.append((m.name, n_goals)) if len(movements) > 0: # Put together the message message_body = "Hello {name}, \n\nthe following movements are approaching their next cycle. " \ + "Take a minute and write down your goals.\n\n".format(persona.name, **kwargs) message_body += "\n".join("* {name} ({num} current goals)".format( name=name, num=n_goals) for name, n_goals in movements) message_body += "\n\nhttp://souma-motor.appspot.com/\n\nYours truly,\Motor" # Send message mail.send_mail(sender="Souma Motor <*****@*****.**>", to="{name} <{email}>".format(name=persona.name, email=persona.email), subject="What do you want to do next in {}?".format(", ".join(name for name, n in movements)), body=message_body) logging.info("Sent reminder email about {} movements to {}: {}".format(len(movements), persona.name, message_body)) else: logging.info("No reminders for {}".format(persona.name)) return ""
def create_Persona(): if request.headers['Content-Type'] == 'application/json': req_data = request.get_json(force=True) persona_edad = req_data['persona_edad'] persona_nombre = req_data['persona_nombre'] persona_apellido = req_data['persona_apellido'] persona_ciudad = req_data['persona_ciudad'] element = [] element.extend( [persona_edad, persona_nombre, persona_apellido, persona_ciudad]) resp_val = validate_fields(element) if resp_val == True: persona = Persona(persona_edad=persona_edad, persona_nombre=persona_nombre, persona_apellido=persona_apellido, persona_ciudad=persona_ciudad) curr_session = db.session try: curr_session.add(persona) curr_session.commit() except: curr_session.rollback() curr_session.flush() id_persona = persona.id_persona data = Persona.query.filter_by(id_persona=id_persona).first() res = toResponse(persona) return jsonify(data=res, status_code=200) else: return resp_val else: return jsonify( data="Unsupported media only content-type application/json")
def Alta_persona(): if request.method == 'POST': if not request.form['name'] or not request.form['city'] or not request.form['addr']: flash('Ingrese todos los campos', 'error') else: nombre =request.form['name'] email =request.form['city'] direccion =request.form['addr'] telefono =request.form['pin'] existe = Persona.query.filter(Persona.nombre == nombre).first() if existe: flash('"La persona ya existe !"') else: try: persona = Persona(nombre,email,direccion,telefono) db.session.add(persona) except Exception as error: print("ERROR ! al cargar la persona!") print(str(error)) db.session.rollback() flash('"ERROR ! al cargar la persona !"') else: db.session.commit() flash('La persona fue agregada correctamente') return redirect(url_for('Listar_todas_las_personas')) return render_template('Alta_persona.html')
def consultar(self, email, password): try: cnx = super().connectDB() cursor = cnx.cursor() sql = "select * from PERSONA where email='" + email + "' and contraseña=sha('" + password + "') and rol='admin';" cursor.execute(sql) administrador = None for row in cursor: documento = row[0] nombre = row[1] direccion = row[2] email = row[3] sexo = row[4] contraseña = row[5] rol = row[6] telefono = row[7] administrador = Persona(documento, nombre, direccion, email, sexo, contraseña, rol, telefono) cursor.close() cnx.close() return administrador except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("Something is wrong with your user name or password") elif err.errno == errorcode.ER_BAD_DB_ERROR: print("Database does not exist") return None
def auto_create_persona(): user = users.get_current_user() if user: persona = Persona.get_or_insert(user.user_id()) if persona.email is None: persona.name = user.email().split("@")[0] persona.email = user.email() persona.put()
def post(self): persona = Persona(cedula=request.form["dni"], nombre=request.form["name"], apellido=request.form["last_name"], fechaNacimiento=request.form["birthdate"], tipo=request.form["type"]) session.add(persona) session.commit()
def persona_context(): """Makes current_persona available in templates""" user = users.get_current_user() if user: persona = Persona.get_by_id(user.user_id()) else: persona = None return dict(current_persona=persona)
def agregar(): persona = Persona() personaForm = PersonaForm(obj=persona) if request.method == 'POST': if personaForm.validate_on_submit(): personaForm.populate_obj(persona) app.logger.debug(f'Persona a insertar: {persona}') #insertar registro db.session.add(persona) db.session.commit() return redirect(url_for('inicio')) return render_template('agregar.html', forma=personaForm)
def index(): # ----Render a list of the current user's movements and their current cycles current_persona = Persona.get_by_id(users.get_current_user().user_id()) movements = Movement.query() movements_with_forms = [] for m in movements: m.form = GoalForm() m.form.movement_id.data = m.key.id() m.form.cycle.data = m.get_next_cycle() m.user_is_member = (current_persona.key in m.members) movements_with_forms.append(m) return render_template('index.html', movements=movements)
def agregarPersona(idFamiliar, user, password): try: persona=Persona( idFamiliar=idFamiliar, user=user, password=password ) db.session.add(persona) db.session.commit() return "Persona added. person id={}".format(persona.id) except Exception as e: return(str(e))
def get(self, user_id): a_user = User.get_by_key_name(user_id) if not a_user: raise webob.exc.HTTPNotFound() personas = Persona.all().ancestor(a_user).run() if not personas: raise webob.exc.HTTPNotFound() personas = [funcs.convert_model(persona) for persona in personas] self.response.write( json.json.dumps( {'meta': funcs.meta_ok(), 'personas' : personas } ))
def join_movement(movement_id): if request.method == "POST": movement = Movement.get_by_id(movement_id) user = users.get_current_user() persona = Persona.get_by_id(user.user_id()) if persona.key in movement.members: movement.members.remove(persona.key) movement.put() flash("You left the movement '{}'".format(movement.name), 'info') else: movement.members.append(persona.key) movement.put() flash("You joined the movement '{}'".format(movement.name), 'success') return redirect(request.referrer)
def goal_view(goal_id=None): if goal_id: # ---- Delete a goal and redirect to http ref goal = Goal.get_by_id(goal_id) if goal_id else None if not goal: flash('The goal with the id {} could not be found'.format(goal_id), 'error') else: if goal.movement.get().get_current_cycle() >= goal.cycle: flash('You can only delete goals for future cycles', 'error') else: goal.key.delete() flash("Goal has been deleted", 'info') return redirect(request.referrer or url_for('index')) else: # ---- Create a new goal and redirect http ref form = GoalForm(request.form) if form.validate_on_submit(): author = Persona.get_by_id(users.get_current_user().user_id()) if not author: flash("You user account was not found", "error") return redirect(request.referrer) movement = Movement.get_by_id(int(form.movement_id.data)) if not movement: flash("The movement '{}' was not found".format(form.movement_id.data), 'error') return redirect(request.referrer) if len(form.desc.data) > 500: # Remove non-ascii characters flash("Goals can have at most 500 characters. Your goal: {}".format( "".join(i for i in form.desc.data if ord(i) < 128)), "error") return redirect(request.referrer) goal = Goal( movement=movement.key, author=author.key, cycle=int(form.cycle.data) if form.cycle.data else None, desc=form.desc.data ) try: goal.put() goal_id = goal.key.id() flash("Goal successfully created", 'success') return redirect(request.referrer or url_for('index')) except CapabilityDisabledError: flash("Sorry, datastore is currently in read-only mode", 'error') return redirect(request.referrer or url_for('index')) else: flash("Invalid form submitted", "error") return redirect(request.referrer)
def mifeed(request, username): url = "http://twitrss.me/twitter_user_to_rss/?user="******"" for number in range(5): salida += dicc.entries[number].title + "<br>" urls = dicc.entries[number].title.split() for url in urls: if url.find("http") == False: url = url.split('&')[0] salida += "<li><a href=" + url + ">" + url + "</a></li>" bSoup = BeautifulSoup(urllib.urlopen(url).read()) if (bSoup.p) != None: salida += str(bSoup.p).decode('utf8') + "</br>" if (bSoup.img) != None: salida += str(bSoup.img).decode('utf8') + "</br>" salida+= "</br>" try: fila = Persona.objects.get(name= username) except Persona.DoesNotExist: fila = Persona(name = username) fila.save() try: f = Tweet.objects.get(content= dicc.entries[number].title) except Tweet.DoesNotExist: f = Tweet(content= dicc.entries[number].title, url= dicc.entries[number].link, name=fila) f.save() return HttpResponse(salida)
def agregar(): # Instanciamos la clase de modelo # Instanciamos la clase form y le asociamos la clase de modelo # Mostramos formulario persona = Persona() personaForm = PersonaForm(obj=persona) if request.method == 'POST': if personaForm.validate_on_submit(): personaForm.populate_obj(persona) app.logger.debug(f'Persona a insertar {persona}') # insertamos el nuevo registro db.session.add(persona) db.session.commit() return redirect(url_for('inicio')) return render_template('agregar.html', forma=personaForm)
def post(self): adopcion = Adopcion(id_duenio=request.form["id_owner"], id_mascota=request.form["id_pet"], fecha=datetime.datetime.now().isoformat()) persona = Persona.query.get(request.form["id_owner"]) if (not persona): p = Persona(cedula=request.form["id_owner"], nombre=request.form["name"], apellido=request.form["last_name"], fechaNacimiento=request.form["birthday"], tipo="dueño") session.add(p) session.commit() session.add(adopcion) session.commit()
def agregar(): persona = Persona() personaForm = PersonaForm( obj=persona ) #le indico que el formulario va a utilizar la clase persona #Agarrar los datos del form y enviarlos a la bdd if request.method == "POST": if personaForm.validate_on_submit( ): #lo que hace es validar que el formulario sea valido personaForm.populate_obj( persona) #completa el objeto de tipo modelo #insertamos nuevo registro db.session.add(persona) db.session.commit() return redirect(url_for("inicio")) return render_template("agregar.html", forma=personaForm)
def send_roundups(): """Send all open roundup emails""" for persona in Persona.query(): # Compile list of movements p_movements = Movement.query(Movement.members == persona.key) movements = list() for m in p_movements: # The email should be sent if today is the start date of the current cycle if m.get_cycle_startdate() == datetime.date.today(): movements.append(m) if len(movements) > 0: # Put together the message message_body = "Hello {name}, \n\na new cycle is starting for these movements. See what your teammates are up to:\n\n".format( name=persona.name, movements=", ".join(m.name for m in movements)) for m in movements: message_body += "--- {} ---\n\n".format(m.name.upper()) for p_key in m.members: persona = p_key.get() goals = persona.get_goals(m.key) message_body += "{} ({}): {}\n".format(persona.name, persona.email, "---" if goals.count() == 0 else "") message_body += "\n".join("* {}".format(g.desc) for g in goals) message_body += "\n" message_body += "\n" message_body += "\nhttp://souma-motor.appspot.com/\n\nYours truly,\Motor" # Send message mail.send_mail(sender="Souma Motor <*****@*****.**>", to="{name} <{email}>".format(name=persona.name, email=persona.email), subject="See what's next in {}".format(", ".join(m.name for m in movements)), body=message_body) logging.info("Sent roundup email about {} movements to {}: {}".format(len(movements), persona.name, message_body)) else: logging.info("No roundup for {}".format(persona.name)) return ""
def __init__(self, articulo_xml): self.texto = articulo_xml.text.replace('\n', ' ').strip() self.es_una_designacion = False designacion_match = re.search(u"des[ií]+gn", self.texto, re.IGNORECASE | re.UNICODE) if designacion_match: pos = designacion_match.start() self.es_una_designacion = True # Buscamos a la persona persona_nombre = PersonaParser.get_nombre_desde_articulo( self.texto) if not persona_nombre: logging.error(logging_msg, "No se encontro a la PERSONA", articulo_xml) persona_codigo = PersonaParser.get_codigo_desde_articulo( self.texto) if not persona_codigo[0]: logging.error(logging_msg, "No se encontro el CODIGO TIPO", articulo_xml) if not persona_codigo[1]: logging.error(logging_msg, "No se encontro el CODIGO NUMERO", articulo_xml) persona = Persona(persona_nombre, persona_codigo[0], persona_codigo[1]) # Buscamos los puestos y la dependencia puestos = PuestoParser.get_puestos(self.texto) if len(puestos) == 0: logging.error(logging_msg, "No se encontraron PUESTOS", articulo_xml) dependencia = PuestoParser.get_dependencia(self.texto) if not dependencia: logging.error(logging_msg, "No se encontro la DEPENDENCIA", articulo_xml) self.designacion = Designacion(persona, puestos, dependencia, self.texto)
def get(self): consulta = Persona.query(ancestor = agendaKey('agendaORT')).order(Persona.nombre) personas = consulta.fetch(10) #Obtenemos el usuario actual. Si es nulo, no esta logueado. loggedUser = users.get_current_user() if loggedUser: nombreUsuario = users.get_current_user().email() usuarioUrl = users.create_logout_url(self.request.uri) urlText = 'Logout' else: nombreUsuario = 'No logueado' usuarioUrl = users.create_login_url(self.request.uri) urlText = 'Login' template = JINJA_ENVIRONMENT.get_template('agenda.html') template_values = { 'listaPersonas':personas, 'usuario':nombreUsuario, 'url': usuarioUrl, 'textoLink': urlText} self.response.write(template.render(template_values))
def __init__(self, anexo_xml): self.texto = anexo_xml.text.replace('\n', ' ').strip() self.columnas = [x for x in anexo_xml.find_all('td') if x.get_text()] self.designaciones = [] # Arreglar de alguna manera esta negrada # Por el momento identificamos 4 tipos de tablas diferentes, hay muchas mas # CAMBIAR ESTO, NO SIRVE PARA NADA tabla_tipo = 0 for i in range(len(self.columnas)): #B 0 - FE II columna = self.columnas[i].text columna_sig = self.columnas[i].text if re.search(u'^[A-Z] \d - [A-Z][A-Z] [A-Z][A-Z]$', columna) and \ (tabla_tipo == 0 or tabla_tipo == 1): persona_nombre = self.columnas[i + 1].text persona_codigo = PersonaParser.get_codigo( self.columnas[i + 2].text) persona = Persona(persona_nombre, persona_codigo[0], persona_codigo[1]) puestos = [self.columnas[i - 1].text.upper()] dependencia = self.columnas[i - 2].text.upper() self.designaciones.append( Designacion(persona, puestos, dependencia, self.texto)) if tabla_tipo == 0: tabla_tipo = 1 elif columna == u"DNI" and \ (tabla_tipo == 0 or tabla_tipo == 2): persona_nombre = u"{0} {1}".format(self.columnas[i - 1].text, self.columnas[i - 2].text) codigo_texto = u"DNI {0}".format(self.columnas[i + 1].text) persona_codigo = PersonaParser.get_codigo(codigo_texto) persona = Persona(persona_nombre, persona_codigo[0], persona_codigo[1]) puestos = [self.columnas[i + 3].text.upper()] dependencia = self.columnas[i + 2].text.upper() self.designaciones.append( Designacion(persona, puestos, dependencia, self.texto)) if tabla_tipo == 0: tabla_tipo = 2 elif re.search(u'^[A-Z]$', columna) and \ (tabla_tipo == 0 or tabla_tipo == 3): persona_nombre = self.columnas[i - 2].text codigo_texto = self.columnas[i - 1].text if re.search(u"\d\d\d\.\d\d\d", persona_nombre): codigo_texto, persona_nombre = persona_nombre, codigo_texto persona_codigo = PersonaParser.get_codigo(codigo_texto) persona = Persona(persona_nombre, persona_codigo[0], persona_codigo[1]) try: puestos = [self.columnas[i + 2].text.upper()] except IndexError: puestos = [] # No se encuentra la dependencia self.designaciones.append( Designacion(persona, puestos, None, self.texto)) if tabla_tipo == 0: tabla_tipo = 3 elif re.search(u'^[A-Z]-\d$', columna) and \ (tabla_tipo == 0 or tabla_tipo == 4): persona_nombre = self.columnas[i - 2].text codigo_texto = self.columnas[i - 1].text if re.search(u"\d\d\d\.\d\d\d", persona_nombre): codigo_texto, persona_nombre = persona_nombre, codigo_texto persona_codigo = PersonaParser.get_codigo(codigo_texto) persona = Persona(persona_nombre, persona_codigo[0], persona_codigo[1]) try: puestos = [self.columnas[i + 1].text.upper()] except IndexError: puestos = [] # No se encuentra la dependencia self.designaciones.append( Designacion(persona, puestos, None, self.texto)) if tabla_tipo == 0: tabla_tipo = 4
def persona_view(persona_id=None): # ---- Render a persona profile persona = Persona.get_by_id(persona_id) return render_template('persona.html', persona=persona)
def list_personas(): # ---- List all personas personas = Persona.query() return render_template('list_personas.html', personas=personas)