def post(self): id = self.get_argument("id-contacto", "") name = self.get_argument("name", "") address = self.get_argument("address", "") town = self.get_argument("town", "") city = self.get_argument("city", "") zip_code = self.get_argument("zip_code", "") telephone = self.get_argument("telephone", "") contacto = Contact() res_contact = contacto.InitById(id) if "success" in res_contact: datos = res_contact["success"] contacto.initialize(datos) contacto.name = name contacto.address = address contacto.town = town contacto.city = city contacto.zip_code = zip_code contacto.telephone = telephone ciudad = City() res_city = ciudad.getNameById(city) if "success" in res_city: contacto.Edit() self.write(json_util.dumps(res_city))
def create_counties(self): for row in self.open_csv(): if row[1]: if not row[2]: if row[1] > 60: City.create(row[4], row[1], row[0]) else: County.create(row[4], row[1], row[0])
def delete_today(cls): now = datetime.now() current_time = math.floor(now.timestamp()) now = now + timedelta(days=-1) start_time = math.floor( now.replace(hour=23, minute=59, second=59, microsecond=0).timestamp()) City.select().filter(City.created_at.between( start_time, current_time)).delete(synchronize_session=False)
def create_city_collection(city_dict): cities = set() for city in city_dict: geo_code = fetch_geocode(city['name']) new_city = City(city['name'], geo_code) cities.add(new_city) return cities
def getCitySummary(): """Return a summary of information regarding a city (avg price per sq meter, admin infor of the city) Raises: Exception: "Error occured" Returns: Dict: key-value pairs of information """ # Get raw data from DVF API data = getCityExtract(request.args) # Compute summary data if isinstance(data, Dict): city = City(data) result = { "current_avg_price_sq_meter_house": city.current_avg_price_sq_meter_house, "current_avg_price_sq_meter_apartment": city.current_avg_price_sq_meter_apartment, "city_name": city.name, "city_postalCode": city.postalCode, "city_inseeCode": city.inseeCode, "city_latitude": city.gps_latitude, "city_longitude": city.gps_longitude } return make_response(jsonify(result), 200) else: return make_response(data, 404) # No result Found
def get(self): contactos = [] cities = [] if self.current_user: user_id = self.current_user["id"] contact = Contact() response_contacto = contact.ListByUserId(user_id) if "success" in response_contacto: contactos = json_util.loads(response_contacto["success"]) city = City() response_city = city.List() if "success" in response_city: cities = response_city["success"] self.render("profile/index.html", contactos=contactos, ciudades=cities)
def load_city_collection(): cities = set() try: file_object = open('resources/largeCitiesWithGeoLocation.json', 'r', encoding="utf8") cities_from_json = json.load(file_object) for city_from_json in cities_from_json: city = City(city_from_json['name'], city_from_json['location']) cities.add(city) except FileNotFoundError: print(file_object + " not found. ") return cities
def convert_raw_data(cls, reg_dict): try: home_city = City.get(name=reg_dict['home']) home_id = home_city.id except City.DoesNotExist: home_id = None try: school = School.get(name=reg_dict['school']) school_id = school.id except School.DoesNotExist: school_id = None applicant = cls(name=reg_dict['name'], home=home_id, email=reg_dict['email'], school=school_id) return applicant
def china_detail(cls, date): if date is None: date = datetime.now().strftime('%Y%m%d') provinces = Province.select().filter(Province.date == date).all() cities = City.select().filter(City.date == date).all() city_map = {} for city in cities: cs = city_map.get(city.province_name, []) if len(cs) == 0: city_map[city.province_name] = [] city_map[city.province_name].append(city.get_json()) result = [] for province in provinces: res = province.get_json() res['cities'] = city_map.get(province.province_name) result.append(res) return result
def register_address_by_names(self, street_name, neighbourhood, city_name, state_name, country_name): try: country = Country(name=country_name) db.session.add(country) db.session.commit() except exc.IntegrityError: db.session.rollback() country = Country.query.filter_by(name=country_name).first() try: state = State(name=state_name, country_id=country.id) db.session.add(state) db.session.commit() except exc.IntegrityError: db.session.rollback() state = State.query.filter( and_(State.name == state_name, State.country_id == country.id)).first() try: city = City(name=city_name, state_id=state.id) db.session.add(city) db.session.flush() except exc.IntegrityError: db.session.rollback() city = City.query.filter( and_(City.name == city_name, City.state_id == state.id)).first() try: address = Address(street_name=street_name, neighbourhood=neighbourhood, city_id=city.id) db.session.add(address) db.session.commit() return address.id except exc.IntegrityError: db.session.rollback() return None
def __init__(self, data): self.outcome = data['outcome'] self.round = data['round'] self.points = data['points'] self.cities = [] for city, value in data['cities'].items(): self.cities.append(City(value)) self.events = [] try: for event in data['events']: self.events.append(process_event(event)) except KeyError: pass try: self.error = data['error'] except KeyError: pass
def build_address(condominium_obj): try: country = Country(name=condominium_obj['CountryName']) db.session.add(country) db.session.flush() except exc.IntegrityError: db.session.rollback() country = Country.query.filter_by( name=condominium_obj['CountryName']).first() try: state = State(name=condominium_obj['StateName'], country_id=country.id) db.session.add(state) db.session.flush() except exc.IntegrityError: db.session.rollback() state = State.query.filter( and_(State.name == condominium_obj['StateName'], State.country_id == country.id)).first() try: city = City(name=condominium_obj['CityName'], state_id=state.id) db.session.add(city) db.session.flush() except exc.IntegrityError: db.session.rollback() city = City.query.filter( and_(City.name == condominium_obj['CityName'], City.state_id == state.id)).first() address = Address(street_name=condominium_obj['StreetName'], neighbourhood=condominium_obj['Neighbourhood'], city_id=city.id) db.session.add(address) db.session.flush() return address.id
def china_summary(cls, date): if date is None: date = datetime.now().strftime('%Y%m%d') provinces = Province.select() \ .filter(Province.country == '中国', Province.date == date) \ .order_by(Province.confirmed.asc()) \ .all() province_names = [province.province_name for province in provinces] cities = City.select() \ .filter(City.province_name.in_(province_names), City.date == date) \ .order_by(City.confirmed.asc()) \ .all() china_summary = ChinaSummary(cured=0, confirmed=0, dead=0, suspected=0, cities={}, province_level={}, provinces={}) city_map = {} for city in cities: if city.province_name in city_map.keys(): city_map[city.province_name].append(city.get_json()) else: city_map[city.province_name] = [city.get_json()] for province in provinces: china_summary.provinces[province.short_name] = { 'cured': province.cured, 'confirmed': province.confirmed, 'dead': province.dead, 'suspected': province.suspected } china_summary.cured += province.cured china_summary.confirmed += province.confirmed china_summary.dead += province.dead china_summary.suspected += province.suspected china_summary.province_level[ province.short_name] = cls.summary_section(province.confirmed) china_summary.cities = city_map return china_summary
def bulk_insert(cls, cities: [City]): City.bulk_insert(cities)
def create_cities(cls): for c in cls.city_list: city = City.create(name=c)
def query_by_time(cls, start: int, end: int): return City.select().filter(City.created_at.between(start, end)).all()
def _create_obj_from_input(input_items: [dict]): return City([ item['value'] for item in input_items if item['name'] == 'Name of city' ][0])
def sync(cls): now = datetime.now().strftime('%Y-%m-%d_%H') log.info(f'begin sync {now}') file_name = f"./data/{now}.json" if not os.path.exists(file_name): CrawlerService.crawler() raw_data = json.load(open(file_name, 'r')) data = raw_data['nCoV2019'] date = datetime.now().strftime('%Y%m%d') world = World(date=date, name='中国', confirmed=data['totalConNum'], suspected=data['totalSusNum'], cured=data['totalCureNum'], dead=data['totalDeathNum'], add_confirmed=data['addCon'], add_cured=data['addCure'], add_dead=data['addDeath'], add_suspected=data['addSus']) history_list = data['historyList'] histories = [] for history in history_list: histories.append( History(date=history['date'], confirmed=history['conNum'], cured=history['cureNum'], dead=history['deathNum'], suspected=history['susNum'])) overseas_list = data['overseasList'] worlds = [] for overseas in overseas_list: worlds.append( World(date=date, confirmed=overseas['conNum'], cured=overseas['cureNum'], suspected=overseas['susNum'], dead=overseas['deathNum'], name=overseas['name'])) domestic_list = data['domesticList'] provinces = [] cities = [] for domestic in domestic_list: provinces.append( Province(date=date, province_name=domestic['name'], short_name=domestic['name'], confirmed=domestic['conNum'], dead=domestic['deathNum'], suspected=domestic['susNum'], cured=domestic['cureNum'])) city_list = domestic['cities'] for city in city_list: cities.append( City(date=date, province_name=domestic['name'], city_name=city['name'], confirmed=city['conNum'], suspected=city['susNum'], cured=city['cureNum'], dead=city['deathNum'])) History.select().delete() History.bulk_insert(histories) World.select().filter(World.date == date).delete() world.insert() World.bulk_insert(worlds) Province.select().filter(Province.date == date).delete() Province.bulk_insert(provinces) City.select().filter(City.date == date).delete() City.bulk_insert(cities) log.info(f'sync {now} done')
def add_city(self, country_name, city_name): country = self.get_by_name(country_name)[0] cities = country['cities'] cities.append(City(city_name)) self.db.update({'cities': self.__serialize(cities)}, self.query.name == country_name)
def get(self): if self.current_user: user_id = self.current_user["id"] contact = Contact() response_obj = contact.ListByUserId(user_id) contactos = [] cities = [] if "success" in response_obj: contactos = json_util.loads(response_obj["success"]) # else: # self.render("beauty_error.html",message="Error al obtener la lista de contactos:{}".format(response_obj["error"])) # return # use globals default to avoid exception web_cellar_id = cellar_id c = Cellar() res_cellar_id = c.GetWebCellar() if "success" in res_cellar_id: web_cellar_id = res_cellar_id["success"] cart = Cart() cart.user_id = user_id lista = cart.GetCartByUserId() suma = 0 for l in lista: suma += l["subtotal"] res_web_cellar = c.InitById(web_cellar_id) if "success" in res_web_cellar: cellar_city_id = c.city_id city = City() city.from_city_id = cellar_city_id res_city = city.ListByFromCityId() # print res_city post_office_list = [] po = PostOffice() res_po = po.ListOnlyWithShippingCost() if "success" in res_po: post_office_list = res_po["success"] if suma > 0: if "success" in res_city: cities = res_city["success"] self.render("store/checkout-1.html", contactos=contactos, data=lista, suma=suma, cities=cities, post_office_list=post_office_list) else: self.render("beauty_error.html", message="Carro está vacío") else: self.redirect("/auth/login")
def get(self): if self.current_user: user_id = self.current_user["id"] nombre = self.get_argument("name", self.current_user["name"]) apellido = self.get_argument("lastname", self.current_user["lastname"]) email = self.get_argument("email", self.current_user["email"]) direccion = self.get_argument("address", "") ciudad = self.get_argument("city_id", "") codigo_postal = self.get_argument("zip_code", "") informacion_adicional = self.get_argument("additional_info", "") telefono = self.get_argument("telephone", "") id_contacto = self.get_argument("contact_id", "") comuna = self.get_argument("town", "") rut = self.get_argument("rut", "") shipping_type = self.get_argument("shipping_type", "") post_office_id = self.get_argument("post_office_id", "") shipping_type_id = 1 cart = Cart() cart.user_id = user_id lista = cart.GetCartByUserId() if len(lista) <= 0: self.render("beauty_error.html", message="Carro está vacío") contact = Contact() contact.name = nombre contact.lastname = apellido contact.telephone = telefono contact.email = email contact.address = direccion if shipping_type == "chilexpress": po = PostOffice() po.InitById(post_office_id) post_office_name = po.name contact.address = "Oficina {}".format(post_office_name) contact.city = ciudad contact.zip_code = codigo_postal contact.user_id = user_id contact.additional_info = informacion_adicional contact.town = comuna contact.rut = rut operacion = "" if id_contacto != "": contact.id = id_contacto response_obj = contact.Edit() operacion = "editar" else: response_obj = contact.Save() operacion = "guardar" if "error" in response_obj: self.render("beauty_error.html", message="Error al {} contacto {}".format( operacion, response_obj["error"])) else: items = 0 suma = 0 for l in lista: c = Cart() response_obj = c.InitById(l["id"]) if "success" in response_obj: c.shipping_id = contact.id c.shipping_info = contact.additional_info c.Edit() else: print response_obj["error"] suma += l["subtotal"] items += l["quantity"] contactos = [] cities = [] response_obj = contact.ListByUserId(user_id) city = City() res_city = city.List() if "success" in response_obj: contactos = json_util.loads(response_obj["success"]) if "success" in res_city: cities = res_city["success"] c = Cellar() res_cellar_id = c.GetWebCellar() web_cellar_id = cellar_id if "success" in res_cellar_id: web_cellar_id = res_cellar_id["success"] res_web_cellar = c.InitById(web_cellar_id) if "success" in res_web_cellar: if shipping_type != "chilexpress": cellar_city_id = c.city_id shipping = Shipping() shipping.from_city_id = int(cellar_city_id) shipping.to_city_id = int(ciudad) res = shipping.GetGianiPrice() if "error" in res: self.render( "beauty_error.html", message="Error al calcular costo de despacho, {}" .format(res["error"])) else: shipping_type_id = 2 shipping = Shipping() shipping.post_office_id = post_office_id res = shipping.GetPriceByPostOfficeId() if "error" in res: self.render( "beauty_error.html", message= "Error al calcular costo de despacho de Chilexpress, {}" .format(res["error"])) else: if shipping.charge_type == 1: costo_despacho = shipping.price * items else: costo_despacho = shipping.price self.render("store/checkout-2.html", contactos=contactos, data=lista, suma=suma, selected_address=direccion, cities=cities, costo_despacho=costo_despacho, shipping_type=shipping_type_id, post_office_id=post_office_id) else: self.redirect("/auth/login")
def post(self): nombre = self.get_argument("name", "") giro = self.get_argument("bussiness", "") rut = self.get_argument("rut", "") email = self.get_argument("email", "") direccion = self.get_argument("address", "") region = self.get_argument("state", "") provincia = self.get_argument("city", "") comuna = self.get_argument("town", "") clave = self.get_argument("password", "") rep_clave = self.get_argument("re-password", "") rut = re.sub(r'\.+|-+', "", rut).lower() if nombre.strip() == "": self.write( json_util.dumps({ "state": 0, "message": "Debe ingresar nombre" })) return elif giro.strip() == "": self.write( json_util.dumps({ "state": 0, "message": "Debe ingresar giro" })) return elif rut.strip() == "": self.write( json_util.dumps({ "state": 0, "message": "Debe ingresar rut" })) return elif not valida(rut): self.write( json_util.dumps({ "state": 0, "message": "Rut ingresado no es válido" })) return elif email.strip() == "": self.write( json_util.dumps({ "state": 0, "message": "Debe ingresar email" })) return elif not isEmailValid(email): self.write( json_util.dumps({ "state": 0, "message": "Email ingresado no es válido" })) return elif direccion.strip( ) == "" or region == "" or provincia == "" or comuna == "": self.write( json_util.dumps({ "state": 0, "message": "Debe ingresar su dirección completa" })) return elif clave.strip() == "": self.write( json_util.dumps({ "state": 0, "message": "Debe ingresar clave" })) return elif rep_clave.strip() != clave.strip(): self.write( json_util.dumps({ "state": 0, "message": "Las claves ingresadas no coinciden" })) return user = User() user.name = nombre user.password = clave user.email = email user.user_type = UserType.EMPRESA user.bussiness = giro user.rut = rut user.status = User.PENDIENTE res_save = user.Save() user_id = None if "error" in res_save: # self.write(json_util.dumps(res_save)) # return self.write( json_util.dumps({ "state": 0, "message": "error de registro {}".format(res_save["error"]) })) return else: user_id = res_save["success"] city_id = None city = City() res_city = city.getIdByName(comuna) if "success" in res_city: city_id = res_city["success"] contact = Contact() contact.town = "{}, {}".format(comuna.encode("utf-8"), region.encode("utf-8")) contact.address = direccion contact.user_id = user_id contact.city = city_id try: html = self.generateMail("registro_mayorista.html", name=nombre.encode('utf-8'), bussiness=giro.encode('utf-8'), email=email.encode('utf-8'), address=direccion.encode('utf-8'), state=region.encode('utf-8'), city=provincia.encode('utf-8'), town=comuna.encode('utf-8'), rut=rut, url_local=url_local) sg = sendgrid.SendGridClient(sendgrid_user, sendgrid_pass) mensaje = sendgrid.Mail() mensaje.set_from("{nombre} <{mail}>".format(nombre=nombre, mail=email)) mensaje.add_to(to_giani) mensaje.set_subject("Registro Mayorista GDF") mensaje.set_html(html) status, msg = sg.send(mensaje) # print status except Exception, e: print str(e) try: html = self.generateMail("registro_mayorista_cliente.html", name=nombre.encode('utf-8')) sg = sendgrid.SendGridClient(sendgrid_user, sendgrid_pass) mensaje = sendgrid.Mail() mensaje.set_from("{nombre} <{mail}>".format( nombre='Giani Da Firenze', mail=email_giani)) mensaje.add_to(email) mensaje.set_subject("Registro Mayorista GDF") mensaje.set_html(html) status, msg = sg.send(mensaje) # print msg except Exception, e: print str(e)