def signin(): # IF its GET request, display the page if request.method == "GET": return render_template("signin.html", title="Application :: Sign In") # Getting JSON data data = request.get_json() # Checking the request if "email" not in data or "pass" not in data: abort(safeglobals.http_bad_request, {"message": safeglobals.error_mandatory_missing}) # Checking that this admin exists admin = Administrator.query.filter_by(email=data['email']).first() if not admin or not admin.verify_password(data['pass']): abort(safeglobals.http_forbidden, {'message': safeglobals.error_access_denied}) # Generating a token and put into session admin.generate_session_key() db_session.commit() session['token'] = admin.session_key # Sending response '''return jsonify(status=safeglobals.http_ok,\ user=admin.name,\ email=admin.email,\ org=admin.orgs.name,\ evaluate_to=time.mktime(admin.orgs.evaluate_to.timetuple()),\ expires_in=time.mktime(admin.orgs.expires_in.timetuple()))''' return jsonify(status=safeglobals.http_ok)
def bloqueo_cancha(): form = BloqueoCanchaForm(request.form) canchas = Cancha.query.with_entities(Cancha.idcancha, Cancha.nombre).order_by(Cancha.nombre.asc()).all() #Carga los Choices (dropdowns) form.tipo.choices = getTipoReservas() form.cancha.choices = canchas horas = getHoras() form.hora_inicio.choices = horas.iteritems() form.hora_fin.choices = horas.iteritems() #and cform.validate() if request.method == 'POST': #Chequear si hay reservas en el rango usuario = Usuario.query.filter(Usuario.usuario == session.get('user_id')).first() reserva = Reserva(form.tipo.data, formatFecha(form.fecha_inicio.data, FECHA_BASE), horas[int(form.hora_inicio.data)], formatFecha(form.fecha_fin.data, FECHA_BASE), horas[int(form.hora_fin.data)], form.cancha.data, usuario.idsocio, form.descripcion.data) try: db_session.add(reserva) db_session.commit() return redirect(url_for('index')) except exc.SQLAlchemyError: flash("Error: No se ha agregado la reserva", "error") tomorrow = datetime.date.today() + datetime.timedelta(days = 1) form.fecha_inicio.data = formatFecha(tomorrow, FECHA_SOLA) form.fecha_fin.data = formatFecha(tomorrow, FECHA_SOLA) return render_template('admin/bloqueo_cancha.html', form=form)
def new(): company_id = g.user.company_id start_date = request.form.get('start_date') end_date = request.form.get('end_date') turbine = request.form.get('turbine') component = request.form.get('component') reason = request.form.get('reason') note = request.form.get('note') if not all([start_date, end_date, turbine, component]): return handle_error(400, 'Invalid form have been filled') new_maintenance = MaintenanceEvent(company_id=company_id, start_date=start_date, end_date=end_date, turbine=turbine, component=component, reason=reason, note=note) db_session.add(new_maintenance) db_session.commit() return redirect(url_for('maintenance.index'))
def edit_reserva(id): reserva = Reserva.query.filter(Reserva.idreserva == id).first() if reserva is None: return redirect(url_for('reservas.add_reserva')) socio = Socio.query.filter(Socio.idsocio == reserva.idsocio).first() una_cancha = Cancha.query.filter(Cancha.idcancha == reserva.idcancha).first() list_oponentes = ReservaSocio.query.join(Socio, ReservaSocio.idsocio==Socio.idsocio)\ .filter(ReservaSocio.idreserva == id)\ .with_entities(ReservaSocio.idreserva, ReservaSocio.idsocio, Socio.nombre).all() reserva_mem = {'fecha': formatFecha(reserva.fecha, FECHA_LARGA), 'hora': reserva.hora + " - " + reserva.hora_fin, 'idcancha': reserva.idcancha, 'cancha': una_cancha.nombre, 'socio': socio.nombre, 'idsocio': socio.idsocio } form = ReservaForm2(request.form) if request.method == 'POST': reserva.descripcion = form.descripcion.data db_session.commit() return redirect(url_for(session.get('pag_actual'))) form = ReservaForm2(request.form, descripcion=reserva.descripcion) return render_template('reservas/edit_reserva.html', form=form, id=id, reserva=reserva_mem, oponentes=list_oponentes)
def delete_socio(id): socio = Socio.query.filter(Socio.idsocio == id).first() if socio.idsocio > 0: # ARREGLAR db_session.delete(socio) db_session.commit() return redirect(url_for("socios.view_socios"))
def delete_reserva(id): reserva = Reserva.query.filter(Reserva.idreserva == id).first() if reserva.idreserva > 0: #ARREGLAR db_session.delete(reserva) db_session.commit() return redirect(url_for(session.get('pag_actual')))
def add_user(): uform = UsuarioForm(request.form) sform = SocioForm(request.form) if request.method == "POST" and uform.validate() and sform.validate(): socio = Socio( sform.tipo.data, sform.nombre.data, sform.telefono.data, sform.celular.data, sform.direccion.data, sform.ciudad.data, sform.cp.data, ) try: db_session.add(socio) db_session.flush() usuario = Usuario(uform.usuario.data, uform.email.data, uform.contrasena.data, socio.idsocio) db_session.add(usuario) db_session.commit() return redirect(url_for("index")) except exc.SQLAlchemyError: flash("Error: No se ha agregado el Socio", "error") form = LoginForm() return render_template("socios/register2.html", uform=uform, sform=sform, form=form)
def sign_in(): # Checking the request data = request.get_json() if "email" not in data or "pass" not in data: abort(400, {"message": "Mandatory information missing"}) # Getting the user with the specified email user = CommonUser.query.filter_by(email=data['email']).first() if not user or not user.verify_password(data['pass']): abort(403, {'message': 'User not found'}) # Creating token token = Token(user.generate_auth_token()) token.user = user # Deleting previous token Token.query.filter_by(uid=user.id).delete() # Inserting token into database db_session.add(token) db_session.commit() # Sending response return jsonify(token=token.token)
def add_org(): admin = None user = None data = request.get_json() if "name" not in data or "email" not in data or "admin" not in data or "pass" not in data: abort(400) # First, we need to check if there are already users with this email admin = Administrator.query.filter_by(email=data['email']).first() if admin is not None: abort(409) user = CommonUser.query.filter_by(email=data['email']).first() if user is not None: abort(409) # Creating new organization, add administrator and user org = Organization(data['name']) admin = Administrator(name=data['admin'], email=data['email']) user = CommonUser(name=data['admin'], email=data['email']) admin.hash_password(data['pass']) user.hash_password(data['pass']) org.administrators.append(admin) org.users.append(user) db_session.add(org) db_session.add(admin) db_session.add(user) db_session.commit() return jsonify(status="ok")
def delete(maintenance_id): maintenance_event = MaintenanceEvent.get_by_id(maintenance_id) if maintenance_event: db_session.delete(maintenance_event) db_session.commit() return redirect(url_for('maintenance.index'))
def delete_cancha(id): cancha = Cancha.query.filter(Cancha.idcancha == id).first() print cancha if cancha.idcancha > 0: #ARREGLAR print cancha.idcancha db_session.delete(cancha) db_session.commit() return redirect(url_for('canchas.view_canchas'))
def put(self, email, postcode): # Check availability: existed_user = db_session.query( models.User).filter_by(email=email).first() if existed_user: if existed_user.status: return dict(result="ok", message="user is already active") existed_user.status = True db_session.add(existed_user) db_session.commit() taks.emailAgent.delay( email, "Coronavirus Map Account Reactivation", f""" You requested to reactivate your notification account, please click on the link bellow to reactivate your account. {c.PROTOCOL}://{c.DOMAIN}:{c.PORT}/api/v1/activate/{existed_user.token} If you are not requested this action, please ignore this email. -- Be Safe. """, ) return dict(result="ok", message="User already registered. Reactivated again") else: # Check postcode availabitity: postcode_obj = (db_session.query( models.Postcode).filter_by(postcode=postcode).first()) if not postcode_obj: return dict(result="error", message="Postcode is not valid") else: new_user = models.User(email, postcode=postcode_obj, status=True) db_session.add(new_user) db_session.commit() tasks.emailAgent.delay( email, "Welcome to Coronavirus Map Notifications", f""" Welcome. To complete your registeration process, please click on the link bellow: {c.PROTOCOL}://{c.DOMAIN}:{c.PORT}/api/v1/activate/{new_user.token} If you are not requested this action, please ignore this email. -- Be Safe. """, ) return dict(result="ok", message="User registered successfully")
def edit(alert_id): note = request.form.get('note') alert = Alert.query.filter(Alert.id==alert_id).one_or_none() alert.note = note db_session.add(alert) db_session.commit() return redirect(url_for('alerts.index'))
def get(self, token): u = db_session.query(models.User).filter_by(token=token).first() if not u: return "Token is invalid" else: u.token = uuid4().hex u.status = False db_session.add(u) db_session.commit() return "User deactivated"
def sign_up(): if request.method == "GET": return render_template("signup.html", title="Application :: Sign Up") else: data = request.get_json() try: if not data['name'] or not data['email'] or not data[ 'pass'] or not data['plan'] or not data['admin']: abort(safeglobals.http_bad_request, {'message': safeglobals.error_mandatory_missing}) except KeyError: abort(safeglobals.http_bad_request, {'message': safeglobals.error_mandatory_missing}) # Checking that no user with this "email" already exists user = Administrator.query.filter_by(email=data['email']).first() if user is not None: abort(safeglobals.http_conflict, {'message': safeglobals.error_account_exists}) user = CommonUser.query.filter_by(email=data['email']).first() if user is not None: abort(safeglobals.http_conflict, {'message': safeglobals.error_account_exists}) # Creating new Administrator admin = Administrator(data['admin'], data['email']) admin.hash_password(data['pass']) # Getting all services services = Service.query.all() # Common user user = CommonUser(data['admin'], data['email']) user.hash_password(data['pass']) user.services = services # Creating a plan plan = Plan.query.get(data['plan']) # Creating organization org = Organization(data['name']) org.administrators.append(admin) org.users.append(user) org.plan = plan org.set_expiration_values(data['plan']) org.set_premium(data['plan']) db_session.add(org) db_session.add(admin) db_session.add(user) db_session.commit() return jsonify( status=safeglobals.http_created), safeglobals.http_created
def init_database(): init_db() # Creating plans plans = [Plan("Free",False),Plan("Basic",False),Plan("Premium",True)] # Creating services services = [Service(name="Evernote"),Service(name="Onenote")] db_session.add_all(plans) db_session.add_all(services) db_session.commit() return jsonify(status="ok")
def verify_auth_token(token): s = Serializer(SECRET_KEY) try: data = s.loads(token) except SignatureExpired: return None except BadSignature: return None user = db_session.query(User).get(data['id']) db_session.commit() return user
def add_products(): db_session.add( Product('Computer', 15, 'Xiaomi Laptop very convenient and easy to use', 'laptop.jpeg')) db_session.add( Product( 'Mobile', 10, 'This model of Samsung Galaxy Note8 is luxurious and trendy this season', 'note8.jpeg')) db_session.add( Product('Watch', 5, 'Xiaomi Laptop very convenient and easy to use', 'watch.jpg')) db_session.commit() return "Items added..."
def save_data(data): init_db() request = Request() request.distance_imbalance = data['calculate'] user_location = Location() user_location.latitude = data['user_location']['latitude'] user_location.longitude = data['user_location']['latitude'] request.location = user_location request.radius = data['radius'] medical_centers = [ build_medical_center(medical_center, request) for medical_center in data['medical_centers'] ] request.medical_centers = medical_centers db_session.add(request) db_session.commit()
def edit_cancha(id): cancha = Cancha.query.filter(Cancha.idcancha == id).first() cform = CanchaForm(request.form) if request.method == 'POST' and cform.validate(): #---Upload File ---------------------------------- if 'foto' in request.files: foto=upload_file(request.files['foto']) #-------------------------------------------------- cancha.nombre = cform.nombre.data cancha.descripcion = cform.descripcion.data cancha.foto = foto db_session.commit() return redirect(url_for('canchas.view_canchas')) cform = CanchaForm(request.form, nombre=cancha.nombre, descripcion=cancha.descripcion) return render_template('admin/edit_cancha.html', cform=cform, id=id)
def book_reserva(): form = ReservaForm(request.form) usuario = Usuario.query.filter(Usuario.usuario == session['user_id']).first() #and form.validate() if request.method == 'POST': #Cargar idSocio dependiendo si es agregado por el Admin o por el Socio if len(request.form['idsocio']) > 0: vsocio = request.form['idsocio'] else: vsocio = usuario.idsocio tipo = 1 hora_fin = addMinutos(form.hora.data, form.tiempo.data) reserva = Reserva(tipo, formatFecha(form.fecha2.data, FECHA_BASE), form.hora.data, formatFecha(form.fecha2.data, FECHA_BASE), hora_fin, form.idcancha.data, vsocio, form.descripcion.data) try: db_session.add(reserva) db_session.flush() #Grabar Oponentes #Aviso: Un Admin no puede agregarse como Oponente #----------------------------------------------------------------------- for field in request.form: if field[:5] == 'ctlid' and len(request.form[field]) > 0 and request.form[field] != reserva.idsocio: oponente = ReservaSocio(reserva.idreserva, request.form[field]) try: db_session.add(oponente) except exc.SQLAlchemyError: flash("Error: No se ha agregado el Oponente", "error") #----------------------------------------------------------------------- db_session.commit() return redirect(url_for(session['pag_actual'])) except exc.SQLAlchemyError: flash("Error: No se ha agregado la reserva", "error") reserva = {'fecha': formatFecha(form.fecha2.data, FECHA_LARGA), 'hora': form.hora.data, 'idcancha': form.idcancha.data, 'cancha': form.cancha.data, 'socio': form.socio.data, 'idsocio': form.idsocio.data } form.tiempo.choices = getTiemposReserva() return render_template('reservas/book_reserva.html', form=form, reserva=reserva)
def run(self, company_id, turbine_id, end_date, window_delta, es_history_config, es_probability_config, es_rul_config, components_definitions, **kwargs): kpi_calculator = KpiCalculator(es_history_config, turbine_id, end_date) kpi = kpi_calculator.get_kpi() window_delta = datetime.timedelta(hours=window_delta) performance_metrics = PerformanceMetrics(es_probability_config, es_rul_config, end_date, window_delta, turbine_id) metrics = performance_metrics.get_performance_metrics('global_model') windfarm_health_score = WindFarmHealthScore(company_id=company_id) turbine_health = TurbineHealth( company_id=company_id, turbine_id=turbine_id, windfarm_health=windfarm_health_score, healthscore=metrics.healthscore, availability=kpi.availability, efficiency=kpi.capacity_factor, time_between_failures=kpi.time_between_failures.seconds / 60, estimated_residual_time=metrics.residual_time, estimated_cost_of_repair=metrics.cost_of_repair, downtime=metrics.downtime, revenue_loss=metrics.revenue_loss, failure_cost=metrics.failure_cost) list_of_components = [] for component in components_definitions: component_metrics = performance_metrics.get_performance_metrics( component.id) list_of_components.append( ComponentHealth(company_id=company_id, component_id=component.id, component_name=component.name, score=component_metrics.healthscore)) db_session.add(turbine_health) db_session.commit() return turbine_health
def edit_socio(id): print id usuario = Usuario.query.filter(Usuario.usuario == id).first() if usuario is None: return redirect(url_for("index")) socio = Socio.query.filter(Socio.idsocio == usuario.idsocio).first() uform = UsuarioForm2(request.form) sform = SocioForm(request.form) if request.method == "POST" and uform.validate() and sform.validate(): socio.tipo = sform.tipo.data socio.nombre = sform.nombre.data socio.telefono = sform.telefono.data socio.celular = sform.celular.data socio.ciudad = sform.ciudad.data socio.direccion = sform.direccion.data socio.cp = sform.cp.data usuario.usuario = uform.usuario.data usuario.email = uform.email.data db_session.commit() if usuario.usuario != id: session["user_id"] = usuario.usuario return redirect(url_for("index")) uform = UsuarioForm2(request.form, usuario=usuario.usuario, email=usuario.email) sform = SocioForm( request.form, tipo=socio.tipo, nombre=socio.nombre, telefono=socio.telefono, celular=socio.celular, ciudad=socio.ciudad, direccion=socio.direccion, cp=socio.cp, ) # form = LoginForm() # , cform=form return render_template("socios/edit_socio.html", uform=uform, sform=sform, id=id)
def add_cancha(): if session['admin'] != 1: return redirect(url_for('page_restricted')) cform = CanchaForm(request.form) foto=Config.DEFAULT_CANCHA_PICTURE if request.method == 'POST' and cform.validate(): #---Upload File ---------------------------------- if 'foto' in request.files: filename = secure_filename(request.files['foto'].filename) foto=upload_file(request.files['foto']) #-------------------------------------------------- cancha = Cancha(cform.nombre.data, cform.descripcion.data, foto) try: db_session.add(cancha) db_session.commit() return redirect(url_for('canchas.view_canchas')) except exc.SQLAlchemyError: flash("Error: No se ha agregado la Cancha", "error") return render_template('admin/add_cancha.html', cform=cform)
def create_user(): # Getting JSON data data = request.get_json() # Checking request if "name" not in data or "email" not in data or "pass" not in data: abort(safeglobals.http_bad_request,{"message":safeglobals.error_mandatory_missing}) # Checking if user already exists user = CommonUser.query.filter_by(email=data['email']).first() if user is not None: abort(safeglobals.http_conflict,{"message":safeglobals.error_account_exists}) # Getting Organization ID admin = Administrator.query.filter_by(session_key=session['token']).first() # Creating new user user = CommonUser(data['name'],data['email']) user.hash_password(data['pass']) user.org = admin.org services = [] result = None # Setting services for service in data['services']: if service['enabled'] == True: result = Service.query.get(service['id']) if result is not None: services.append(result) user.services = services # Adding user to database db_session.add(user) db_session.commit() # Sending response return jsonify(status=safeglobals.http_created)
def get_postcodes(): """Downloads postcodes from URL and parses it :returns: dataframe """ if r.get("POSTCODES_RETRIVAL_LOCK") == 1: return "LOCKED" r.set("POSTCODES_RETRIVAL_LOCK", 1) content = requests.get(POSTCODES_URL) zf = ZipFile(BytesIO(content.content)) for item in zf.namelist(): print("file in zip: " + item) match = [s for s in zf.namelist() if ".csv" in s][0] df = pandas.read_csv(zf.open(match), low_memory=False) for i in df.itertuples(): p = Postcode(i.postcode, i.latitude, i.longitude) db_session.add(p) print(p) d = db_session.commit() r.delete("POSTCODES_RETRIVAL_LOCK") return df
def save_url(img_dict): img = Image(img_dict["link"]) db_session.add(img) db_session.commit()
from models.base import Base from core.database import engine, db_session from models.user import User Base.metadata.create_all(engine) # Initial user u = User(login="******", password="******", first_name="John", last_name="Doe") db_session.add(u) db_session.commit()