def centers(): try: if request.method == "GET": centros = Center.return_centers_API_Data() count = len(centros) page = int(request.args.get("page", 1)) limit = (PageSetting.find_settings()).elements if 0 >= page: return render_template("errors/error404.html") obj = {} obj["page"] = page obj["limit"] = limit obj["count"] = count obj["centros"] = centros[(page - 1) * limit : (page * limit)] return jsonify(obj) else: params = json.loads(request.data) mensaje = Center.create(params) if mensaje[0][1] == "success": response = {"status": 201, "body": mensaje[0][0], "center": params} else: response = {"status": 409, "body": mensaje[0][0]} return jsonify(response), response.status except Exception as e: return jsonify(detect_error(sys.exc_info()[0], e))
def delete_center(): """Elimina un centro de manera definitiva""" try: center_id = request.args['object_id'] center_name = Center.get_by_id(center_id).name if Center.delete_by_id(center_id): dbSession.commit() flash("el Centro {} ha sido borrado".format(center_name), "info") except BadRequestKeyError: flash("ERROR: id Centro no recibido", "danger") except NoResultFound as e: flash(e, 'danger') finally: return redirect(url_for('center_index'))
def create(): """ Da de alta un centro en la base de datos.""" form = CreateCenterForm() app.logger.info(form.data) if form.validate(): center = Center() form.populate_obj(center) center.protocol = request.files['protocol'].read() dbSession.add(center) dbSession.commit() if form.errors: display_errors(form.errors) return redirect(url_for("center_new")) return redirect(url_for("center_index", page=1))
def create(id): try: datos_turno = request.get_json() if id != datos_turno['centro_id']: raise ValueError("id url no coincide con centro_id.") center = Center.get_by_id(id) # datos_turno['centro_id'] Shifts.check_date(str_date_to_datetime(datos_turno['fecha']).date()) Shifts.check_duration(str_time_to_datetime(datos_turno['hora_inicio']), str_time_to_datetime(datos_turno['hora_fin'])) datos_turno['hora_inicio'] = str_time_to_datetime( datos_turno['hora_inicio']).time() datos_turno['hora_fin'] = str_time_to_datetime( datos_turno['hora_fin']).time() datos_turno['fecha'] = str_date_to_datetime( datos_turno['fecha']).date() shift = Shifts.populate_from_api(datos_turno) created_shift = Shifts.create_shift( shift, center) # errores posibles capturados return jsonify({"atributos": created_shift.serialize()}), 200 except (BadRequestKeyError, ValueError, KeyError, AttributeError, NoResultFound) as err: app.logger.info(traceback.format_exc()) return get_json_error_msg(error_msg=str(err), error_code=420, status="invalid request") except Exception as e: app.logger.info(traceback.format_exc()) return get_json_error_msg(error_code=500, error_msg="Error inesperado", status="internal server error")
def new_view(center_id): try: center = Center.get_by_id(center_id) except NoResultFound as err: flash(err, "danger") return redirect(url_for("turnos_index")) form = CreateShiftForm() return render_template("shifts/new.html", form=form, center=center)
def index(): try: page = int(request.args['page']) except (BadRequestKeyError, ValueError): page = 1 try: res = Page(Center.get_for_index(), page, SYS_PAGE_COUNT) except AttributeError: return redirect(url_for('center_index')) return render_template("center/index.html", pagination=res)
def get_protocol(object_id): try: center = Center.get_by_id(object_id) return send_file(io.BytesIO(center.protocol), mimetype='pdf', as_attachment=True, attachment_filename='{} protocol.pdf'.format( center.name)) except NoResultFound as e: flash(e, 'danger') return redirect(url_for("center_index"))
def update_center_form(object_id): """ renderiza el formulario para editar un centro """ try: center = Center.get_by_id(object_id) except NoResultFound as e: flash(e, "danger") return redirect(url_for('center_index')) form = CreateCenterForm(obj=center) return render_template('center/update.html', form=form, center_id=object_id)
def update_form(): form_date = request.args['date'] center_id = request.args['center_id'] try: center = Center.get_by_id(center_id) except NoResultFound as err: flash(err, "danger") return redirect(url_for('turnos_new')) d = datetime.strptime(form_date, "%Y-%m-%d").date() return jsonify( list( map(lambda t: t.isoformat(), center.get_shifts_blocks_avalaible(d))))
def search_by_state(): try: state = eval(request.args['args'])['state'] page = int(request.args['page']) except (BadRequestKeyError, ValueError) as e: flash("ERROR: {}".format(e), e) return redirect(url_for('center_index')) query = Center.query_by_state(state) try: pagination = Page(query, page, SYS_PAGE_COUNT) except AttributeError: pagination = Page(query, 1, SYS_PAGE_COUNT) context = {'pagination': pagination, 'state': state} return render_template("center/index.html", **context)
def shifts_by_city(city_id): """dada una ciudad devuelve los turnos totales por tipo de centro de la ciudad indicada, recibe el id de la ciudad. """ try: shifts_of_city = list( chain(*[c.shifts for c in Center.get_by_city(city_id)])) city_counts = list( map(lambda sh: sh.center.center_type, shifts_of_city)) return jsonify(Counter(city_counts)) except ValueError as e: msg, error_code = str(e), 404 return get_json_error_msg(error_msg=msg, error_code=error_code) except (OSError, ConnectionError) as e: return get_json_error_msg(error_code=500, error_msg="Error en el servidor", status="internal server error")
def search_by_name(): """Busca centros por nombre. Recibe name, que es un string, devuelve una lista paginada de centros """ try: name = thwart(request.args['args']) page = int(request.args['page']) except (BadRequestKeyError, ValueError) as e: flash("ERROR: {}".format(e), e) return redirect(url_for('center_index')) query = Center.query_by_name(name) try: pagination = Page(query, page, SYS_PAGE_COUNT) except AttributeError: # raised when page < 1 pagination = Page(query, 1, SYS_PAGE_COUNT) context = {'pagination': pagination, 'name': name} return render_template("center/index.html", **context)
def center_by_id(id): try: center = Center.find_by_id(id) dictCenter = { "name": center.name, "address": center.address, "phone": center.phone, "open_time": center.open_time.strftime("%H:%M"), "close_time": center.close_time.strftime("%H:%M"), "cente_type": center.center_type, "latitude": center.latitude, "longitude": center.longitude, "web": center.web, "email": center.email, } return jsonify(dictCenter) except Exception as e: return jsonify(detect_error(sys.exc_info()[0], e))
def create_view(center_id): """Recibe el id del centro al que pertenece el turno. Crea un turno siempre y cuando haya disponibilidad en el día elegido.""" form = CreateShiftForm() if form.validate(): shift = Shifts() form.populate_obj(shift) shift.center_id = center_id try: center = Center.get_by_id(shift.center_id) Shifts.create_shift(shift, center) flash("Turno agregado exitosamente", "success") except (NoResultFound, ValueError) as err: flash(err, "danger") if form.errors: display_errors(form.errors) return redirect(url_for("turnos_new", center_id=center_id)) return redirect(url_for("turnos_index", page=1))
def update_center(object_id): """ edita los atributos del centro con los datos obtenidos del formulario """ form = CreateCenterForm(request.form) if form.validate(): try: center = Center.get_by_id(object_id) except NoResultFound as e: flash(e, 'danger') return redirect(url_for("center_index")) form.populate_obj(center) center.protocol = request.files['protocol'].read() dbSession.commit() elif form.errors: display_errors(form.errors) flash("Error al validar formulario", "danger") return update_center_form(object_id) flash("se guardaron los cambios", "info") return redirect(url_for("center_index"))
def create(self, params): """Crea el turno, o en caso de error indica el problema""" center = Center.find_by_id(params["center_id"]) if center.status != "Aceptado": return ( "No se puede reservar turno de un centro que no esté aceptado", "danger", ) fecha = params["day"] if self.validarFecha(self, fecha): turn = Turn(params) base.session.add(turn) base.session.commit() return ("Se creó el turno", "success") else: return ( "No se puede crear un turno en una fecha anterior al día de hoy", "danger", )
def search_by_center_name(): """Busca turnos por nombre de centro. Recibe center_name(string), y numero de pagina, devuelve un template de lista de turnos(Shifts)""" try: center_name = thwart(request.args['center_name']) page = int(request.args['page']) if page < 0: flash("El número de página debe ser mayor o igual a 1.") return redirect(url_for('turnos_index')) except (BadRequestKeyError, ValueError) as e: flash("ERROR: {}".format(e), e) return redirect(url_for('turnos_index')) c = Center.get_by_name(center_name) pagination = Shifts.search_by_center_name_paginated(c, page) search_donor_form = SearchDonorEmailForm() return render_template("shifts/index.html", pagination=pagination, shifts=True, center_name=center_name, search_donor_form=search_donor_form)
def update(self, params): """Actualiza la información de un turno""" center = Center.find_by_id(params["center_id"]) if center.status != "Aceptado": return ( "No se puede modificar un turno de un centro que no esté aceptado", "danger", ) fecha = params["day"] if self.validarFecha(fecha): self.email_request = params["email"] self.day = params["day"] self.num_block = params["num_block"] self.time = self.hour_dict( params["num_block"] ) # le paso el nuevo bloque actualizando la nueva hora self.phone = params["phone"] base.session.commit() return ("Se actualizó el turno", "success") else: return ("Los datos no son válidos", "danger")
def change_state(method, message): try: center_id = request.args['object_id'] except BadRequestKeyError: flash("ERROR: id Centro no recibido", "danger") return redirect(url_for("center_index")) try: center = Center.get_by_id(center_id) except NoResultFound as e: flash(e, 'danger') return redirect(url_for("center_index")) try: getattr(center, method)() except IntegrityError: flash('hubo un problema en la transacción', 'danger') return redirect(url_for("center_index")) except AttributeError as e: flash(e, 'danger') return redirect(url_for("center_index")) flash(message.format(center.name), "info") return redirect(url_for("center_index"))
def avalaible_by_date(id): """Devuelve los turnos disponibles para el centro x. Parametro opcional: fecha. Si no recibe fecha, fecha=actual. """ try: fecha = datetime.strptime(request.args['fecha'], '%Y-%m-%d').date() center = Center.get_by_id(id) # fecha2 = datetime.strptime("2020-12-13", '%Y-%m-%d').date() # if fecha == fecha2: # return get_json_error_msg(center_info={"centro_id": center.id, "fecha": fecha.isoformat()}, # status="shifts not available", error_code=404, # error_msg="no hay turnos disponibles".format(center.id)) if center.published is False: raise ValueError("centro id={} no se encuentra activo".format( center.id)) # podria implementarse en el metodo except (ValueError, NoResultFound, BadRequestKeyError) as e: app.logger.info(traceback.format_exc()) msg, error_code = str(e), 404 if type(e) == BadRequestKeyError: msg, error_code = "error: fecha no recibida", 422 return get_json_error_msg(error_msg=msg, error_code=error_code) except Exception as e: app.logger.info(traceback.print_exc()) return get_json_error_msg(error_code=500, error_msg="Error en el servidor", status="internal server error") turnos = center.get_shifts_blocks_avalaible(fecha) if turnos: return get_json_turnos(turnos=turnos, fecha=fecha, centro_id=center.id), 200 return get_json_error_msg(center_info={ "centro_id": center.id, "fecha": fecha.isoformat() }, status="shifts not available", error_code=404, error_msg="no hay turnos disponibles".format( center.id))
def new(): """ Vista de creacion de un centro de ayuda, devuelve la vista en el metodo GET o valida en el metodo POST, si la validacion es correcta guarda el centro en la base, si no flashea mensajes de error de las validaciones que fallaron """ if (request.method == 'POST'): if not (check_token(request.form["csrf_token"])): return render_template( 'centers/new.html', center_types=Type.query.order_by(Type.name).all(), ) form = request.form nuevo_centro = Center( name=form['nombre-centro'], address=form['direccion'], phone_number=form['phone'], opens_at=f"{form['opens_at_hour']}:{form['opens_at_min']}", close_at=f"{form['close_at_hour']}:{form['close_at_min']}", municipio=form["muni"], coordinates=f"{form['lat']},{form['lng']}") nuevo_centro.types.append( Type.query.filter_by(name=form["tipo"]).first()) if "email" in form: nuevo_centro.email = form["email"] if "web" in form: nuevo_centro.web = form["web"] if "publication_state" in form: nuevo_centro.publication_state = True # Solo pueden acceder usuarios con permisos estado = State.query.filter_by(name="Aprobado").first() estado.centers.append(nuevo_centro) msj = "Centro cargado correctamente." try: if request.files["protocolo"]: # Validate and save si tiene pdf nuevo_centro.validate_and_save(pdf=request.files["protocolo"]) save_pdf_file(request.files["protocolo"], nuevo_centro.protocolo) else: # Validate and save si no tiene pdf nuevo_centro.validate_and_save() flash(msj, "success") return redirect(url_for('centers.index')) except AssertionError as e: flash_messages(str(e)) return render_template( 'center/new.html', last_form=request.form, center_types=Type.query.order_by(Type.name).all(), ) return redirect('/center') else: # method=GET CSRF_TOKEN = generate_token() return render_template( '/center/new.html', center_types=Type.query.order_by(Type.name).all(), CSRF_TOKEN_STRING=CSRF_TOKEN, )
def centers_by_type(): centros = Center.return_centers_by_type_API_Data() return jsonify(centros)
def new(): """ Crea un centro con los datos recibidos en formato Json a traves de POST """ json = request.get_json(force=True) errors = validate_json_center(json) if errors: abort(400, f"El JSON no es valido, {errors}") url = "https://api-referencias.proyecto2020.linti.unlp.edu.ar/" munis = requests.get(url + "municipios?per_page=300") if munis.status_code != 200: abort(500) if "id" in json["municipio"]: pos = "id" search = json["municipio"]["id"] else: pos = "name" search = json["municipio"]["nombre"] found = False for m in munis.json()["data"]["Town"].values(): if search == m[pos]: found = True id = m["id"] name = m["name"] if not found: return jsonify(messages="El municipio no se encontro"), 400 new_center = Center( name=json["nombre"], address=json["direccion"], phone_number=json["telefono"], opens_at=json["hora_apertura"], close_at=json["hora_cierre"], web=json["web"], email=json["email"], publication_state=False, municipio=str(id), coordinates=( str(json["coordenadas"][0]) + "," + str(json["coordenadas"][1]) ) ) try: tipo = Type.query.filter_by(name=json["tipo"]).first() if not tipo: tipos = [tipo.name for tipo in Type.query.all()] error = "no existe el tipo indicado en la aplicación," error += " los tipos que existen son: " for tipo in tipos: error += " " + tipo + "," raise AssertionError(error) new_center.types.append(tipo) state = State.query.filter_by(name="Pendiente").first() state.centers.append(new_center) new_center.validate_and_save() dic = { "id": new_center.id, "nombre": new_center.name, "direccion": new_center.address, "telefono": new_center.phone_number, "hora_apertura": new_center.opens_at.isoformat()[0:-3], "hora_cierre": new_center.close_at.isoformat()[0:-3], "tipo": new_center.types[0].name, "web": new_center.web, "email": new_center.email, "coordenadas": json["coordenadas"], "municipio": { "id": id, "name": name } } return jsonify(atributos=dic), 201 except AssertionError as err: return jsonify(messages=str(err)[0:-1]), 400