Ejemplo n.º 1
0
 def setUp(self):
     self.app = create_app('testing')
     self.app_context = self.app.app_context()
     self.app_context.push()
     db.create_all()
     Airport.insert_test_airports()
     Destination.insert_test_destinations()
Ejemplo n.º 2
0
def populate_airports(limit=None, reload=False):
    """
    Populate :model:`app.Airport`s from the datasource into the database.
    """
    Airport.objects.all().delete()
    cols = [field.name for field in Airport._meta.fields]
    airports_data = get_airports(cols, reload)[:limit]
    aiports_instances = [Airport(**airport) for airport in airports_data]
    try:
        return Airport.objects.bulk_create(aiports_instances)
    except Exception as err:
        raise err
Ejemplo n.º 3
0
def addAirport():
    form = AirportForm()
    if form.validate_on_submit():
        data = form.data
        airport = Airport.query.filter_by(name=data["name"]).count()
        if airport == 1:
            flash("The airport name already exists!")
            return redirect(url_for("staff.addAirport"))
        airport = Airport(name=data["name"], city=data["city"])
        db.session.add(airport)
        db.session.commit()
        flash("Add success!")
        return redirect(url_for("staff.addAirport"))
    return render_template("staff/addAirport.html", form=form)
Ejemplo n.º 4
0
def addairport():
    form = AddAirport()
    if request.method == 'POST' and form.validate():
        newAirport = Airport(iata_code=form.new_iata_code.data,
                             icao_code=form.new_icao_code.data,
                             name=form.new_name.data,
                             city=form.new_city.data,
                             country=form.new_country.data,
                             size=form.new_size.data)
        # print (newAirport)
        db.session.add(newAirport)
        db.session.commit()
        return redirect(url_for('diagnostics.selection'))
    return render_template("diagnostics/addairport.html",
                           title='Add Airport',
                           form=form)
Ejemplo n.º 5
0
    def upload_data_from_csv(file):
        """ Receives data to upload to airport table """
        
        try:
            file_data = serialize_file_data(file)
            # Add airports registry
            for single_airport in file_data:
                airport = Airport(**single_airport)
                db.session.add(airport)
            
            db.session.commit()
            resp = message(True, "Airports data uploaded with success")

            return resp, 200

        except Exception as error:
                    current_app.logger.error(error)
                    return internal_err_resp()
Ejemplo n.º 6
0
    def create_airport(data):
        """ Create a new airport registry """

        from .utils import load_data

        try:
            airport = Airport(**data)
            db.session.add(airport)
            db.session.commit()

            resp = message(True, f"New airport saved.")
            resp["data"] = load_data(airport);
            
            return resp, 200

        except Exception as error:
            current_app.logger.error(error)
            return internal_err_resp()
Ejemplo n.º 7
0
def import_airports(file_name: str) -> None:
    if file_name[0] != "/":
        file_name = current_dir + "/" + file_name

    with open(file_name, "r") as csvfile:
        csvreader = csv.DictReader(csvfile)
        for idx, row in enumerate(csvreader):
            # Create Airline.
            airport = Airport(
                airport_name=row["Name"],
                city=row["City"],
                country=row["Country"],
                iata_faa=row["IATA/FAA"],
                icao=row["ICAO"],
                latitude=row["Latitude"],
                longitude=row["Longitude"],
                timezone=row["Timezone"],
                dst=row["DST"],
                tz_database_time_zone=row["Tz database time zone"],
            ).save(idx % chunk_size == 0)

            print(idx, airport.airport_name)

        db.session.commit()  # save last chunk
Ejemplo n.º 8
0
def airports():
    """Find closest airports."""
    lat = float(request.args.get("lat"))
    lng = float(request.args.get("lng"))
    limit = int(request.args.get("limit")) or 1
    find_closest_city = request.args.get("find_closest_city") == "true"

    redis_key = "|".join(
        ["airports",
         str(lat),
         str(lng),
         str(limit),
         str(find_closest_city)])

    try:
        result = redis_store.get(redis_key)
        redis_is_connected = True
        if result:
            return jsonify(pickle.loads(result))
    except RedisConnectionError:
        redis_is_connected = False

    result = {"airports": Airport.get_closest_airports(lat, lng, limit)}

    if find_closest_city:
        # Try to find with Elasticsearch.
        try:
            cities = es.search(
                index="airtickets-city-index",
                from_=0,
                size=1,
                doc_type="CityName",
                body={
                    "query": {
                        "bool": {
                            "must": {
                                "geo_distance": {
                                    "distance": "500km",
                                    "location": {
                                        "lat": lat,
                                        "lon": lng
                                    },
                                }
                            }
                        }
                    },
                    "sort": {
                        "_geo_distance": {
                            "location": {
                                "lat": lat,
                                "lon": lng
                            },
                            "order": "asc",
                            "unit": "km",
                        }
                    },
                    "size": 1,
                },
            )
            result["closest_city"] = cities["hits"]["hits"][0]["_source"]
        except (ElasticConnectionError, NotFoundError, AttributeError):
            result["closest_city"] = next(
                iter(City.get_closest_cities(lat, lng, 1) or []), None)

    if redis_is_connected:
        redis_store.set(redis_key, pickle.dumps(result), 86400)

    return jsonify(result)
from app.models import Airport, Destination, Weather

app = create_app('development')
app_context = app.app_context()
app_context.push()

db.create_all()

with open('data/airports.csv', encoding='utf-8') as file:
    for line in file:
        # "iata_code","lat","long"
        # "MAD",40.47193,-3.56264
        line = line.replace('"', '')
        fields = line.split(',')
        a = Airport(
            iata_code=fields[0],
            lat=float(fields[1]),
            long=float(fields[2]))
        db.session.add(a)

db.session.commit()

with open('data/destinations.csv', encoding='utf-8') as file:
    for line in file:
        # "city","country","iata_code","lat","long"
        # "Madrid","Spain","MAD",40.47193,-3.56264
        line = line.replace('"', '')
        fields = line.split(',')
        d = Destination(
            city=fields[0],
            country=fields[1],
            iata_code=fields[2],