How to use get_properties method in Playwright Python

Best Python code snippet using playwright-python

routes.py

Source:routes.py Github

copy

Full Screen

1from flask import render_template,flash, request, url_for, redirect, session, abort, g2from functools import wraps3from main.models.adm import *4from main.models.properties import *5from main.models.subscribers import *6from main.propertyForm import SeguridadForm,ComfortForm,PropertyForm7from main import app8from datetime import date,timedelta 9import logging 10import os11import random12import io13import base6414import math 15from PIL import Image16import cProfile, pstats, io17def profile(fnc):18 19 """A decorator that uses cProfile to profile a function"""20 21 def inner(*args, **kwargs):22 23 pr = cProfile.Profile()24 pr.enable()25 retval = fnc(*args, **kwargs)26 pr.disable()27 s = io.StringIO()28 sortby = 'cumulative'29 ps = pstats.Stats(pr, stream=s).sort_stats(sortby)30 ps.print_stats(.5)31 with open('C:/Users/Santi/Desktop/Inmobiliaria/main/p_optimize.log.txt', 'w+') as f:32 f.write(str(date.today()) + f'/n' + s.getvalue())33 print(s.getvalue())34 return retval35 return inner36#logging.basicConfig(filename='p_optimize.log', level=logging.DEBUG)37# from flask_mail import Mail, Message38# mail_data = MainMail.query.first()39# if mail_data != None:40# app.config['MAIL_SERVER'] = 'smtp.googlemail.com'41# app.config['MAIL_PORT'] = 2542# app.config['MAIL_USE_TLS'] = True43# app.config['MAIL_USERNAME'] = str(mail_data.mail) # enter your email here44# app.config['MAIL_DEFAULT_SENDER'] = str(mail_data.mail) # enter your email here45# app.config['MAIL_PASSWORD'] = str(mail_data.mail_password) # enter your password here46# else:47# app.config['MAIL_SERVER'] = 'smtp.googlemail.com'48# app.config['MAIL_PORT'] = 2549# app.config['MAIL_USE_TLS'] = True50# app.config['MAIL_USERNAME'] = 'nomail@gmail.com' # enter your email here51# app.config['MAIL_DEFAULT_SENDER'] = 'nomail@gmail.com' # enter your email here52# app.config['MAIL_PASSWORD'] = 'xxxx' # enter your password here53# print(app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])54# mail = Mail(app)55# def sort_imgs():56# os.chdir(imgs_dir)57# properties = os.listdir()58# for f in properties:59# os.chdir(imgs_dir + '/' + f)60# imgs = os.listdir()61# imgs.sort(key=lambda x: x[1:])62# print(imgs)63# @app.before_request64# def caca():65# sort_imgs()66imgs_dir = os.getcwd() + '/main/static/imgs/'67def properties_mtx(properties, columns):68 print(imgs_dir)69 aux = []70 p_show = []71 for i,propiedad in enumerate(properties):72 foto = get_img(propiedad.ref)73 aux.append([propiedad,foto])74 #print((i+1)%columns)75 if ((i+1)%columns) == 0:76 p_show.append(aux)77 aux = []78 if aux != []:79 p_show.append(aux) 80 #print(p_show[0])81 return p_show82def store_imgs(ref,imgs):83 os.chdir(imgs_dir)84 os.mkdir(ref)85 os.chdir(ref)86 print(os.getcwd())87 for i,img in enumerate(imgs):88 fext = img.filename.split('.')89 im = Image.open(img).save(str(i+1) + '.' + fext[-1])90def add_imgs(path_ref,img,id):91 im = Image.open(img).save(path_ref + '/' + str(id))92def del_imgs(ref,id):93 id = [int(i) for i in id]94 id.sort()95 f = []96 f_aux = []97 wrk_path = imgs_dir + ref + '/'98 imgs = os.listdir(wrk_path)99 imgs.sort(key=lambda x: x[1:])100 imgs = imgs[id[0]-1:]101 init_imgs = len(imgs)102 print(init_imgs,imgs,id)103 for j in range(init_imgs):104 f.append(os.path.splitext(wrk_path + imgs[j]))105 print(f)106 for delete_offset,i in enumerate(id):107 idx_mapping = i-id[0]-delete_offset108 print(idx_mapping,f[idx_mapping][0])109 init_imgs -= 1110 os.remove(f[idx_mapping][0]+f[idx_mapping][1])111 for j in range(idx_mapping,init_imgs):112 os.rename(f[j+1][0] + f[j+1][1], f[j][0] + f[j+1][1])113 return True114def get_imgs(ref):115 prop_phs = []116 os.chdir(imgs_dir + ref)117 imgs = os.listdir()118 for i in imgs:119 ph = open(i,'rb')120 im = base64.b64encode(ph.read()).decode('utf-8')121 ph.close()122 prop_phs.append(im)123 return prop_phs124def get_img(ref):125 os.chdir(imgs_dir + ref +'/')126 imgs = os.listdir()127 print(imgs)128 if (len(imgs) > 0):129 ph = open(imgs[0],'rb')130 im = base64.b64encode(ph.read()).decode('utf-8')131 ph.close()132 else:133 os.chdir(imgs_dir)134 ph = open('default.png','rb')135 im = base64.b64encode(ph.read()).decode('utf-8')136 ph.close()137 return im138def is_number(num_input):139 try:140 float(num_input)141 return True142 except ValueError:143 pass144 try:145 import unicodedata146 unicodedata.numeric(num_input)147 return True148 except (TypeError, ValueError):149 pass150 return False151@app.before_request152def get_current_user():153 g.user = None154 username = session.get('username')155 if username is not None:156 g.user = username157def login_required(f):158 @wraps(f)159 def decorated_function(*args, **kwargs):160 if g.user is None:161 return redirect(url_for('login_page', next=request.url))162 return f(*args, **kwargs)163 return decorated_function164#ROUTES -------------------------------165def assign_properties_to_from(form,get_properties):166 form.nombre.data = get_properties.propietario.nombre167 form.apellido.data = get_properties.propietario.apellido168 form.email.data = get_properties.propietario.email169 form.telefono.data = get_properties.propietario.telefono170 form.barrio.data = get_properties.barrio.barrio171 form.destacado.data = get_properties.destacado172 form.operacion.data = get_properties.operaciones.operacion173 form.tipo_propiedad.data = get_properties.tipo_propiedad.tipo_propiedad174 form.titulo.data = get_properties.titulo175 form.direccion.data = get_properties.direccion176 form.permuta.data = get_properties.permuta177 form.financia.data = get_properties.financia178 form.ref.data = get_properties.ref179 form.distancia_al_mar.data = get_properties.distancia_al_mar180 form.descripcion.data = get_properties.descripcion181 form.precio_dolares.data = get_properties.precio_dolares182 form.precio_pesos.data = get_properties.precio_pesos183 form.metraje_edificio.data = get_properties.metraje_edificio184 form.metraje_patio.data = get_properties.metraje_patio185 form.baños.data = get_properties.baños186 form.dormitorios.data = get_properties.dormitorios187 form.permuta.data = get_properties.permuta188 form.financia.data = get_properties.financia189 form.garaje.data = get_properties.garaje190 form.estado.data = get_properties.estado191 form.orientacion.data = get_properties.orientacion192 form.disposicion.data = get_properties.disposicion193 form.n_plantas.data = get_properties.n_plantas194 form.comfort.agua_caliente.data = get_properties.comfort[0].agua_caliente195 form.comfort.aire_acondicionado.data = get_properties.comfort[0].aire_acondicionado196 form.comfort.altillo.data = get_properties.comfort[0].altillo197 form.comfort.amueblada.data = get_properties.comfort[0].amueblada198 form.comfort.balcón.data = get_properties.comfort[0].balcón199 form.comfort.barbacoa.data = get_properties.comfort[0].barbacoa200 form.comfort.box.data = get_properties.comfort[0].box201 form.comfort.bungalow.data = get_properties.comfort[0].bungalow202 form.comfort.calefacción.data = get_properties.comfort[0].calefacción203 form.comfort.depósito.data = get_properties.comfort[0].depósito204 form.comfort.dormitorio_de_servicio.data = get_properties.comfort[0].dormitorio_de_servicio205 form.comfort.estufa_leña.data = get_properties.comfort[0].estufa_leña206 form.comfort.garaje.data = get_properties.comfort[0].garaje207 form.comfort.gas_por_cañería.data = get_properties.comfort[0].gas_por_cañería208 form.comfort.gym.data = get_properties.comfort[0].gym209 form.comfort.instalación_de_tv_cable.data = get_properties.comfort[0].instalación_de_tv_cable210 form.comfort.jacuzzi.data = get_properties.comfort[0].jacuzzi211 form.comfort.jardín.data = get_properties.comfort[0].jardín212 form.comfort.lavadero.data = get_properties.comfort[0].lavadero213 form.comfort.lavandería.data = get_properties.comfort[0].lavandería214 form.comfort.linea_blanca.data = get_properties.comfort[0].linea_blanca215 form.comfort.living_comedor.data = get_properties.comfort[0].living_comedor216 form.comfort.losa_radiante.data = get_properties.comfort[0].losa_radiante217 form.comfort.parrillero.data = get_properties.comfort[0].parrillero218 form.comfort.patio.data = get_properties.comfort[0].patio219 form.comfort.piscina.data = get_properties.comfort[0].piscina220 form.comfort.piso_porcelanato.data = get_properties.comfort[0].piso_porcelanato221 form.comfort.placard_en_la_cocina.data = get_properties.comfort[0].placard_en_la_cocina222 form.comfort.placard_en_dormitorio.data = get_properties.comfort[0].placard_en_dormitorio223 form.comfort.playroom.data = get_properties.comfort[0].playroom224 form.comfort.previsión_aa.data = get_properties.comfort[0].previsión_aa225 form.comfort.sauna.data = get_properties.comfort[0].sauna226 form.comfort.sótano.data = get_properties.comfort[0].sótano227 form.comfort.terraza.data = get_properties.comfort[0].terraza228 form.comfort.terraza_lavadero.data = get_properties.comfort[0].terraza_lavadero229 form.comfort.vista_al_mar.data = get_properties.comfort[0].vista_al_mar230 form.comfort.vestidor.data = get_properties.comfort[0].vestidor231 form.comfort.walkin_closet.data = get_properties.comfort[0].walkin_closet232 form.comfort.wifi.data = get_properties.comfort[0].wifi233 form.seguridad.alarma.data = get_properties.seguridad[0].alarma234 form.seguridad.cámaras_cctv.data = get_properties.seguridad[0].cámaras_cctv235 form.seguridad.cerca_perimetral.data = get_properties.seguridad[0].cerca_perimetral236 form.seguridad.portería_24hs.data = get_properties.seguridad[0].portería_24hs237 form.seguridad.portón_eléctrico.data = get_properties.seguridad[0].portón_eléctrico238 form.seguridad.rejas.data = get_properties.seguridad[0].rejas239 form.seguridad.guardia_de_seguridad.data = get_properties.seguridad[0].guardia_de_seguridad240 return form241def assign_form_to_properties(get_property,form):242 barrio = Barrios.query.filter_by(barrio = form.data['barrio']).first()243 operacion = Operaciones.query.filter_by(operacion = form.data['operacion']).first()244 tipo_propiedad = Tipo_propiedad.query.filter_by(tipo_propiedad = form.data['tipo_propiedad']).first()245 get_property.destacado = form.data['destacado']246 get_property.ref = form.data['ref']247 get_property.propietario.nombre = form.data['nombre']248 get_property.propietario.apellido = form.data['apellido']249 get_property.propietario.email = form.data['email']250 get_property.propietario.telefono = form.data['telefono'] 251 get_property.operacion_id = operacion.id 252 get_property.fecha_publicacion = date.today() 253 get_property.tipo_propiedad_id = tipo_propiedad.id 254 get_property.barrio_id = barrio.id 255 get_property.titulo = form.data['titulo'] 256 get_property.direccion = form.data['direccion'] 257 get_property.descripcion = form.data['descripcion'] 258 get_property.precio_dolares = abs(form.data['precio_dolares']) if form.data['precio_dolares'] else None 259 get_property.precio_pesos = abs(form.data['precio_pesos']) if form.data['precio_pesos'] else None 260 get_property.metraje_edificio = form.data['metraje_edificio'] 261 get_property.metraje_patio = form.data['metraje_patio'] 262 get_property.metraje_total = form.data['metraje_edificio'] if form.data['metraje_patio'] is None else form.data['metraje_edificio'] + form.data['metraje_patio'] 263 get_property.baños = form.data['baños'] 264 get_property.dormitorios = form.data['dormitorios'] 265 get_property.permuta = form.data['permuta'] if form.data['permuta'] != 2 else None 266 get_property.financia = form.data['financia'] if form.data['financia'] != 2 else None 267 get_property.garaje = form.data['garaje'] 268 get_property.estado = form.data['estado'] 269 get_property.orientacion = form.data['orientacion'] 270 get_property.disposicion = form.data['disposicion'] 271 get_property.n_plantas = form.data['n_plantas'] 272 get_property.comfort[0].agua_caliente = form.comfort.data['agua_caliente']273 get_property.comfort[0].aire_acondicionado = form.comfort.data['aire_acondicionado']274 get_property.comfort[0].altillo = form.comfort.data['altillo']275 get_property.comfort[0].amueblada = form.comfort.data['amueblada']276 get_property.comfort[0].balcón = form.comfort.data['balcón']277 get_property.comfort[0].barbacoa = form.comfort.data['barbacoa']278 get_property.comfort[0].box = form.comfort.data['box']279 get_property.comfort[0].bungalow =form.comfort.data['bungalow']280 get_property.comfort[0].calefacción = form.comfort.data['calefacción']281 get_property.comfort[0].depósito = form.comfort.data['depósito']282 get_property.comfort[0].dormitorio_de_servicio = form.comfort.data['dormitorio_de_servicio']283 get_property.comfort[0].estufa_leña = form.comfort.data['estufa_leña']284 get_property.comfort[0].garaje = form.comfort.data['garaje']285 get_property.comfort[0].gas_por_cañería = form.comfort.data['gas_por_cañería']286 get_property.comfort[0].gym = form.comfort.data['gym']287 get_property.comfort[0].instalación_de_tv_cable = form.comfort.data['instalación_de_tv_cable']288 get_property.comfort[0].jacuzzi = form.comfort.data['jacuzzi']289 get_property.comfort[0].jardín = form.comfort.data['jardín']290 get_property.comfort[0].lavadero = form.comfort.data['lavadero']291 get_property.comfort[0].lavandería = form.comfort.data['lavandería']292 get_property.comfort[0].linea_blanca = form.comfort.data['linea_blanca']293 get_property.comfort[0].living_comedor = form.comfort.data['living_comedor']294 get_property.comfort[0].losa_radiante = form.comfort.data['losa_radiante']295 get_property.comfort[0].parrillero = form.comfort.data['parrillero']296 get_property.comfort[0].patio = form.comfort.data['patio']297 get_property.comfort[0].piscina = form.comfort.data['piscina']298 get_property.comfort[0].piso_porcelanato = form.comfort.data['piso_porcelanato']299 get_property.comfort[0].placard_en_la_cocina = form.comfort.data['placard_en_la_cocina']300 get_property.comfort[0].placard_en_dormitorio = form.comfort.data['placard_en_dormitorio']301 get_property.comfort[0].playroom = form.comfort.data['playroom']302 get_property.comfort[0].previsión_aa = form.comfort.data['previsión_aa']303 get_property.comfort[0].sauna = form.comfort.data['sauna']304 get_property.comfort[0].sótano = form.comfort.data['sótano']305 get_property.comfort[0].terraza = form.comfort.data['terraza']306 get_property.comfort[0].terraza_lavadero = form.comfort.data['terraza_lavadero']307 get_property.comfort[0].vestidor = form.comfort.data['vestidor']308 get_property.comfort[0].walkin_closet = form.comfort.data['walkin_closet']309 get_property.comfort[0].wifi = form.comfort.data['wifi']310 get_property.seguridad[0].alarma = form.seguridad.data['alarma']311 get_property.seguridad[0].cámaras_cctv = form.seguridad.data['cámaras_cctv']312 get_property.seguridad[0].cerca_perimetral = form.seguridad.data['cerca_perimetral']313 get_property.seguridad[0].portería_24hs = form.seguridad.data['portería_24hs']314 get_property.seguridad[0].portón_eléctrico = form.seguridad.data['portón_eléctrico']315 get_property.seguridad[0].rejas = form.seguridad.data['rejas']316 get_property.seguridad[0].guardia_de_seguridad = form.seguridad.data['guardia_de_seguridad']317def paginacion(page,step,id,prop_query):318 print(page,step,id)319 destacados_count = prop_query.filter(Properties.pausado == False,Properties.destacado == 1).count()320 if (step == 1):321 if ((page-1)*9 < destacados_count):322 get_properties = prop_query.filter(Properties.pausado == False,Properties.destacado == 1,Properties.id > id).limit(9).all()323 properties_count = len(get_properties)324 if (properties_count < 9):325 get_properties_left = prop_query.filter(Properties.pausado == False,Properties.destacado == 0).limit(9-properties_count).all()326 for propiedades in get_properties_left:327 get_properties.append(propiedades)328 return get_properties329 elif ((page-1)*9 == destacados_count):330 get_properties = prop_query.filter(Properties.pausado == False,Properties.destacado == 0).limit(9).all()331 return get_properties332 else:333 get_properties = prop_query.filter(Properties.pausado == False,Properties.destacado == 0,Properties.id > id).limit(9).all()334 return get_properties335 else :336 if ((page*9)+1 > destacados_count):337 properties_count = prop_query.filter(Properties.pausado == False,Properties.destacado == 0,Properties.id < id).count()338 if (properties_count < 9):339 get_properties_left = prop_query.order_by().filter(Properties.pausado == False,Properties.destacado == 0,Properties.id < id).all()340 get_properties = prop_query.order_by(Properties.id.desc()).filter(Properties.pausado == False,Properties.destacado == 1).limit(9-properties_count).all()341 get_properties = get_properties[::-1]342 for propiedades in get_properties_left:343 get_properties.append(propiedades)344 return get_properties345 elif ((page*9)+1 == destacados_count):346 get_properties = prop_query.order_by(Properties.id.desc()).filter(Properties.pausado == False,Properties.destacado == 1).limit(9).all()347 get_properties = get_properties[::-1]348 return get_properties349 else:350 get_properties = prop_query.filter(Properties.pausado == False,Properties.destacado == 1,Properties.id < id).limit(9).all()351 return get_properties352@app.route('/caca')353def caca():354 a1 = Properties.query.all()355 start = os.getcwd()356 for a in a1:357 os.mkdir(start + '/main/static/imgs/' + a.ref)358 os.chdir(start + '/main/static/imgs/' + a.ref)359 for i in range(1,15):360 pic = getattr(a,'photos'+ str(i))361 if pic is not None:362 im = Image.open(io.BytesIO(pic))363 im.save(os.getcwd() +'/'+ str(i) + '.JPEG')364 im.close()365@app.route('/')366#@profile367def index():368 barrios_query = Barrios.query.all()369 p_show = []370 aux = []371 i = 0372 get_properties = Properties.query.filter(Properties.pausado == False,Properties.destacado == 1).limit(9).all()373 properties_count = len(get_properties) if get_properties is not None else 0374 if (properties_count < 9):375 get_properties_left = Properties.query.filter(Properties.pausado == False,Properties.destacado == 0).limit(9-properties_count).all()376 for propiedades in get_properties_left:377 get_properties.append(propiedades)378 #print(get_properties)379 paginas = Properties.query.count()380 p_show = properties_mtx(get_properties,3)381 #print(p_show[0])382 paginas = math.ceil(int(paginas)/9) if paginas != '0' else 1383 return render_template('index-premium.html', barrios = barrios_query, 384 get_properties = p_show, paginas = paginas, pagina = 1)385@app.route('/page')386#@profile387def page():388 barrios_query = Barrios.query.all()389 p_show = []390 aux = []391 i = 0392 get_properties = Properties.query.filter(Properties.pausado == False,Properties.destacado == 1).limit(9).all()393 properties_count = len(get_properties) if get_properties is not None else 0394 if (properties_count < 9):395 get_properties_left = Properties.query.filter(Properties.pausado == False,Properties.destacado == 0).limit(9-properties_count).all()396 for propiedades in get_properties_left:397 get_properties.append(propiedades)398 #print(get_properties)399 paginas = Properties.query.count()400 p_show = properties_mtx(get_properties,3)401 #print(p_show[0])402 paginas = math.ceil(int(paginas)/9) if paginas != '0' else 1403 return render_template('index-premium-pag.html', barrios = barrios_query, 404 get_properties = p_show, paginas = paginas, pagina = 1,operacion_title = "Todas las propiedades")405@app.route('/<int:page>/<int:step>/<int:id>')406def index_paginas(page,step,id):407 print(page,step,id)408 p_search = False409 p_show = []410 aux = []411 barrios_query = Barrios.query.all()412 destacados_count = Properties.query.filter(Properties.pausado == False,Properties.destacado == 1).count()413 print(destacados_count)414 get_properties = paginacion(page,step,id,Properties.query)415 paginas = Properties.query.count()416 p_show = properties_mtx(get_properties,3)417 #print(p_show) 418 paginas = math.ceil(int(paginas)/9) if paginas != '0' else 1419 print(' ' , p_show[0][0][0].id)420 #if (id == paginas)421 return render_template('index-premium-pag.html', 422 get_properties = p_show, barrios = barrios_query, pagina = page, 423 paginas = paginas, p_search = p_search,operacion_title = "Todas las propiedades") 424@app.route('/delete/<id>', methods=['GET'])425def delete(id):426 # try:427 com_deletes = Comfort.query.filter_by(id = id).delete()428 sec_deletes = Seguridad.query.filter_by(id = id).delete()429 p_deletes = Properties.query.filter_by(id = id).delete()430 db.session.commit()431 # except Exception:432 # flash('No es posible eliminar esta propiedad')433 return redirect(url_for('admin',section = 'home'))434@app.route('/paused/<id>', methods=['GET'])435def pause(id):436 prop = Properties.query.filter_by(id = id).first()437 if prop.pausado == True:438 prop.pausado = False439 db.session.commit()440 return redirect(url_for('admin',section = 'paused'))441 else:442 prop.pausado = True443 db.session.commit()444 return redirect(url_for('admin',section = 'home'))445@app.route('/p_search', methods=['POST', 'GET'])446def search_page():447 barrios_query = Barrios.query.all()448 querys = Properties.query449 errores = {}450 print('asdasdasd',request.form)451 currency = request.form['currency']452 precio_min = request.form['precio_min']453 precio_max = request.form['precio_max']454 metraje_min = request.form['metraje_min']455 metraje_max = request.form['metraje_max']456 if request.form['ref'] != '':457 flag = True 458 querys = querys.filter_by(ref = request.form['ref']) 459 if request.form['dormitorios'] != '':460 flag = True 461 querys = querys.filter_by(dormitorios = request.form['dormitorios'])462 if request.form['baños'] != '':463 flag = True464 querys = querys.filter_by(baños = request.form['baños']) 465 if request.form['barrio'] != '':466 flag = True467 querys = querys.filter(Properties.barrio.has(barrio=request.form['barrio']))468 469 if request.form['operacion']:470 flag = True471 querys = querys.filter(Properties.operaciones.has(operacion=request.form['operacion']))472 if request.form['tipo_propiedad']:473 flag = True474 querys = querys.filter(Properties.tipo_propiedad.has(tipo_propiedad=request.form['tipo_propiedad']))475 #....PRECIOS QUERY & erroresHANDLING...........................476 query1 = querys477 if(currency == 'precio_dolares'):478 query_precio = False479 query_precio1 = False480 if precio_min != '':481 if not is_number(precio_min):482 errores["precio_min"] = "No es un numero"483 else:484 flag = True485 query_precio = True486 query1 = query1.filter(Properties.precio_dolares >= precio_min)487 if precio_max != '':488 if not is_number(precio_max):489 errores["precio_max"] = "No es un numero"490 else:491 flag = True492 query_precio1 = True493 query1 = query1.filter(Properties.precio_dolares <= precio_max)494 if query_precio and query_precio1 and precio_min > precio_max:495 query1 = querys496 errores["precio_min"] = "Diferencia invalida"497 errores["precio_max"] = "Diferencia invalida"498 else:499 query_precio = False500 query_precio1 = False501 if precio_min != '':502 query_precio = False503 if not is_number(precio_min):504 errores["precio_min"] = "No es un numero"505 else:506 flag = True507 query_precio = True508 query1 = query1.filter(Properties.precio_pesos >= precio_min)509 if precio_max != '':510 query_precio1 = False511 if not is_number(precio_max):512 errores["precio_max"] = "No es un numero"513 else:514 flag = True515 query_precio1 = True516 query1 = query1.filter(Properties.precio_pesos <= precio_max)517 if query_precio and query_precio1 and precio_min > precio_max:518 query1 = querys519 errores["precio_min"] = "Diferencia invalida"520 errores["precio_max"] = "Diferencia invalida"521 522 523 #....METRAJE QUERY & erroresHANDLING...........................524 query2 = query1525 query_metraje = False526 query_metraje1 = False527 if metraje_min != '': 528 if not is_number(metraje_min):529 errores["metraje_min"] = "No es un numero"530 else:531 flag = True532 query_metraje = True533 query2 = query2.filter(Properties.metraje_edificio >= metraje_min)534 if metraje_max != '':535 if not is_number(metraje_max):536 errores["metraje_max"] = "No es un numero"537 else:538 flag = True539 query_metraje1 = True540 query2 = query2.filter(Properties.metraje_edificio <= metraje_max)541 if query_metraje and query_metraje1 and metraje_min > metraje_max:542 query2 = querys543 errores["metraje_min"] = "Diferencia invalida"544 errores["metraje_max"] = "Diferencia invalida"545 print(query2)546 search_results = query2 if flag==True else False547 print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%4', search_results)548 if (search_results):549 paginas = search_results.count()550 if(paginas == 0):551 flash("Sin resultados")552 return redirect(url_for('page'))553 get_properties = search_results.filter(Properties.pausado == False,Properties.destacado == 1).limit(9).all()554 properties_count = len(get_properties) if get_properties is not None else 0555 if (properties_count < 9):556 search_results_left = search_results.filter(Properties.pausado == False,Properties.destacado == 0).limit(9-properties_count).all()557 for propiedades in search_results_left:558 get_properties.append(propiedades)559 session['busqueda'] = request.form 560 else:561 #p_show = Properties.query.limit(30).all()562 return redirect(url_for('page'))563 print(errores,[e for e in errores])564 print(get_properties)565 p_show = properties_mtx(get_properties,3)566 paginas = math.ceil(int(paginas)/9)567 return render_template('index-premium-pag.html', barrios = barrios_query,568 paginas = paginas, pagina = 1, 569 get_properties=p_show, errores=errores, p_search = True)570@app.route('/p_search/<int:page>/<int:step>/<int:id>', methods=['POST', 'GET'])571def search(page,step,id):572 barrios_query = Barrios.query.all()573 querys = Properties.query574 flag = False575 errores = {}576 print('asdasdasd',session.get('busqueda'))577 currency = session.get('busqueda')['currency']578 precio_min = session.get('busqueda')['precio_min']579 precio_max = session.get('busqueda')['precio_max']580 metraje_min = session.get('busqueda')['metraje_min']581 metraje_max = session.get('busqueda')['metraje_max']582 if session.get('busqueda')['ref'] != '':583 flag = True 584 querys = querys.filter_by(ref = session.get('busqueda')['ref']) 585 if session.get('busqueda')['dormitorios'] != '':586 flag = True 587 querys = querys.filter_by(dormitorios = session.get('busqueda')['dormitorios'])588 if session.get('busqueda')['baños'] != '':589 flag = True590 querys = querys.filter_by(baños = session.get('busqueda')['baños']) 591 if session.get('busqueda')['barrio'] != '':592 flag = True593 querys = querys.filter(Properties.barrio.has(barrio=session.get('busqueda')['barrio'])) 594 if session.get('busqueda')['operacion']:595 flag = True596 querys = querys.filter(Properties.operaciones.has(operacion=session.get('busqueda')['operacion']))597 if session.get('busqueda')['tipo_propiedad']:598 flag = True599 querys = querys.filter(Properties.tipo_propiedad.has(tipo_propiedad=session.get('busqueda')['tipo_propiedad']))600 #....PRECIOS QUERY & erroresHANDLING...........................601 query1 = querys602 if(currency == 'precio_dolares'):603 query_precio = False604 query_precio1 = False605 if precio_min != '':606 if not is_number(precio_min):607 errores["precio_min"] = "No es un numero"608 else:609 flag = True610 query_precio = True611 query1 = query1.filter(Properties.precio_dolares >= precio_min)612 if precio_max != '':613 if not is_number(precio_max):614 errores["precio_max"] = "No es un numero"615 else:616 flag = True617 query_precio1 = True618 query1 = query1.filter(Properties.precio_dolares <= precio_max)619 if query_precio and query_precio1 and precio_min > precio_max:620 query1 = querys621 errores["precio_min"] = "Diferencia invalida"622 errores["precio_max"] = "Diferencia invalida"623 else:624 query_precio = False625 query_precio1 = False626 if precio_min != '':627 if not is_number(precio_min):628 errores["precio_min"] = "No es un numero"629 else:630 flag = True631 query_precio = True632 query1 = query1.filter(Properties.precio_pesos >= precio_min)633 if precio_max != '':634 if not is_number(precio_max):635 errores["precio_max"] = "No es un numero"636 else:637 flag = True638 query_precio1 = True639 query1 = query1.filter(Properties.precio_pesos <= precio_max)640 if query_precio and query_precio1 and precio_min > precio_max:641 query1 = querys642 errores["precio_min"] = "Diferencia invalida"643 errores["precio_max"] = "Diferencia invalida" 644 #....METRAJE QUERY & erroresHANDLING...........................645 query2 = query1646 query_metraje = False647 query_metraje1 = False648 if metraje_min != '':649 if not is_number(metraje_min):650 errores["metraje_min"] = "No es un numero"651 else:652 flag = True653 query_metraje = True654 query2 = query2.filter(Properties.metraje_edificio >= metraje_min)655 if metraje_max != '':656 if not is_number(metraje_max):657 errores["metraje_max"] = "No es un numero"658 else:659 flag = True660 query_metraje1 = True661 query2 = query2.filter(Properties.metraje_edificio <= metraje_max)662 if query_metraje and query_metraje1 and metraje_min > metraje_max:663 query2 = querys664 errores["metraje_min"] = "Diferencia invalida"665 errores["metraje_max"] = "Diferencia invalida"666 print(query2)667 search_results = query2 if flag==True else False668 if (search_results != False):669 paginas = search_results.count()670 if(paginas == 0):671 return redirect(url_for('page'))672 search_results = paginacion(page,step,id,search_results)673 else:674 return redirect(url_for('page'))675 print(errores,[e for e in errores])676 print(search_results)677 p_show = properties_mtx(search_results,3)678 paginas = math.ceil(int(paginas)/9)679 return render_template('index-premium-pag.html', barrios = barrios_query, 680 paginas = paginas, pagina = page, get_properties=p_show, 681 errores=errores, p_search = True)682@app.route('/admin-search', methods=['POST', 'GET'])683def admin_search():684 barrios_query = Barrios.query.all()685 querys = Properties.query686 flag = False687 errores = {}688 print('asdasdasd',request.form)689 currency = request.form['currency']690 precio_min = request.form['precio_min']691 precio_max = request.form['precio_max']692 metraje_min = request.form['metraje_min']693 metraje_max = request.form['metraje_max']694 if request.form['ref'] != '':695 flag = True 696 querys = querys.filter_by(ref = request.form['ref']) 697 if request.form['dormitorios'] != '':698 flag = True 699 querys = querys.filter_by(dormitorios = request.form['dormitorios'])700 if request.form['baños'] != '':701 flag = True702 querys = querys.filter_by(baños = request.form['baños']) 703 if request.form['barrio'] != '':704 flag = True705 querys = querys.filter(Properties.barrio.has(barrio=request.form['barrio'])) 706 if request.form['operacion']:707 flag = True708 querys = querys.filter(Properties.operaciones.has(operacion=request.form['operacion']))709 if request.form['tipo_propiedad']:710 flag = True711 querys = querys.filter(Properties.tipo_propiedad.has(tipo_propiedad=request.form['tipo_propiedad']))712 #....PRECIOS QUERY & erroresHANDLING...........................713 query1 = querys714 if(currency == 'precio_dolares'):715 query_precio = False716 query_precio1 = False717 if precio_min != '':718 if not is_number(precio_min):719 errores["precio_min"] = "No es un numero"720 else:721 flag = True722 query_precio = True723 query1 = query1.filter(Properties.precio_dolares >= precio_min)724 if precio_max != '':725 if not is_number(precio_max):726 errores["precio_max"] = "No es un numero"727 else:728 flag = True729 query_precio1 = True730 query1 = query1.filter(Properties.precio_dolares <= precio_max)731 if query_precio and query_precio1 and precio_min > precio_max:732 query1 = querys733 errores["precio_min"] = "Diferencia invalida"734 errores["precio_max"] = "Diferencia invalida"735 else:736 query_precio = False737 query_precio1 = False738 if precio_min != '':739 if not is_number(precio_min):740 errores["precio_min"] = "No es un numero"741 else:742 flag = True743 query_precio = True744 query1 = query1.filter(Properties.precio_pesos >= precio_min)745 if precio_max != '':746 if not is_number(precio_max):747 errores["precio_max"] = "No es un numero"748 else:749 flag = True750 query_precio1 = True751 query1 = query1.filter(Properties.precio_pesos <= precio_max)752 if query_precio and query_precio1 and precio_min > precio_max:753 query1 = querys754 errores["precio_min"] = "Diferencia invalida"755 errores["precio_max"] = "Diferencia invalida" 756 #....METRAJE QUERY & erroresHANDLING...........................757 query2 = query1758 query_metraje = False759 query_metraje1 = False760 if metraje_min != '':761 if not is_number(metraje_min):762 errores["metraje_min"] = "No es un numero"763 else:764 flag = True765 query_metraje = True766 query2 = query2.filter(Properties.metraje_edificio >= metraje_min)767 if metraje_max != '':768 if not is_number(metraje_max):769 errores["metraje_max"] = "No es un numero"770 else:771 flag = True772 query_metraje1 = True773 query2 = query2.filter(Properties.metraje_edificio <= metraje_max)774 if query_metraje is not None and query_metraje1 is not None and metraje_min > metraje_max:775 query2 = querys776 errores["metraje_min"] = "Diferencia invalida"777 errores["metraje_max"] = "Diferencia invalida"778 print(query2)779 search_results = query2 if flag==True else False780 if (search_results != False):781 paginas = search_results.count()782 if(paginas == 0):783 flash('No se encontro ninguna propiedad')784 return redirect(url_for('admin', section="home"))785 search_results = search_results.order_by(Properties.destacado).all()786 else:787 return redirect(url_for('admin', section="home"))788 print(errores,[e for e in errores])789 print(query2)790 properties_fotos_concat = []791 for p in search_results:792 foto = get_img(p.ref)793 properties_fotos_concat.append([p,foto]) 794 barrios_query = Barrios.query.all()795 form = PropertyForm()796 contactquestions_amount = Contactquestions.query.filter_by(read=False).count()797 return render_template('admin.html', questions_amount=contactquestions_amount, barrios = barrios_query, 798 get_properties=properties_fotos_concat, errores=errores, form=form)799@app.route('/ventas', methods=['GET'])800def ventas():801 ventas = True802 barrios_query = Barrios.query.all()803 p_show = []804 get_properties = Properties.query.filter(Properties.pausado == False,Properties.destacado == 1,Properties.operacion_id == 1).limit(9).all()805 properties_count = len(get_properties) if get_properties is not None else 0806 if (properties_count < 9):807 get_properties_left = Properties.query.filter(Properties.pausado == False,Properties.destacado == 0,Properties.operacion_id == 1).limit(9-properties_count).all()808 for propiedades in get_properties_left:809 get_properties.append(propiedades)810 paginas =Properties.query.filter_by(operacion_id = 1).count()811 print([propiedad.id for propiedad in get_properties])812 p_show = properties_mtx(get_properties,3)813 paginas = math.ceil(int(paginas)/9) if paginas != '0' else 1 814 return render_template('index-premium-pag.html', barrios = barrios_query, 815 get_properties = p_show, paginas = paginas, pagina = 1,ventas = ventas,operacion_title = "Propiedades en venta")816@app.route('/ventas/<int:page>/<int:step>/<int:id>', methods=['GET'])817def ventas_pag(page,step,id):818 ventas = True819 barrios_query = Barrios.query.all()820 p_show = []821 get_properties = paginacion(page,step,id,Properties.query.filter(Properties.operacion_id==1))822 if (get_properties == []):823 return redirect(url_for('ventas'))824 paginas = Properties.query.filter_by(operacion_id = 1).count()825 p_show = properties_mtx(get_properties,3)826 paginas = math.ceil(int(paginas)/9) if paginas != '0' else 1 827 return render_template('index-premium-pag.html', barrios = barrios_query, 828 get_properties = p_show, paginas = paginas, pagina = page, ventas = ventas,operacion_title = "Propiedades en venta")829@app.route('/alquiler', methods=['GET'])830def alquiler():831 alquiler = True832 barrios_query = Barrios.query.all()833 p_show = []834 get_properties = Properties.query.filter(Properties.pausado == False,Properties.destacado == 1,Properties.operacion_id == 2).limit(9).all()835 properties_count = len(get_properties) if get_properties is not None else 0836 if (properties_count < 9):837 get_properties_left = Properties.query.filter(Properties.pausado == False,Properties.destacado == 0,Properties.operacion_id == 2).limit(9-properties_count).all()838 for propiedades in get_properties_left:839 get_properties.append(propiedades)840 paginas = Properties.query.filter_by(operacion_id = 2).count()841 p_show = properties_mtx(get_properties,3)842 paginas = math.ceil(int(paginas)/9) if paginas != '0' else 1843 return render_template('index-premium-pag.html', barrios = barrios_query, 844 get_properties = p_show, paginas = paginas, pagina = 1, alquiler = alquiler,operacion_title = "Propiedades en alquiler")845@app.route('/alquiler/<int:page>/<int:step>/<int:id>', methods=['GET'])846def alquiler_pag(page,step,id):847 alquiler = True848 barrios_query = Barrios.query.all()849 p_show = []850 get_properties = paginacion(page,step,id,Properties.query.filter(Properties.pausado == False,Properties.operacion_id==2))851 print('asdasdas',get_properties)852 if (get_properties == []):853 return redirect(url_for('alquiler'))854 paginas = Properties.query.filter_by(operacion_id = 2).count()855 p_show = properties_mtx(get_properties,3)856 paginas = math.ceil(int(paginas)/9) if paginas != '0' else 1857 return render_template('index-premium-pag.html', barrios = barrios_query, 858 get_properties = p_show, paginas = paginas, pagina = page ,alquiler = alquiler,operacion_title = "Propiedades en alquiler")859@app.route('/contact-mail', methods=['POST', 'GET'])860def contact_questions():861 new_question = Contactquestions(complete_name = request.form['contact-name'], 862 mail = request.form['contact-email'], phone = request.form['contact-phone'], 863 question = request.form['contact-question'])864 db.session.add(new_question)865 db.session.commit()866 flash("Pregunta enviada correctamente!")867 return redirect(url_for('index'))868@app.route('/question-mail', methods=['POST', 'GET'])869def property_questions():870 id = request.form['contact-property_id']871 new_question = Contactquestions(property_id=request.form['contact-property_id'],complete_name = "Buscando propiedad", 872 mail = request.form['contact-email'], phone = request.form['contact-phone'], 873 question = request.form['contact-question'])874 db.session.add(new_question)875 db.session.commit()876 flash("Pregunta enviada correctamente!")877 return redirect(url_for('profile', id=id))878@profile879@app.route('/admin/<section>')880#@login_required881def admin(section):882 test = []883 form = PropertyForm()884 barrios_query = Barrios.query.all()885 propietarios = Propietarios.query.all()886 contactquestions_amount = Contactquestions.query.filter_by(read=False).count()887 if section == "insert":888 get_properties = Properties.query.with_entities(Properties.ref).all()889 print(get_properties)890 return render_template('insert.html',form=form,get_properties = get_properties,propietarios=propietarios)891 if section == "home":892 get_properties = Properties.query.filter_by(pausado=0).all()893 for propiedades in get_properties:894 foto = get_img(propiedades.ref)895 test.append([propiedades,foto])896 print(get_properties)897 section="home"898 return render_template('admin.html', barrios = barrios_query, propietarios=propietarios,get_properties=test, 899 form=form, questions_amount=contactquestions_amount, section=section)900 if section == "sale":901 get_properties = Properties.query.filter_by(operacion_id = 1, pausado = 0).all()#THE ONE THAT CHANGES902 for propiedades in get_properties:903 foto = get_img(propiedades.ref)904 test.append([propiedades,foto]) 905 print(get_properties)906 section="sale"907 return render_template('admin.html', propietarios=propietarios,barrios = barrios_query, get_properties = test, 908 form=form, questions_amount=contactquestions_amount, base64=base64, section=section)909 if section == "rent":910 get_properties = Properties.query.filter_by(operacion_id = 2, pausado = 0).all()#THE ONE THAT CHANGES911 for propiedades in get_properties:912 foto = get_img(propiedades.ref)913 test.append([propiedades,foto]) 914 print(get_properties)915 section="rent"916 return render_template('admin.html', barrios = barrios_query, get_properties = test, 917 form=form, propietarios=propietarios,questions_amount=contactquestions_amount, base64=base64, section=section)918 if section == "paused":919 get_properties = Properties.query.filter_by(pausado = 1).all()#THE ONE THAT CHANGES920 for propiedades in get_properties:921 foto = get_img(propiedades.ref)922 test.append([propiedades,foto]) 923 print(get_properties)924 section="paused"925 return render_template('admin.html', propietarios=propietarios,barrios = barrios_query, get_properties = test, 926 form=form, questions_amount=contactquestions_amount, section=section)927@profile 928@app.route('/update/<id>', methods=['GET', 'POST'])929#@login_required930def update(id):931 contactquestions_amount = Contactquestions.query.filter_by(read=False).count()932 get_properties = Properties.query.get(id)933 form = PropertyForm()934 assign_properties_to_from(form,get_properties)935 propietarios = Propietarios.query.all()936 barrios = Barrios.query.all()937 print(form.data,get_properties.titulo)938 return render_template('asdasd.html', 939 form = form,fotos = get_imgs(get_properties.ref), propietarios = propietarios,questions_amount=contactquestions_amount,id = id,barrios = barrios, base64=base64)940@app.route('/about')941def about():942 return render_template('about.html')943 944@profile945@app.route('/edit-property/<int:id>', methods=['POST'])946#@login_required947def edit_property(id):948 print(request.files.getlist('change_pic[]'))949 change_pic = [a for a in request.files.getlist('change_pic[]') if a.filename != '']950 print(change_pic)951 form = PropertyForm()952 flag = True953 added_imgs = request.files.getlist('pics')954 get_property = Properties.query.get(id)955 path_to_ref = imgs_dir + '/' + get_property.ref956 all_imgs = os.listdir(path_to_ref)957 # Check when a pic is re-changed (if is pushed to change_pic array or changed content within same index)958 if request.args.getlist('change[]'):959 updates_imgs = zip(request.args.getlist('change[]') ,change_pic)960 for update in updates_imgs:961 print('werrrrrrrrr',update[1])962 fext = update[1].filename.split('.')963 print(fext[-1])964 img_fullname = all_imgs[int(update[0])-1]965 os.remove(path_to_ref + '/' + img_fullname)966 im = Image.open(update[1]).save(path_to_ref + '/' + str(update[0]) + '.' + fext[-1])967 if request.args.getlist('delete[]'): 968 deletes = request.args.getlist('delete[]')969 del_check = del_imgs(get_property.ref,deletes)970 added_imgs = request.files.getlist('pics')971 print(added_imgs[0].filename)972 #Condicional por si el input no trae ninguna imagen973 if added_imgs[0].filename != '':974 all_imgs = os.listdir(path_to_ref)975 added_imgs_count = len(added_imgs)976 total_imgs = len(all_imgs)977 i = 0978 while (i < added_imgs_count and total_imgs < 15):979 ext = added_imgs[i].filename.split('.')980 print(ext)981 img_check = add_imgs(path_to_ref,added_imgs[i], str(total_imgs+1) +'.'+ ext[-1])982 i+=1983 total_imgs =+ 1984 pics_amount_condition_check = i == added_imgs_count985 if (not pics_amount_condition_check):986 flag = False987 flash('Demasiadas fotos, las ultimas ' + str(added_imgs_count-i) + ' no fueron ingresadas')988 if form.validate_on_submit() and flag: 989 ref_check = Properties.query.filter_by(ref = form.data['ref']).first()990 if (form.data['precio_dolares'] == '' and form.data['precio_dolares'] == ''):991 flag = False992 flash("La propiedad necesita un precio")993 if (ref_check is not None and ref_check.id != get_property.id):994 flag = False 995 flash("La referencia tiene que ser unica")996 if not flag:997 contactquestions_amount = Contactquestions.query.filter_by(read=False).count()998 propietarios = Propietarios.query.all()999 barrios = Barrios.query.all()1000 fotos = get_imgs(get_property.ref)1001 print(form.errors)1002 for error in form.errors:1003 form.errors[error][0] = 'Valor no valido'1004 print(error)1005 return render_template('asdasd.html', 1006 form = form,fotos = fotos, propietarios = propietarios,questions_amount=contactquestions_amount,id = id,barrios = barrios, base64=base64)1007 else:1008 assign_form_to_properties(get_property,form)1009 db.session.commit()1010 else:1011 contactquestions_amount = Contactquestions.query.filter_by(read=False).count()1012 propietarios = Propietarios.query.all()1013 barrios = Barrios.query.all()1014 fotos = get_imgs(get_property.ref)1015 print(form.errors)1016 for error in form.errors:1017 form.errors[error][0] = 'Valor no valido'1018 print(error)1019 return render_template('asdasd.html', 1020 form = form,fotos = fotos, propietarios = propietarios,questions_amount=contactquestions_amount,id = id,barrios = barrios, base64=base64)1021 return redirect(url_for('admin', section='home'))1022@app.route('/profile/<id>')1023def profile(id):1024 get_property = Properties.query.filter_by(id = id).first()1025 comodidades = Comfort.query.filter_by(id = id).first()1026 seguridad = Seguridad.query.filter_by(id = id).first()1027 fotos = get_imgs(get_property.ref)1028 return render_template('profile.html', 1029 get_property = get_property, fotos = fotos,1030 comfort = comodidades,1031 seguridad = seguridad)1032@app.route('/insertation', methods=['POST','GET'])1033# @login_required1034def insertation():1035 form = PropertyForm()1036 fotos_count = len(form.fotos.data)1037 flag = True1038 print('asd')1039 if form.validate_on_submit():1040 ref_check = Properties.query.filter_by(ref = request.form['ref']).first()1041 ref_check = Properties.query.filter_by(ref = request.form['ref'].upper()).first() if ref_check is None else ref_check1042 print(ref_check,request.form['ref'])1043 if (form.data['precio_pesos'] == '' and form.data['precio_dolares'] == ''):1044 flag = False1045 flash("La propiedad necesita un precio")1046 if (fotos_count > 15):1047 flag = False1048 flash("Demasiadas fotos, maximo 15")1049 if (ref_check is not None):1050 flag = False1051 flash("La referencia tiene que ser unica")1052 if flag:1053 barrio = Barrios.query.filter_by(barrio = form.data['barrio']).first()1054 operacion = Operaciones.query.filter_by(operacion = form.data['operacion']).first()1055 tipo_propiedad = Tipo_propiedad.query.filter_by(tipo_propiedad = form.data['tipo_propiedad']).first()1056 store_imgs(form.data['ref'],form.fotos.data)1057 propietario_query = Propietarios.query.filter_by(telefono = form.data['telefono']).first()1058 if propietario_query is None:1059 propietario_add = Propietarios(nombre = form.data['nombre'], apellido = form.data['apellido'], email = form.data['email'], telefono = form.data['telefono']) 1060 db.session.add(propietario_add)1061 db.session.commit()1062 propietario_query = Propietarios.query.filter_by(telefono = form.data['telefono']).first()1063 print(propietario_query.id)1064 property_data = Properties(operacion_id = operacion.id,1065 pausado = 0,1066 fecha_publicacion = date.today(),1067 tipo_propiedad_id = tipo_propiedad.id,1068 propietario_id = propietario_query.id,1069 barrio_id = barrio.id,1070 destacado = form.data['destacado'],1071 ref = request.form['ref'],1072 distancia_al_mar = form.data['distancia_al_mar'],1073 titulo = request.form['titulo'],1074 direccion = request.form['direccion'],1075 descripcion = form.data['descripcion'],1076 precio_dolares = abs(form.data['precio_dolares']) if form.data['precio_dolares'] else None,1077 precio_pesos = abs(form.data['precio_pesos']) if form.data['precio_pesos'] else None,1078 metraje_edificio = form.data['metraje_edificio'],1079 metraje_patio = form.data['metraje_patio'],1080 metraje_total = form.data['metraje_edificio'] if form.data['metraje_patio'] is None else form.data['metraje_edificio'] + form.data['metraje_patio'],1081 baños = form.data['baños'],1082 dormitorios = form.data['dormitorios'],1083 permuta = form.data['permuta'] if form.data['permuta'] != 2 else None,1084 financia = form.data['financia'] if form.data['financia'] != 2 else None,1085 garaje = form.data['garaje'],1086 estado = form.data['estado'],1087 orientacion = form.data['orientacion'],1088 disposicion = form.data['disposicion'],1089 n_plantas = form.data['n_plantas'])1090 db.session.add(property_data)1091 db.session.commit()1092 comfort = Comfort(agua_caliente = form.comfort.data['agua_caliente'],1093 aire_acondicionado = form.comfort.data['aire_acondicionado'],1094 altillo = form.comfort.data['altillo'],1095 amueblada = form.comfort.data['amueblada'],1096 balcón = form.comfort.data['balcón'],1097 barbacoa = form.comfort.data['barbacoa'],1098 box = form.comfort.data['box'],1099 bungalow = form.comfort.data['bungalow'],1100 calefacción = form.comfort.data['calefacción'],1101 depósito = form.comfort.data['depósito'],1102 dormitorio_de_servicio = form.comfort.data['dormitorio_de_servicio'],1103 estufa_leña = form.comfort.data['estufa_leña'],1104 garaje = form.comfort.data['garaje'],1105 gas_por_cañería = form.comfort.data['gas_por_cañería'],1106 gym = form.comfort.data['gym'],1107 instalación_de_tv_cable = form.comfort.data['instalación_de_tv_cable'],1108 jacuzzi = form.comfort.data['jacuzzi'],1109 jardín = form.comfort.data['jardín'],1110 lavadero = form.comfort.data['lavadero'],1111 lavandería = form.comfort.data['lavandería'],1112 linea_blanca = form.comfort.data['linea_blanca'],1113 living_comedor = form.comfort.data['living_comedor'],1114 losa_radiante = form.comfort.data['losa_radiante'],1115 parrillero = form.comfort.data['parrillero'],1116 patio = form.comfort.data['patio'],1117 piscina = form.comfort.data['piscina'],1118 piso_porcelanato = form.comfort.data['piso_porcelanato'],1119 placard_en_la_cocina = form.comfort.data['placard_en_la_cocina'],1120 placard_en_dormitorio = form.comfort.data['placard_en_dormitorio'],1121 playroom = form.comfort.data['playroom'],1122 previsión_aa = form.comfort.data['previsión_aa'],1123 sauna = form.comfort.data['sauna'],1124 sótano = form.comfort.data['sótano'],1125 terraza = form.comfort.data['terraza'],1126 terraza_lavadero = form.comfort.data['terraza_lavadero'],1127 vestidor = form.comfort.data['vestidor'],1128 vista_al_mar = form.comfort.data['vista_al_mar'],1129 walkin_closet = form.comfort.data['walkin_closet'],1130 wifi = form.comfort.data['wifi'])1131 seguridad = Seguridad( alarma = form.seguridad.data['alarma'],1132 cámaras_cctv = form.seguridad.data['cámaras_cctv'],1133 cerca_perimetral = form.seguridad.data['cerca_perimetral'],1134 portería_24hs = form.seguridad.data['portería_24hs'],1135 portón_eléctrico = form.seguridad.data['portón_eléctrico'],1136 rejas = form.seguridad.data['rejas'],1137 guardia_de_seguridad = form.seguridad.data['guardia_de_seguridad'])1138 db.session.add_all([comfort,seguridad])1139 db.session.commit()1140 flash('Ingreso completado con exito')1141 return redirect(url_for('admin',section='home'))1142 barrios_query = Barrios.query.all()1143 propietarios = Propietarios.query.all()1144 contactquestions_amount = Contactquestions.query.filter_by(read=False).count()1145 get_properties = Properties.query.all()1146 return render_template('insert.html', barrios = barrios_query, propietarios=propietarios,get_properties = get_properties, 1147 form=form, questions_amount=contactquestions_amount, section="home")1148@app.route('/insert-propietario', methods=['POST','GET'])1149@login_required1150def insert_propietario():1151 propietario_mail = request.form['email']1152 propietario_check = Propietarios.query.filter_by(email=propietario_mail).first()1153 if propietario_check:1154 return redirect(url_for('owners'))1155 flash("Propietario ya esta ingresado")1156 else:1157 propietario_add = Propietarios(nombre = request.form['nombre'], apellido = request.form['apellido'], email = request.form['email'], telefono = request.form['telefono']) 1158 db.session.add(propietario_add)1159 db.session.commit()1160 return redirect(url_for('owners'))1161 1162@app.route('/update-owner', methods=['POST', 'GET'])1163@login_required1164def update_owner():1165 owner_id = request.form['id']1166 get_owner = Propietarios.query.filter_by(id=owner_id).first()1167 get_owner.nombre = request.form['nombre']1168 get_owner.apellido = request.form['apellido']1169 get_owner.email = request.form['email']1170 get_owner.telefono = request.form['telefono']1171 try:1172 db.session.commit()1173 except Exception as e:1174 flash("Error! Hay otro propietario con esos datos")1175 print(e)1176 return redirect(url_for('owners'))1177@app.route('/propietarios')1178@login_required1179def owners():1180 contactquestions_amount = Contactquestions.query.filter_by(read=False).count()1181 form = PropertyForm()1182 propietarios = Propietarios.query.all()1183 return render_template('owners.html', questions_amount=contactquestions_amount, form=form, propietarios=propietarios,base64 = base64)1184@app.route('/propietarios/<id>')1185@login_required1186def owner_profile(id):1187 contactquestions_amount = Contactquestions.query.filter_by(read=False).count()1188 form = PropertyForm()1189 propietario = Propietarios.query.filter_by(id=id).first()1190 for propiedades in propietario.properties:1191 foto = get_img(propiedades.ref)1192 setattr(propiedades,'foto',foto)1193 print('asdasdasdasdasdasdasdasdsdasdasda',propietario.properties[0])1194 return render_template('owner-profile.html', questions_amount=contactquestions_amount, form=form, propietario=propietario)1195@app.route('/delete-prop/<id>', methods=['GET'])1196@login_required1197def delete_prop(id):1198 # try:1199 p_deletes = Properties.query.filter_by(id = id).delete()1200 com_deletes = Comfort.query.filter_by(id = id).delete()1201 sec_deletes = Seguridad.query.filter_by(id = id).delete()1202 db.session.commit()1203 # except Exception:1204 # flash('No es posible eliminar esta propiedad')1205 return redirect(url_for('owner_profile', id=id))1206@app.route('/remove_owner/<id>', methods=['POST'])1207@login_required1208def remove_owner(id):1209 db.session.query(Propietarios).filter_by(id=id).delete()1210 db.session.commit()1211 flash("Propietario eliminado.")1212 return redirect(url_for('owners'))1213@app.route('/contact-page')1214def contactus():1215 return render_template('contact.html')1216@app.route('/subscribed', methods=['GET', 'POST'])1217def subscribers():1218 client_mail = request.form['email']1219 new_subscriber = Subscribers( mail=client_mail)1220 try:1221 db.session.add(new_subscriber)1222 db.session.commit()1223 flash("Te has suscripto correctamente")1224 except Exception as e:1225 flash("Este mail ya esta ingresado")1226 print(e)1227 return redirect(url_for('index'))1228@app.route('/login_page')1229def login_page():1230 return render_template('login.html')1231@app.route('/login', methods=['GET', 'POST'])1232def login():1233 admin_check = Admins.query.all() 1234 username = request.form['username']1235 password = request.form['userpass']1236 if admin_check != []:1237 i = 01238 while username != admin[i].user and password != admin[i].password:1239 i+=11240 if username == admin[i].user:1241 session['username'] = username1242 print(g.user)1243 return redirect(url_for('admin', section="home"))1244 else:1245 flash("Usuario incorrecto")1246 return redirect(url_for('login_page'))1247 else:1248 if username == "admin" and password == "pass":1249 session['username'] = username1250 print(g.user)1251 return redirect(url_for('admin', section="home"))1252 else:1253 flash("Usuario incorrecto")1254 return redirect(url_for('login_page'))1255 1256 # if request.form['username'] == username and request.form['userpass'] == userpass:1257 # session['username'] = request.form['username']1258 # print(g.user)1259 # return redirect(url_for('admin', section="home"))1260 # else:1261 # flash("Usuario incorrecto")1262 # return redirect(url_for('login_page'))1263@app.route('/logout')1264def logout():1265 session['username'] = None1266 return redirect(url_for('index'))1267# ADMIN/SOCIAL ######################################################1268@app.route('/social/<section>')1269@login_required1270def social_page(section):1271 saved_amount = Contactquestions.query.filter_by(saved=True).count()1272 trash_amount = Contactquestions.query.filter_by(erased=True).count()1273 form = PropertyForm()1274 contactquestions_amount = Contactquestions.query.filter_by(read=False).count()1275 get_subscribers = Subscribers.query.all()1276 subscribers_amount = Subscribers.query.count()1277 subscribers = Subscribers.query.all()1278 if section == "home":1279 get_questions = Contactquestions.query.filter_by(erased=False).all()#THE ONE THAT CHANGES1280 return render_template('social.html', form=form, 1281 subscribers_amount = subscribers_amount, subscribers=subscribers, 1282 questions = get_questions, section="home", trash_amount=trash_amount, saved_amount=saved_amount, questions_amount=contactquestions_amount, subscriber = get_subscribers)1283 if section == "saved":1284 get_questions = Contactquestions.query.filter_by(saved=True).all()#THE ONE THAT CHANGES1285 form = PropertyForm()1286 return render_template('social.html', form=form, 1287 subscribers_amount = subscribers_amount, subscribers=subscribers,1288 questions = get_questions, section="saved", trash_amount=trash_amount, saved_amount=saved_amount, questions_amount=contactquestions_amount, subscriber = get_subscribers)1289 if section == "trash":1290 get_questions = Contactquestions.query.filter_by(erased=True).all()#THE ONE THAT CHANGES1291 return render_template('social.html', form=form, 1292 subscribers_amount = subscribers_amount, subscribers=subscribers,1293 questions = get_questions, section="trash", trash_amount=trash_amount, saved_amount=saved_amount, questions_amount=contactquestions_amount, subscriber = get_subscribers)1294@app.route('/readed/<id>', methods=['POST'])1295@login_required1296def readed(id):1297 get_question = Contactquestions.query.filter_by(id=id).first()1298 get_question.read = True1299 db.session.commit()1300 return redirect(url_for('social_page', section="home"))1301@app.route('/answered/<id>', methods=['POST'])1302@login_required1303def answered(id):1304 get_question = Contactquestions.query.filter_by(id=id).first()1305 get_question.answered = True1306 get_question.read = True1307 db.session.commit()1308 return redirect(url_for('social_page', section="home"))1309@app.route('/remove_question/<id>', methods=['POST'])1310@login_required1311def removed(id):1312 get_question = Contactquestions.query.filter_by(id=id).first()1313 if get_question.erased == False:1314 get_question.erased = True1315 get_question.saved = False1316 db.session.commit()1317 section = "home"1318 else:1319 db.session.query(Contactquestions).filter_by(id=id).delete()1320 db.session.commit()1321 section="trash"1322 return redirect(url_for('social_page', section=section))1323@app.route('/save_question/<id>', methods=['POST'])1324@login_required1325def saved(id):1326 path = request.path1327 get_question = Contactquestions.query.filter_by(id=id).first()1328 if get_question.saved == True and get_question.erased==False:1329 get_question.saved = False1330 db.session.commit()1331 return redirect(url_for('social_page', section="home"))1332 if get_question.saved == True and get_question.erased==True:1333 get_question.saved = False1334 db.session.commit()1335 return redirect(url_for('social_page', section="trash"))1336 if get_question.saved == False and get_question.erased ==True:1337 get_question.saved = True1338 get_question.erased = False1339 db.session.commit()1340 return redirect(url_for('social_page', section="trash"))1341 if get_question.saved == False:1342 get_question.saved = True1343 get_question.erased = False1344 db.session.commit()1345 return redirect(url_for('social_page', section="home"))1346@app.route('/send-mail-subscribers')1347@login_required1348def mail_send():1349 auto_send = False1350 property_id = 11351 property_description = Properties.query.filter_by(id=property_id).first()1352 message = property_description.descripcion1353 subscribers = Subscribers.query.all()1354 subscribers_mail = []1355 for subscriber in subscribers:1356 subscriber.mail1357 subscribers_mail.append(subscriber.mail)1358 print(subscribers)1359 msg = Message("Nueva propiedad ingresada!",1360 recipients=subscribers_mail)1361 msg.html = '<div style="border-style:solid;border-width:thin;border-color:#dadce0;border-radius:8px;padding:40px 20px"><div style="font-family:''Google Sans'',Roboto,RobotoDraft,Helvetica,Arial,sans-serif;border-bottom:thin solid #dadce0;color:rgba(0,0,0,0.87);line-height:32px;padding-bottom:24px;text-align:center;word-break:break-word"><img alt=Pallaresyasociados aria-hidden=true class=CToWUd width=50 src="https://scontent.fmvd4-1.fna.fbcdn.net/v/t1.0-9/16473247_262488650849599_8347533623051414236_n.jpg?_nc_cat=105&ccb=2&_nc_sid=09cbfe&_nc_eui2=AeG32RxTx024IYxCbpOzxz-1-3zJOy680pX7fMk7LrzSlYUv26nRqU1xX8N6KgvjcljdMNMVh_R061esq01RqNwe&_nc_ohc=Zps9IjZhHekAX9DH0kL&_nc_ht=scontent.fmvd4-1.fna&oh=e9b1d6a35f896795c3e791fc5cbbcff5&oe=5FD115BF" style=margin-bottom:16px width=74> <div style=font-size:24px> Descubre mas detalles sobre esta propiedad! </div> <div style=font-family:Roboto-Regular,Helvetica,Arial,sans-serif;font-size:14px;color:rgba(0,0,0,0.87);line-height:20px;padding-top:20px;text-align:center>' + message + '<div style=padding-top:32px;text-align:center><a href=http://127.0.0.1:3000/profile/1 style="font-family:''Google Sans'',Roboto,RobotoDraft,Helvetica,Arial,sans-serif;line-height:16px;color:#ffffff;font-weight:400;text-decoration:none;font-size:14px;display:inline-block;padding:10px 24px;background-color:rgb(1, 167, 1);border-radius:5px;min-width:90px" target=_blank> Ver la casa </a></div></div></div></div>'1362 if auto_send==True:1363 mail.send(msg)1364 1365 return render_template('mail.html')1366@app.route('/insert-miemail', methods=['POST']) #Función sin terminar1367@login_required1368def my_email():1369 existent_mail = MainMail.query.all()1370 verify_user = request.form['miemail-email']1371 verify_pass = request.form['miemail-pass']1372 # Exist?1373 if existent_mail == []:1374 try:1375 myemail_add = MainMail(mail = request.form['miemail-email'], 1376 mail_password = request.form['miemail-pass']) 1377 db.session.add(myemail_add)1378 db.session.commit()1379 flash("Correo registrado con éxito")1380 return redirect(url_for('config'))1381 except expression as identifier:1382 flash("Error, ese correo ya esta registrado")1383 return redirect(url_for('config'))1384 # = mail & != pass1385 elif existent_mail.mail == verify_user and existent_mail.mail_password != verify_pass:1386 try:1387 existent_mail.mail = request.form['miemail-email']1388 existent_mail.mail_password = request.form['miemail-pass'] 1389 db.session.commit()1390 flash("Contraseña cambiada con éxito")1391 return redirect(url_for('config'))1392 except expression as identifier:1393 flash("Error, ese correo ya esta registrado")1394 return redirect(url_for('config'))1395 # = mail & = pass1396 elif existent_mail.mail == verify_user and existent_mail.mail_password == verify_pass:1397 flash("Error, correo y contraseña ya estan registradas")1398 return redirect(url_for('config'))1399 1400@app.route('/config')1401def config():1402 contactquestions_amount = Contactquestions.query.filter_by(read=False).count()1403 return render_template("config.html", questions_amount=contactquestions_amount)1404@app.route('/regist-admin', methods=['POST'])1405@login_required1406def regist_admin():1407 try:1408 admin_add = Admins(user = request.form['admin-user'], 1409 password = request.form['admin-pass']) 1410 db.session.add(admin_add)1411 db.session.commit()1412 flash("Administrador registrado con éxito")1413 return redirect(url_for('config'))1414 except Exception as e:1415 print(e)1416 flash("Error, ese administrador ya esta registrado")1417 return redirect(url_for('config'))1418@app.route('/profile-admin/<id>')1419@login_required1420def profileforadmin(id):1421 get_property = Properties.query.filter_by(id = id).first()1422 comodidades = Comfort.query.filter_by(id = id).first()1423 seguridad = Seguridad.query.filter_by(id = id).first()1424 return render_template('profileforadmin.html', 1425 get_property = get_property, 1426 comfort = comodidades,...

Full Screen

Full Screen

device.py

Source:device.py Github

copy

Full Screen

...56 return self.dbus_method("CreateNode", uuid)57 def remove_node(self, node_path):58 return self.dbus_method("RemoveNode", node_path)59 ###Props60 def get_properties(self):61 return self.dbus_method("GetProperties")62 def set_property(self, key, value):63 return self.dbus_method("SetProperty", key, value)64 def get_name(self):65 if "Name" in self.get_properties().keys():66 return self.get_properties()["Name"]67 def get_vendor(self):68 if "Vendor" in self.get_properties().keys():69 return self.get_properties()["Vendor"]70 def get_product(self):71 if "Product" in self.get_properties().keys():72 return self.get_properties()["Product"]73 def get_version(self):74 if "Version" in self.get_properties().keys():75 return self.get_properties()["Version"]76 def get_legacy_pairing(self):77 if "LegacyPairing" in self.get_properties().keys():78 return self.get_properties()["LegacyPairing"]79 def get_alias(self):80 if "Alias" in self.get_properties().keys():81 return self.get_properties()["Alias"]82 def set_alias(self, alias):83 self.set_property("Alias", alias)84 def get_icon(self):85 if "Icon" in self.get_properties().keys():86 return self.get_properties()["Icon"]87 def get_nodes(self):88 nodes = []89 if "Nodes" in self.get_properties().keys():90 nodes = self.get_properties()["Nodes"]91 if nodes:92 nodes = map(lambda x:str(x), nodes)93 return nodes94 def get_paired(self):95 if "Paired" in self.get_properties().keys():96 return bool(self.get_properties()["Paired"])97 def get_connected(self):98 if "Connected" in self.get_properties().keys():99 return bool(self.get_properties()["Connected"])100 def get_blocked(self):101 if "Blocked" in self.get_properties().keys():102 return bool(self.get_properties()["Blocked"])103 def set_blocked(self, blocked):104 self.set_property("Blocked", dbus.Boolean(blocked))105 def get_trusted(self):106 if "Trusted" in self.get_properties().keys():107 return bool(self.get_properties()["Trusted"])108 def set_trusted(self, trusted):109 self.set_property("Trusted", dbus.Boolean(trusted))110 def get_adapter(self):111 if "Adapter" in self.get_properties().keys():112 return str(self.get_properties()["Adapter"])113 def get_address(self):114 if "Address" in self.get_properties().keys():115 return self.get_properties()["Address"]116 else:117 return None118 def get_class(self):119 if "Class" in self.get_properties().keys():120 return self.get_properties()["Class"]121 else:122 return None123 def get_uuids(self):124 uuids = []125 if "UUIDs" in self.get_properties().keys():126 uuids = self.get_properties()["UUIDs"]127 if uuids:128 uuids = map(lambda x:str(x), uuids)129 return uuids130 def get_services(self):131 if "Services" in self.get_properties().keys():132 services = self.get_properties()["Services"]133 if services:134 services = map(lambda x:str(x), services)135 return services136 return []137 def disconnect_requested_cb(self):138 self.emit("disconnect-requested")139 def property_changed_cb(self, key, value):140 self.emit("property-changed", key, value)141 def node_created_cb(self, node_path):142 self.emit("node-created", node_path)143 def node_removed_cb(self, node_path):144 self.emit("node-removed", node_path)145class Audio(BusBase):146 __gsignals__ = {147 "property-changed":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (str, gobject.TYPE_PYOBJECT))148 }149 def __init__(self, device_path):150 BusBase.__init__(self, path = device_path, interface = "org.bluez.Audio")151 self.bus.add_signal_receiver(self.property_changed_cb, dbus_interface = self.object_interface,152 path = self.object_path, signal_name = "PropertyChanged")153 def a_connect(self):154 return self.dbus_method("Connect")155 def a_disconnect(self):156 return self.dbus_method("Disconnect")157 def get_properties(self):158 return self.dbus_method("GetProperties")159 def get_state(self):160 if "State" in self.get_properties().keys():161 return self.get_properties()["State"]162 def property_changed_cb(self, key, value):163 self.emit("property-changed", key, value)164class Headset(BusBase):165 __gsignals__ = {166 "answer-requested":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),167 "property-changed":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (str, gobject.TYPE_PYOBJECT))168 }169 def __init__(self, device_path):170 BusBase.__init__(self, path = device_path, interface = "org.bluez.Headset")171 self.bus.add_signal_receiver(self.property_changed_cb, dbus_interface = self.object_interface,172 path = self.object_path, signal_name = "PropertyChanged")173 self.bus.add_signal_receiver(self.answer_requested_cb, dbus_interface = self.object_interface,174 path = self.object_path, signal_name = "AnswerRequested")175 def hs_connect(self):176 return self.dbus_method("Connect")177 def hs_disconnect(self):178 return self.dbus_method("Disconnect")179 def is_connected(self):180 return self.dbus_method("IsConnected")181 def indicate_call(self):182 return self.dbus_method("IndicateCall")183 def cancel_call(self):184 return self.dbus_method("CancelCall")185 def play(self):186 return self.dbus_method("Play")187 def stop(self):188 return self.dbus_method("Stop")189 def get_properties(self):190 return self.dbus_method("GetProperties")191 def set_property(self, key, value):192 return self.dbus_method("SetProperty", key, value)193 def get_state(self):194 if "State" in self.get_properties().keys():195 return self.get_properties()["State"]196 def get_connected(self):197 if "Connected" in self.get_properties().keys():198 return self.get_properties()["Connected"]199 def get_playing(self):200 if "Playing" in self.get_properties().keys():201 return self.get_properties()["Playing"]202 else:203 return self.dbus_method("IsPlaying")204 def get_speaker_gain(self):205 if "SpeakerGain" in self.get_properties().keys():206 return self.get_properties()["SpeakerGain"]207 else:208 return self.dbus_method("GetSpeakerGain")209 def set_speaker_gain(self, gain):210 self.set_property("SpeakerGain", gain)211 def get_microphone_gain(self):212 if "MicrophoneGain" in self.get_properties().keys():213 return self.get_properties()["MicrophoneGain"]214 else:215 return self.dbus_method("GetMicrophoneGain")216 def set_microphone_gain(self, gain):217 self.set_property("MicrophoneGain", gain)218 def property_changed_cb(self, key, value):219 self.emit("property-changed", key, value)220 def answer_requested_cb(self, key, value):221 self.emit("answer-requested", key, value)222class AudioSink(BusBase):223 __gsignals__ = {224 "property-changed":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (str, gobject.TYPE_PYOBJECT))225 }226 def __init__(self, device_path):227 BusBase.__init__(self, path = device_path, interface = "org.bluez.AudioSink")228 self.bus.add_signal_receiver(self.property_changed_cb, dbus_interface = self.object_interface,229 path = self.object_path, signal_name = "PropertyChanged")230 def as_connect(self):231 return self.dbus_method("Connect")232 def as_disconnect(self):233 return self.dbus_method("Disconnect")234 def get_properties(self):235 return self.dbus_method("GetProperties")236 def get_state(self):237 if "State" in self.get_properties().keys():238 return self.get_properties()["State"]239 def get_connected(self):240 if "Connected" in self.get_properties().keys():241 return self.get_properties()["Connected"]242 def get_playing(self):243 if "Playing" in self.get_properties().keys():244 return self.get_properties()["Playing"]245 def property_changed_cb(self, key, value):246 self.emit("property-changed", key, value)247class AudioSource(BusBase):248 __gsignals__ = {249 "property-changed":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (str, gobject.TYPE_PYOBJECT))250 }251 def __init__(self, device_path):252 BusBase.__init__(self, path = device_path, interface = "org.bluez.AudioSource")253 self.bus.add_signal_receiver(self.property_changed_cb, dbus_interface = self.object_interface,254 path = self.object_path, signal_name = "PropertyChanged")255 def as_connect(self):256 return self.dbus_method("Connect")257 def as_disconnect(self):258 return self.dbus_method("Disconnect")259 def get_properties(self):260 return self.dbus_method("GetProperties")261 def get_state(self):262 # Possible values: "disconnected", "connecting", "connected", "playing"263 if "State" in self.get_properties().keys():264 return self.get_properties()["State"]265 def property_changed_cb(self, key, value):266 self.emit("property-changed", key, value)267class HeadsetFreeGateway(BusBase):268 __gsignals__ = {269 "property-changed":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (str, gobject.TYPE_PYOBJECT)),270 "ring":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (str,)),271 "call-terminated":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),272 "call-started":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),273 "call-ended":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),274 }275 def __init__(self, device_path):276 BusBase.__init__(self, path = device_path, interface = "org.bluez.HeadsetGateway")277 self.bus.add_signal_receiver(self.property_changed_cb, dbus_interface = self.object_interface,278 path = self.object_path, signal_name = "PropertyChanged")279 self.bus.add_signal_receiver(self.ring_cb, dbus_interface = self.object_interface,280 path = self.object_path, signal_name = "Ring")281 self.bus.add_signal_receiver(self.call_terminated_cb, dbus_interface = self.object_interface,282 path = self.object_path, signal_name = "CallTerminated")283 self.bus.add_signal_receiver(self.call_started_cb, dbus_interface = self.object_interface,284 path = self.object_path, signal_name = "CallStarted")285 self.bus.add_signal_receiver(self.call_ended_cb, dbus_interface = self.object_interface,286 path = self.object_path, signal_name = "CallEnded")287 def hfg_connect(self):288 return self.dbus_method("Connect")289 def hfg_disconnect(self):290 return self.dbus_method("Disconnect")291 def answer_call(self):292 return self.dbus_method("AnswerCall")293 def terminate_call(self):294 return self.dbus_method("TerminateCall")295 def call(self, number):296 return self.dbus_method("Call", number)297 def get_operator_name(self):298 return self.dbus_method("GetOperatorName")299 def send_dtmf(self, digits):300 return self.dbus_method("SendDTMF", digits)301 def get_subscriber_number(self):302 return self.dbus_method("GetSubscriberNumber")303 def get_properties(self):304 return self.dbus_method("GetProperties")305 def get_connected(self):306 if "Connected" in self.get_properties().keys():307 return self.get_properties()["Connected"]308 def get_registration_status(self):309 if "RegistrationStatus" in self.get_properties().keys():310 return self.get_properties()["RegistrationStatus"]311 def get_signal_strength(self):312 if "SignalStrength" in self.get_properties().keys():313 return self.get_properties()["SignalStrength"]314 def get_roaming_status(self):315 if "RoamingStatus" in self.get_properties().keys():316 return self.get_properties()["RoamingStatus"]317 def get_battery_charge(self):318 if "BatteryCharge" in self.get_properties().keys():319 return self.get_properties()["BatteryCharge"]320 def get_speaker_gain(self):321 if "Connected" in self.get_properties().keys():322 return self.get_properties()["Connected"]323 def get_microphone_gain(self):324 if "MicrophoneGain" in self.get_properties().keys():325 return self.get_properties()["MicrophoneGain"]326 def property_changed_cb(self, key, value):327 self.emit("property-changed", key, value)328 def ring_cb(self, number):329 self.emit("ring", number)330 def call_terminated_cb(self):331 self.emit("call-terminated")332 def call_started_cb(self):333 self.emit("call-started")334 def call_ended_cb(self):335 self.emit("call-ended")336class Control(BusBase):337 __gsignals__ = {338 "connected":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),339 "disconnected":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),340 "property-changed":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (str, gobject.TYPE_PYOBJECT))341 }342 def __init__(self, device_path):343 BusBase.__init__(self, path = device_path, interface = "org.bluez.Control")344 self.bus.add_signal_receiver(self.connected_cb, dbus_interface = self.object_interface,345 path = self.object_path, signal_name = "Connected")346 self.bus.add_signal_receiver(self.disconnected_cb, dbus_interface = self.object_interface,347 path = self.object_path, signal_name = "Disconnected")348 self.bus.add_signal_receiver(self.property_changed_cb, dbus_interface = self.object_interface,349 path = self.object_path, signal_name = "PropertyChanged")350 def volume_up(self):351 return self.dbus_method("VolumeUp")352 def volume_down(self):353 return self.dbus_method("VolumeDown")354 def get_properties(self):355 return self.dbus_method("GetProperties")356 def get_connected(self):357 if "Connected" in self.get_properties().keys():358 return self.get_properties()["Connected"]359 else:360 return bool(self.dbus_method("IsConnected"))361 def connected_cb(self):362 self.emit("connected")363 def disconnected_cb(self):364 self.emit("disconnected")365 def property_changed_cb(self, key, value):366 self.emit("property-changed", key, value)367class HealthManager(BusBase):368 __gsignals__ = {369 "channel-connected":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (str,)),370 "channel-deleted":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (str,)),371 "property-changed":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (str, gobject.TYPE_PYOBJECT))372 }373 def __init__(self, device_path):374 BusBase.__init__(self, path = device_path, interface = "org.bluez.HealthDevice")375 self.bus.add_signal_receiver(self.channel_connected_cb, dbus_interface = self.object_interface,376 path = self.object_path, signal_name = "ChannelConnected")377 self.bus.add_signal_receiver(self.channel_deleted_cb, dbus_interface = self.object_interface,378 path = self.object_path, signal_name = "ChannelDeleted")379 self.bus.add_signal_receiver(self.property_changed_cb, dbus_interface = self.object_interface,380 path = self.object_path, signal_name = "PropertyChanged")381 def echo(self):382 return self.dbus_method("Echo")383 def create_channel(self, application, configuration):384 return self.dbus_method("CreateChannel", application, configuration)385 def destroy_channel(self, channel):386 return self.dbus_method("DestroyChannel", channel)387 def get_properties(self):388 return self.dbus_method("GetProperties")389 def get_mainchannel(self):390 if "MainChannel" in self.get_properties().keys():391 return self.get_properties()["MainChannel"]392 def channel_connected_cb(self, channel):393 self.emit("channel-connected", channel)394 def channel_deleted_cb(self, channel):395 self.emit("disconnected", channel)396 def property_changed_cb(self, key, value):397 self.emit("property-changed", key, value)398class HandsfreeGateway(BusBase):399 __gsignals__ = {400 "property-changed":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (str, gobject.TYPE_PYOBJECT))401 }402 def __init__(self, device_path):403 BusBase.__init__(self, path = device_path, interface = "org.bluez.HandsfreeGateway")404 self.bus.add_signal_receiver(self.property_changed_cb, dbus_interface = self.object_interface,405 path = self.object_path, signal_name = "PropertyChanged")406 def hfg_connect(self):407 return self.dbus_method("Connect")408 def hfg_disconnect(self):409 return self.dbus_method("Disconnect")410 def get_properties(self):411 return self.dbus_method("GetProperties")412 def get_state(self):413 if "State" in self.get_properties().keys():414 return self.get_properties()["State"]415 def register_agent(self, agent_path):416 return self.dbus_method("RegisterAgent", agent_path)417 def unregister_agent(self, agent_path):418 return self.dbus_method("UnregisterAgent", agent_path)419 def property_changed_cb(self, key, value):420 self.emit("property-changed", key, value)421class Network(BusBase):422 __gsignals__ = {423 "property-changed":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (str, gobject.TYPE_PYOBJECT))424 }425 def __init__(self, device_path):426 BusBase.__init__(self, path = device_path, interface = "org.bluez.Network")427 self.bus.add_signal_receiver(self.property_changed_cb, dbus_interface = self.object_interface,428 path = self.object_path, signal_name = "PropertyChanged")429 def n_connect(self, uuid):430 return self.dbus_method("Connect", uuid)431 def n_disconnect(self):432 return self.dbus_method("Disconnect")433 def get_properties(self):434 return self.dbus_method("GetProperties")435 def get_connected(self):436 if "Connected" in self.get_properties().keys():437 return self.get_properties()["Connected"]438 def get_interface(self):439 if "Interface" in self.get_properties().keys():440 return self.get_properties()["Interface"]441 def get_uuid(self):442 if "UUID" in self.get_properties().keys():443 return self.get_properties()["UUID"]444 def property_changed_cb(self, key, value):445 self.emit("property-changed", key, value)446class Input(BusBase):447 __gsignals__ = {448 "property-changed":(gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (str, gobject.TYPE_PYOBJECT))449 }450 def __init__(self, device_path):451 BusBase.__init__(self, path = device_path, interface = "org.bluez.Input")452 self.bus.add_signal_receiver(self.property_changed_cb, dbus_interface = self.object_interface,453 path = self.object_path, signal_name = "PropertyChanged")454 def i_connect(self):455 return self.dbus_method("Connect")456 def i_disconnect(self):457 return self.dbus_method("Disconnect")458 def get_properties(self):459 return self.dbus_method("GetProperties")460 def get_connected(self):461 if "Connected" in self.get_properties().keys():462 return self.get_properties()["Connected"]463 def property_changed_cb(self, key, value):464 self.emit("property-changed", key, value)465class Serial(BusBase):466 def __init__(self, device_path):467 BusBase.__init__(self, path = device_path, interface = "org.bluez.Serial")468 def s_connect(self, pattern):469 return self.dbus_method("Connect", pattern)470 def connect_fd(self, pattern):471 return self.dbus_method("ConnectFD", pattern)472 def s_disconnect(self, device):473 return self.dbus_method("Disconnect", device)474if __name__ == "__main__":475 from manager import Manager476 from adapter import Adapter...

Full Screen

Full Screen

auto_doc.py

Source:auto_doc.py Github

copy

Full Screen

...9 ),10 },11 "feature_store.md": {12 "fs_get": ["hsfs.connection.Connection.get_feature_store"],13 "fs_properties": keras_autodoc.get_properties(14 "hsfs.feature_store.FeatureStore"15 ),16 "fs_methods": keras_autodoc.get_methods(17 "hsfs.feature_store.FeatureStore", exclude=["from_response_json"]18 ),19 },20 "feature.md": {21 "feature": ["hsfs.feature.Feature"],22 "feature_properties": keras_autodoc.get_properties("hsfs.feature.Feature"),23 "feature_methods": keras_autodoc.get_methods(24 "hsfs.feature.Feature", exclude=["from_response_json", "to_dict"]25 ),26 },27 "feature_group.md": {28 "fg_create": ["hsfs.feature_store.FeatureStore.create_feature_group"],29 "fg_get": ["hsfs.feature_store.FeatureStore.get_feature_group"],30 "fg_properties": keras_autodoc.get_properties(31 "hsfs.feature_group.FeatureGroup"32 ),33 "fg_methods": keras_autodoc.get_methods(34 "hsfs.feature_group.FeatureGroup",35 exclude=[36 "from_response_json",37 "update_from_response_json",38 "json",39 "to_dict",40 ],41 ),42 },43 "on_demand_feature_group.md": {44 "fg_create": ["hsfs.feature_store.FeatureStore.create_on_demand_feature_group"],45 "fg_get": ["hsfs.feature_store.FeatureStore.get_on_demand_feature_group"],46 "fg_properties": keras_autodoc.get_properties(47 "hsfs.feature_group.OnDemandFeatureGroup"48 ),49 "fg_methods": keras_autodoc.get_methods(50 "hsfs.feature_group.OnDemandFeatureGroup",51 exclude=[52 "from_response_json",53 "update_from_response_json",54 "json",55 "to_dict",56 ],57 ),58 },59 "training_dataset.md": {60 "td_create": ["hsfs.feature_store.FeatureStore.create_training_dataset"],61 "td_get": ["hsfs.feature_store.FeatureStore.get_training_dataset"],62 "td_properties": keras_autodoc.get_properties(63 "hsfs.training_dataset.TrainingDataset"64 ),65 "td_methods": keras_autodoc.get_methods(66 "hsfs.training_dataset.TrainingDataset",67 exclude=[68 "from_response_json",69 "update_from_response_json",70 "json",71 "to_dict",72 ],73 ),74 "tf_record_dataset": ["hsfs.core.tfdata_engine.TFDataEngine.tf_record_dataset"],75 "tf_csv_dataset": ["hsfs.core.tfdata_engine.TFDataEngine.tf_csv_dataset"],76 },77 "storage_connector.md": {78 "sc_get": [79 "hsfs.feature_store.FeatureStore.get_storage_connector",80 "hsfs.feature_store.FeatureStore.get_online_storage_connector",81 ],82 "hopsfs_methods": keras_autodoc.get_methods(83 "hsfs.storage_connector.HopsFSConnector", exclude=["from_response_json"]84 ),85 "hopsfs_properties": keras_autodoc.get_properties(86 "hsfs.storage_connector.HopsFSConnector"87 ),88 "s3_methods": keras_autodoc.get_methods(89 "hsfs.storage_connector.S3Connector", exclude=["from_response_json"]90 ),91 "s3_properties": keras_autodoc.get_properties(92 "hsfs.storage_connector.S3Connector"93 ),94 "redshift_methods": keras_autodoc.get_methods(95 "hsfs.storage_connector.RedshiftConnector", exclude=["from_response_json"]96 ),97 "redshift_properties": keras_autodoc.get_properties(98 "hsfs.storage_connector.RedshiftConnector"99 ),100 "adls_methods": keras_autodoc.get_methods(101 "hsfs.storage_connector.AdlsConnector", exclude=["from_response_json"]102 ),103 "adls_properties": keras_autodoc.get_properties(104 "hsfs.storage_connector.AdlsConnector"105 ),106 "snowflake_methods": keras_autodoc.get_methods(107 "hsfs.storage_connector.SnowflakeConnector", exclude=["from_response_json"]108 ),109 "snowflake_properties": keras_autodoc.get_properties(110 "hsfs.storage_connector.SnowflakeConnector"111 ),112 "jdbc_methods": keras_autodoc.get_methods(113 "hsfs.storage_connector.JdbcConnector", exclude=["from_response_json"]114 ),115 "jdbc_properties": keras_autodoc.get_properties(116 "hsfs.storage_connector.JdbcConnector"117 ),118 "gcs_methods": keras_autodoc.get_methods(119 "hsfs.storage_connector.GcsConnector", exclude=["from_response_json"]120 ),121 "gcs_properties": keras_autodoc.get_properties(122 "hsfs.storage_connector.GcsConnector"123 ),124 },125 "query_vs_dataframe.md": {126 "query_methods": keras_autodoc.get_methods("hsfs.constructor.query.Query"),127 "query_properties": keras_autodoc.get_properties(128 "hsfs.constructor.query.Query"129 ),130 },131 "statistics.md": {132 "statistics_config": ["hsfs.statistics_config.StatisticsConfig"],133 "statistics_config_properties": keras_autodoc.get_properties(134 "hsfs.statistics_config.StatisticsConfig"135 ),136 },137 "feature_validation.md": {138 "rule": ["hsfs.rule.Rule"],139 "rule_properties": keras_autodoc.get_properties("hsfs.rule.Rule"),140 "ruledefinition": ["hsfs.ruledefinition.RuleDefinition"],141 "ruledefinition_getall": ["hsfs.connection.Connection.get_rules"],142 "ruledefinition_get": ["hsfs.connection.Connection.get_rule"],143 "ruledefinition_properties": keras_autodoc.get_properties(144 "hsfs.ruledefinition.RuleDefinition"145 ),146 "expectation": ["hsfs.expectation.Expectation"],147 "expectation_properties": keras_autodoc.get_properties(148 "hsfs.expectation.Expectation"149 ),150 "expectation_methods": keras_autodoc.get_methods(151 "hsfs.expectation.Expectation",152 exclude=[153 "from_response_json",154 "update_from_response_json",155 "json",156 "to_dict",157 ],158 ),159 "expectation_create": ["hsfs.feature_store.FeatureStore.create_expectation"],160 "expectation_get": ["hsfs.feature_store.FeatureStore.get_expectation"],161 "expectation_getall": ["hsfs.feature_store.FeatureStore.get_expectations"],162 "validation_result": ["hsfs.validation_result.ValidationResult"],163 "validation_result_properties": keras_autodoc.get_properties(164 "hsfs.validation_result.ValidationResult"165 ),166 "validate": ["hsfs.feature_group.FeatureGroup.validate"],167 "validation_result_get": ["hsfs.feature_group.FeatureGroup.get_validations"],168 },169 "tags.md": {170 "fg_tag_add": ["hsfs.feature_group.FeatureGroupBase.add_tag"],171 "fg_tag_get": ["hsfs.feature_group.FeatureGroupBase.get_tag"],172 "fg_tag_get_all": ["hsfs.feature_group.FeatureGroupBase.get_tags"],173 "fg_tag_delete": ["hsfs.feature_group.FeatureGroupBase.delete_tag"],174 "td_tag_add": ["hsfs.training_dataset.TrainingDataset.add_tag"],175 "td_tag_get": ["hsfs.training_dataset.TrainingDataset.get_tag"],176 "td_tag_get_all": ["hsfs.training_dataset.TrainingDataset.get_tags"],177 "td_tag_delete": ["hsfs.training_dataset.TrainingDataset.delete_tag"],178 },179 "transformation_functions.md": {180 "transformation_function": [181 "hsfs.transformation_function.TransformationFunction"182 ],183 "transformation_function_properties": keras_autodoc.get_properties(184 "hsfs.transformation_function.TransformationFunction"185 ),186 "transformation_function_methods": keras_autodoc.get_methods(187 "hsfs.transformation_function.TransformationFunction",188 exclude=[189 "from_response_json",190 "update_from_response_json",191 "json",192 "to_dict",193 ],194 ),195 "create_transformation_function": [196 "hsfs.feature_store.FeatureStore.create_transformation_function"197 ],198 "get_transformation_function": [199 "hsfs.feature_store.FeatureStore.get_transformation_function"200 ],201 "get_transformation_functions": [202 "hsfs.feature_store.FeatureStore.get_transformation_functions"203 ],204 },205 "api/connection_api.md": {206 "connection": ["hsfs.connection.Connection"],207 "connection_properties": keras_autodoc.get_properties(208 "hsfs.connection.Connection"209 ),210 "connection_methods": keras_autodoc.get_methods("hsfs.connection.Connection"),211 },212 "api/feature_store_api.md": {213 "fs": ["hsfs.feature_store.FeatureStore"],214 "fs_get": ["hsfs.connection.Connection.get_feature_store"],215 "fs_properties": keras_autodoc.get_properties(216 "hsfs.feature_store.FeatureStore"217 ),218 "fs_methods": keras_autodoc.get_methods("hsfs.feature_store.FeatureStore"),219 },220 "api/feature_group_api.md": {221 "fg": ["hsfs.feature_group.FeatureGroup"],222 "fg_create": ["hsfs.feature_store.FeatureStore.create_feature_group"],223 "fg_get": ["hsfs.feature_store.FeatureStore.get_feature_group"],224 "fg_properties": keras_autodoc.get_properties(225 "hsfs.feature_group.FeatureGroup"226 ),227 "fg_methods": keras_autodoc.get_methods("hsfs.feature_group.FeatureGroup"),228 },229 "api/training_dataset_api.md": {230 "td": ["hsfs.training_dataset.TrainingDataset"],231 "td_create": ["hsfs.feature_store.FeatureStore.create_training_dataset"],232 "td_get": ["hsfs.feature_store.FeatureStore.get_training_dataset"],233 "td_properties": keras_autodoc.get_properties(234 "hsfs.training_dataset.TrainingDataset"235 ),236 "td_methods": keras_autodoc.get_methods(237 "hsfs.training_dataset.TrainingDataset"238 ),239 },240 "api/feature_api.md": {241 "feature": ["hsfs.feature.Feature"],242 "feature_properties": keras_autodoc.get_properties("hsfs.feature.Feature"),243 "feature_methods": keras_autodoc.get_methods("hsfs.feature.Feature"),244 },245 "api/storage_connector_api.md": {246 "sc_get": [247 "hsfs.feature_store.FeatureStore.get_storage_connector",248 "hsfs.feature_store.FeatureStore.get_online_storage_connector",249 ],250 "hopsfs_methods": keras_autodoc.get_methods(251 "hsfs.storage_connector.HopsFSConnector", exclude=["from_response_json"]252 ),253 "hopsfs_properties": keras_autodoc.get_properties(254 "hsfs.storage_connector.HopsFSConnector"255 ),256 "s3_methods": keras_autodoc.get_methods(257 "hsfs.storage_connector.S3Connector", exclude=["from_response_json"]258 ),259 "s3_properties": keras_autodoc.get_properties(260 "hsfs.storage_connector.S3Connector"261 ),262 "redshift_methods": keras_autodoc.get_methods(263 "hsfs.storage_connector.RedshiftConnector", exclude=["from_response_json"]264 ),265 "redshift_properties": keras_autodoc.get_properties(266 "hsfs.storage_connector.RedshiftConnector"267 ),268 "adls_methods": keras_autodoc.get_methods(269 "hsfs.storage_connector.AdlsConnector", exclude=["from_response_json"]270 ),271 "adls_properties": keras_autodoc.get_properties(272 "hsfs.storage_connector.AdlsConnector"273 ),274 "snowflake_methods": keras_autodoc.get_methods(275 "hsfs.storage_connector.SnowflakeConnector", exclude=["from_response_json"]276 ),277 "snowflake_properties": keras_autodoc.get_properties(278 "hsfs.storage_connector.SnowflakeConnector"279 ),280 "jdbc_methods": keras_autodoc.get_methods(281 "hsfs.storage_connector.JdbcConnector", exclude=["from_response_json"]282 ),283 "jdbc_properties": keras_autodoc.get_properties(284 "hsfs.storage_connector.JdbcConnector"285 ),286 "gcs_methods": keras_autodoc.get_methods(287 "hsfs.storage_connector.GcsConnector", exclude=["from_response_json"]288 ),289 "gcs_properties": keras_autodoc.get_properties(290 "hsfs.storage_connector.GcsConnector"291 ),292 },293 "api/statistics_config_api.md": {294 "statistics_config": ["hsfs.statistics_config.StatisticsConfig"],295 "statistics_config_properties": keras_autodoc.get_properties(296 "hsfs.statistics_config.StatisticsConfig"297 ),298 },299 "api/rule_api.md": {300 "rule": ["hsfs.rule.Rule"],301 "rule_properties": keras_autodoc.get_properties("hsfs.rule.Rule"),302 },303 "api/rule_definition_api.md": {304 "ruledefinition": ["hsfs.ruledefinition.RuleDefinition"],305 "ruledefinition_getall": ["hsfs.connection.Connection.get_rules"],306 "ruledefinition_get": ["hsfs.connection.Connection.get_rule"],307 "ruledefinition_properties": keras_autodoc.get_properties(308 "hsfs.ruledefinition.RuleDefinition"309 ),310 },311 "api/expectation_api.md": {312 "expectation": ["hsfs.expectation.Expectation"],313 "expectation_properties": keras_autodoc.get_properties(314 "hsfs.expectation.Expectation"315 ),316 "expectation_methods": keras_autodoc.get_methods(317 "hsfs.expectation.Expectation",318 exclude=[319 "from_response_json",320 "update_from_response_json",321 "json",322 "to_dict",323 ],324 ),325 "expectation_create": ["hsfs.feature_store.FeatureStore.create_expectation"],326 "expectation_get": ["hsfs.feature_store.FeatureStore.get_expectation"],327 "expectation_getall": ["hsfs.feature_store.FeatureStore.get_expectations"],328 },329 "api/validation_api.md": {330 "validation_result": ["hsfs.validation_result.ValidationResult"],331 "validation_result_properties": keras_autodoc.get_properties(332 "hsfs.validation_result.ValidationResult"333 ),334 "validate": ["hsfs.feature_group.FeatureGroup.validate"],335 "validation_result_get": ["hsfs.feature_group.FeatureGroup.get_validations"],336 },337 "api/transformation_functions_api.md": {338 "transformation_function": [339 "hsfs.transformation_function.TransformationFunction"340 ],341 "transformation_function_properties": keras_autodoc.get_properties(342 "hsfs.transformation_function.TransformationFunction"343 ),344 "transformation_function_methods": keras_autodoc.get_methods(345 "hsfs.transformation_function.TransformationFunction",346 exclude=[347 "from_response_json",348 "update_from_response_json",349 "json",350 "to_dict",351 ],352 ),353 "create_transformation_function": [354 "hsfs.feature_store.FeatureStore.create_transformation_function"355 ],356 "get_transformation_function": [357 "hsfs.feature_store.FeatureStore.get_transformation_function"358 ],359 "get_transformation_functions": [360 "hsfs.feature_store.FeatureStore.get_transformation_functions"361 ],362 },363 "api/job_configuration.md": {364 "job_configuration": ["hsfs.core.job_configuration.JobConfiguration"]365 },366 "api/query_api.md": {367 "query_methods": keras_autodoc.get_methods(368 "hsfs.constructor.query.Query",369 exclude=["json", "to_dict"],370 ),371 "query_properties": keras_autodoc.get_properties(372 "hsfs.constructor.query.Query"373 ),374 },375 "versioning.md": {376 "fg_append": ["hsfs.feature_group.FeatureGroup.append_features"],377 "fg_get_all": ["hsfs.feature_store.FeatureStore.get_feature_groups"],378 "td_get_all": ["hsfs.feature_store.FeatureStore.get_training_datasets"],379 "as_of": ["hsfs.constructor.query.Query.as_of"],380 "commit_details": ["hsfs.feature_group.FeatureGroup.commit_details"],381 },382}383hsfs_dir = pathlib.Path(__file__).resolve().parents[0]384def generate(dest_dir):385 doc_generator = keras_autodoc.DocumentationGenerator(...

Full Screen

Full Screen

typeCount.py

Source:typeCount.py Github

copy

Full Screen

...26# b = graph_db.get_indexed_node("employerIdIndex","id","105454359493345")27# print b28# print graph_db.neo4j_version29# a = graph_db.node(7)30# print a.get_properties()31# print a.get_properties()['nodeType'] == 132# c = graph_db.get_or_create_index(neo4j.Node, "employerIdIndex")33# print c34# tmp = graph_db.node(7)35# print tmp.get_properties()['nodeType']36#from first 10000 nodes37#{0: 3503, 1: 3760, 2: 2326, 3: 1, 4: 1, 5: 1, 6: 0, 7: 0}38# store = {0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0}39# for i in range(1,10000): #node 0 does not have nodeType40# # print i41# try:42# tmp = graph_db.node(i).get_properties() 43# except:44# print "No data"45# continue46# store[tmp["nodeType"]] += 147# print store48#from first 1000 who are co-workers, list of companies49# companies = []50# for i in range(1,1000):51# try:52# tmp = graph_db.node(i).get_properties() 53# except:54# print "No data"55# continue56# if tmp["nodeType"] == 1:57# companies.append(tmp["name"])58# print set(companies)59##############################################60typechart = {"Type1":0,"Type2":0,"Type3":0,"Type4":0,"Type5":0,"Type6":0,"Type7":0,"Type8":0}61# human = []62# for i in Xrange(1,100):63# try:64# tmp = graph_db.node(i).get_properties() 65# except:66# print "No data"67# continue68# if tmp["nodeType"] == 0:69# human.append(i)70# print human71def typeCount(typechart,node):72 # node = graph_db.node(nodeID)73 school = {"College":[],"High School":[],"Graduate School":[]}74 schools = list(node.match_outgoing(rel_type = "STUDIED", end_node = None))75 for i in xrange(0,len(schools)):76 rel = graph_db.relationship(schools[i]._id)77 school[rel.get_properties()["educationType"]].append(schools[i].end_node.get_properties()["name"])78 print school79 company = []80 #WORKED_AT81 companies = list(node.match_outgoing(rel_type = "WORKED_AT", end_node = None))82 for i in xrange(0,len(companies)):83 company.append(companies[i].end_node.get_properties()["name"])84 #WORKS_AT85 companies = list(node.match_outgoing(rel_type = "WORKS_AT", end_node = None))86 for i in xrange(0,len(companies)):87 company.append(companies[i].end_node.get_properties()["name"])88 print company89 #CONNECTED NODES90 connections = list(node.match_outgoing(rel_type = "CONNECTED", end_node = None)) + \91 list(node.match_incoming(rel_type = "CONNECTED"))92 connectionschool = {"College":[],"High School":[],"Graduate School":[]}93 connectioncompany = []94 print "This is connections size:"95 print len(connections)96 #if end node is itself, use start node!!!!97 for i in xrange(0,len(connections)):98 if connections[i].end_node == node:99 print "node and end node are the same!"100 connectioncompanies = list(connections[i].start_node.match_outgoing(rel_type = "WORKS_AT", end_node = None))101 else:102 connectioncompanies = list(connections[i].end_node.match_outgoing(rel_type = "WORKS_AT", end_node = None))103 print "This is connection companies"104 print len(connectioncompanies)105 #works_at106 for j in xrange(0,len(connectioncompanies)):107 connectioncompany.append(connectioncompanies[j].end_node.get_properties()["name"])108 #worked_at109 if connections[i].end_node == node:110 print "node and end node are the same!"111 connectioncompanies = list(connections[i].start_node.match_outgoing(rel_type = "WORKED_AT", end_node = None))112 else:113 connectioncompanies = list(connections[i].end_node.match_outgoing(rel_type = "WORKED_AT", end_node = None))114 for k in xrange(0,len(connectioncompanies)):115 connectioncompany.append(connectioncompanies[k].end_node.get_properties()["name"])116 if connections[i].end_node == node:117 print "node and end node are the same!"118 connectionschools = list(connections[i].start_node.match_outgoing(rel_type = "STUDIED", end_node = None))119 else:120 connectionschools = list(connections[i].end_node.match_outgoing(rel_type = "STUDIED", end_node = None))121 for l in xrange(0,len(connectionschools)):122 rel = graph_db.relationship(connectionschools[l]._id)123 try:124 connectionschool[rel.get_properties()["educationType"]].append(connectionschools[l].end_node.get_properties()["name"])125 except:126 continue127 # print "connection high school"128 # print set(connectionschool["High School"])129 # print connectionschool130 # print connectioncompany131 highschool = list(set(school["High School"]) & set(connectionschool["High School"]))132 college = list(set(school["College"]) & set(connectionschool["College"]) & set(connectionschool["Graduate School"]))133 company_intercept = list(set(company) & set(connectioncompany))134 print "Here are the interceptions:"135 print highschool136 print college137 print company_intercept138 if len(highschool)!=0:139 typechart["Type2"]+=1140 print "same highschool"141 elif len(college)!=0:142 typechart["Type3"]+=1143 print "same college"144 elif len(company_intercept)!=0:145 typechart["Type4"]+=1146 elif len(company_intercept) and len(highschool)!=0:147 typechart["Type5"]+=1148 elif len(company_intercept) and len(college)!=0:149 typechart["Type6"]+=1150 elif len(highschool) != 0 and len(college) !=0:151 typechart["Type7"]+=1152 elif len(highschool) != 0 and len(college) !=0 and len(company_intercept):153 typechart["Type8"]+=1154 else:155 typechart["Type1"]+=1156 #reset the connectionschool and connectioncompany157 connectionschool = {"College":[],"High School":[],"Graduate School":[]}158 connectioncompany = []159 return typechart160query = neo4j.CypherQuery(graph_db, "START n = node(*) WHERE has(n.nodeType) AND n.nodeType = 0 RETURN n LIMIT 1;")161record = list(query.stream())162node = record[0][0]163connectionschool = {"College":[],"High School":[],"Graduate School":[]}164connectionschools = []165connectioncompany = []166# print node167# connections = list(node.match_outgoing(rel_type = "CONNECTED", end_node = None)) + \168# list(node.match_incoming(rel_type = "CONNECTED"))169# a = connections[len(connections)-1].start_node170# connectioncompanies = list(a.match_outgoing(rel_type = "WORKED_AT", end_node = None))171connectionschools = list(node.match_outgoing(rel_type = "STUDIED", end_node = None))172for i in xrange(0,len(connectionschools)):173 # print schools[i]._id174 rel = graph_db.relationship(connectionschools[i]._id)175 # print rel.get_properties()["educationType"]176 connectionschool[rel.get_properties()["educationType"]].append(connectionschools[i].end_node.get_properties()["name"])177print connectionschool178# for k in xrange(0,len(connectioncompanies)):179# connectioncompany.append(connectioncompanies[k].end_node.get_properties()["name"])180# for l in xrange(0,len(connectionschools)):181# rel = graph_db.relationship(connectionschools[l]._id)182# try:183# connectionschool[rel.get_properties()["educationType"]].append(connectionschools[l].end_node.get_properties()["name"])184# except:185# continue186# print connectionschools[1]187# print connectionschools[1]._id188# rel = graph_db.relationship(5)189# print rel.get_properties()190# print rel.get_properties()["educationType"]191# print connectionschools[0].end_node.get_properties()["name"]192# print connectioncompany193# a = graph_db.node(11)194# print a.get_properties()195# print connectionschool196#################################################GOOD BELOW197# for record in query.stream():198# node = record[0]199# typeCount(typechart,node)200# print typechart201# print typeCount(typechart,12)202end_time = time.time()203print("Elapsed time was %g seconds" % (end_time - start_time))204body = "Elapsed time was %g seconds" % (end_time - start_time)205 206"Sends an e-mail to the specified recipient."207 208body = body + " : " + str(typechart)209 210headers = ["From: " + sender,211 "Subject: " + subject,212 "To: " + recipient,213 "MIME-Version: 1.0",214 "Content-Type: text/html"]215headers = "\r\n".join(headers)216 217session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)218 219session.ehlo()220session.starttls()221session.ehlo222session.login(sender, password)223 224#session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)225#session.quit()226# Connected + Nothing else = Type 1227# Connected + high-school = Type 2228# Connected + college-mate = Type 3229# Connected + co-worker = Type 4230# Connected + co-worker + high-school = Type 5231# Connected + co-worker + college mate = Type 6232# Connected + high-school + college mate = Type 7233# Connected + high school + college mate +co-worker = Type 8234#find particular nodes' high school and college235# node = graph_db.node(727)236# school = {"College":[],"High School":[]}237# schools = list(node.match_outgoing(rel_type = "STUDIED", end_node = None))238# for i in xrange(0,len(schools)):239# # print schools[i]._id240# rel = graph_db.relationship(schools[i]._id)241# # print rel.get_properties()["educationType"]242# school[rel.get_properties()["educationType"]].append(schools[i].end_node.get_properties()["name"])243# print school244# company = []245# #WORKED_AT246# companies = list(node.match_outgoing(rel_type = "WORKED_AT", end_node = None))247# for i in xrange(0,len(companies)):248# rel = graph_db.relationship(companies[i]._id)249# company.append(companies[i].end_node.get_properties()["name"])250# #WORKS_AT251# companies = list(node.match_outgoing(rel_type = "WORKS_AT", end_node = None))252# for i in xrange(0,len(companies)):253# # print schools[i]._id254# rel = graph_db.relationship(companies[i]._id)255# # print rel.get_properties()["educationType"]256# company.append(companies[i].end_node.get_properties()["name"])257# print company258# #CONNECTED NODES259# connections = list(node.match_outgoing(rel_type = "CONNECTED", end_node = None))260# connectionschool = {"College":[],"High School":[]}261# connectioncompany = []262# print connections[0].end_node263# #works_at264# connectioncompanies = list(connections[0].end_node.match_outgoing(rel_type = "WORKS_AT", end_node = None))265# print connectioncompanies266# for i in xrange(0,len(connectioncompanies)):267# # print schools[i]._id268# rel = graph_db.relationship(connectioncompanies[i]._id)269# # print rel.get_properties()["educationType"]270# connectioncompany.append(connectioncompanies[i].end_node.get_properties()["name"])271# print "this is connection company:"272# print connectioncompany273# #worked_at274# connectioncompanies = list(connections[0].end_node.match_outgoing(rel_type = "WORKED_AT", end_node = None))275# print connectioncompanies276# for i in xrange(0,len(connectioncompanies)):277# # print schools[i]._id278# rel = graph_db.relationship(connectioncompanies[i]._id)279# # print rel.get_properties()["educationType"]280# connectioncompany.append(connectioncompanies[i].end_node.get_properties()["name"])281# connectionschools = list(connections[0].end_node.match_outgoing(rel_type = "STUDIED", end_node = None))282# for i in xrange(0,len(connectionschools)):283# # print schools[i]._id284# rel = graph_db.relationship(connectionschools[i]._id)285# # print rel.get_properties()["educationType"]286# connectionschool[rel.get_properties()["educationType"]].append(connectionschools[i].end_node.get_properties()["name"])287# highschool = list(set(school["High School"]) & set(connectionschool["High School"]))288# college = list(set(school["College"]) & set(connectionschool["College"]))289# company_intercept = list(set(company) & set(connectioncompany))290# print highschool291# print college292# if len(highschool)!=0:293# typechart["Type2"]+=1294# print "same highschool"295# if len(college)!=0:296# typechart["Type3"]+=1297# print "same college"298# if len(highschool) != 0 and len(college) !=0:299# typechart["Type7"]+=1300# print "same highschool and college"301# print typechart302#print list(set(school["High School"]) & set(connectionschool["High School"]))303#print list(set(school["College"]) & set(connectionschool["College"]))304# print node.get_properties()305# node 12 check all his connection type306# node = graph_db.node(12)307# human = graph_db.get_indexed_relationship("userIdIndex","CONNECTED","12")308# connections = list(node.match_outgoing(rel_type = "CONNECTED", end_node = None))309# connections = list(node.match_outgoing(rel_type = "STUDIED", end_node = None))310# print connections[0]._id311# b = graph_db.relationship(connections[0]._id)312# b.get_properties()["educationType"]313# print b.get_properties()314# name = connections[0].end_node315# print name.get_properties()["name"]316# print(type(connections))317# url = "http://localhost:8001/db/data/relationship/122969794"318# new = neo4j.Node(url)319# print new.get_properties()320# b = graph_db.relationship(122969794)321# print b.get_properties()322# human.get_indexes(neo4j.Relationship)323# print human324# b = graph_db.relationship(122969750)...

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful