def create_station(self, fm_band):
        if not self.name or self.name.isspace():
            return jsonify({
                "message":"name is required"
            }),400

        if type(self.name) != str:
            return jsonify({
                "message": "name should be a string"
            }),400
        if not self.address or self.address.isspace():
            return jsonify({
                "message":"address is required"
            }),400

        if type(self.address) != str:
            return jsonify({
                "message": "address should be a string"
            }),400
        
        station_model = Station(self.name,self.address)
        station = station_model.create_station(fm_band)


        return jsonify({
            "message":"station created successfully",
            "station" :station
        }), 201
Exemple #2
0
 def get(self):
     letMeCheck = []
     print(request.args['country_code'])
     hasHourTemp = Station.getOperational()
     allStations = Station.getStationsFromMet(request.args['country_code'])
     for st in allStations['data']:
         if st['id'] in hasHourTemp:
             st['hasHourTemp'] = True
         else:
             st['hasHourTemp'] = False
         letMeCheck.append(st)
     Station.saveManyStaions(letMeCheck)
     return letMeCheck
    def get_stations():
        model  = Station("","")

        stations = model.get_stations()

        if len(stations) == 0:
            return jsonify({
                "message":"sorry! no statiosn were found"
            })

        return jsonify({
            "message":"successful",
            "stations":stations
        })
Exemple #4
0
 def __init__(self, data):
     self.data = data
     if (len(self.deservedStations) > 0
             and 'stations' not in self.deservedStations[0]):
         for i in range(len(self.deservedStations)):
             self.deservedStations[i]['station'] = Station.find_station(
                 self.deservedStations[i]['label'])
Exemple #5
0
    def _parse(self):
        self.ovo = self.param('ovo')

        for tds in self.tr_tds(1, from_index=1):
            id = int(tds[0].text())

            if not Station.get(id=id):
                StationDirty(
                    id=id,
                    address=StationParser.clear_html(tds[1].html()),
                    bound=tds[2].text(),
                )

                Station(id=id, ovo_id=self.ovo.id)

        self.ovo.processed = True
Exemple #6
0
 def get(self):
     myElements = ['air_temperature']
     mySources = list2Strings(Station.getAllStationsAsString(Station), 20)
     #mySources = ['SN50500']
     fewdaysago = datetime.date.today() - datetime.timedelta(1)
     fromDate = datetime.date.today()
     if 'days' in request.args:
         fewdaysago = datetime.date.today() - datetime.timedelta(
             int(request.args['days']))
     if 'daysAgo' in request.args:
         fromDate = datetime.date.today() - datetime.timedelta(
             int(request.args['daysAgo']))
         if 'days' in request.args:
             fewdaysago = datetime.date.today() - datetime.timedelta(
                 int(request.args['days']) + int(request.args['daysAgo']))
     getDataFrom = fewdaysago.strftime("%Y-%m-%d")
     getDataTo = fromDate.strftime("%Y-%m-%d")
     dateString = getDataFrom + '/' + getDataTo
     allOfIt = []
     for stations in mySources:
         r = MetWrapper.getObservations(stations, myElements, dateString)
         if r.status_code == 200:
             allOfIt.append(r.json())
     Measurement.saveMany(allOfIt)
     return allOfIt
def test_get_stations_from_response():
    json = {
        "payload": [
            {
                "code": "BVB",
                "namen": {
                    "lang": "Aachen Hbf",
                }
            }
        ]
    }
    

    response = mock.Mock()
    response.status_code = 200
    response.json = mock.Mock(return_value=json)

    expected_result = [
        Station(
            name="Aachen Hbf",
            code="BVB"
        )
    ]
    result = get_stations_from_response(response)

    assert result == expected_result
Exemple #8
0
    def getDataFrom(station):
        stuff = []

        station = station  #+ ':0'
        station_id = Station.findById('Station', station).id
        prepare = Measurement.query.filter_by(station_id=station_id).order_by(
            Measurement.mtime.asc())
        for item in prepare:
            stuff.append({
                'station':
                Station.findById('Station', station).code,
                'value':
                item.value,
                'time':
                datetime.strftime(item.mtime, '%Y-%m-%d %H:%M')
            })
        return stuff
 def add_stations(self, min_capacity, max_capacity, number):
     for i in range(number):
         self.stations.append(
             Station(
                 capacity=random.randint(min_capacity, max_capacity),
                 radius=0.85,
                 faker=self.faker,
             ))
Exemple #10
0
    def _build_line_data(self, station_df):
        """Constructs all stations on the line"""
        stations = station_df["station_name"].unique()

        station_data = station_df[station_df["station_name"] == stations[0]]
        line = [
            Station(station_data["station_id"].unique()[0], stations[0],
                    self.color)
        ]
        prev_station = line[0]
        for station in stations[1:]:
            station_data = station_df[station_df["station_name"] == station]
            new_station = Station(station_data["station_id"].unique()[0],
                                  station, self.color, prev_station)
            prev_station.dir_b = new_station
            prev_station = new_station
            line.append(new_station)
        return line
Exemple #11
0
def create_new_station(contacted, stationname, located):

    station = Station()
    station.contact = contacted
    station.name = stationname
    station.location = located
    station.save()
    return jsonify({
        "message": "Successfully make a new item."
        }), 200
Exemple #12
0
 def saveMany(data):
     for chunk in data:
         for item in chunk['data']:
             for obs in item['observations']:
                 converted = datetime.strptime(item['referenceTime'],
                                               '%Y-%m-%dT%H:%M:%S.000Z')
                 myId = Station.getStationIdWithCode(
                     item['sourceId'][0:-2]).id
                 mes = Measurement(myId, converted, obs['elementId'],
                                   obs['value'])
                 db.session.add(mes)
     db.session.commit()
    def get_station(name):

        if not name or name.isspace():
            return jsonify({
                "message":"name is required"
            }),400

        if type(name) != str:
            return jsonify({
                "message": "name should be a string"
            }),400

        station_model = Station("","")
        my_station = station_model.get_station(name)
        if my_station is None:
            return jsonify({
                "message":"station was not found"
            }),200
        
        return jsonify({
            "message":"successful",
            "station":my_station
        }), 200
Exemple #14
0
def show():
    station_object = []
    station = Station.select()
    for i in station:
        station_object.append(
            {
                'id': i.id,
                'name': i.name
            }
        )
    return jsonify({
            "message": "Successfully update a new item.",
            "station_object": station_object
        }), 200
def test_get_station_from_json():
    json = {
        "code": "BVB",
        "namen": {
            "lang": "Aachen Hbf",
        }
    }

    expected_result = Station(
        name="Aachen Hbf",
        code="BVB"
    )

    result = get_station_from_json(json)

    assert result == expected_result
Exemple #16
0
    def getAllDataFromWhere(fromTime, toTime, defType='air_temperature'):
        fixThis = []
        returnThis = Measurement.query.filter(
            Measurement.mtime >= fromTime).filter(
                Measurement.mtime <= toTime).filter(
                    Measurement.mType == defType).all()
        for mes in returnThis:
            #fixThis.append({'station': mes.station , 'value' : mes.value, 'time': datetime.strftime(mes.mtime, '%Y-%m-%dT%H:%M:%S.000Z')})
            fixThis.append({
                'station':
                Station.findById('Station', mes.station_id).code,
                'value':
                mes.value,
                'time':
                datetime.strftime(mes.mtime, '%Y-%m-%d %H:%M:%S.000Z')
            })

        return fixThis
Exemple #17
0
def get_all_stations():
    try:
        with open('stations.txt', 'r') as f:
            stations = pickle.load(f)
            return stations
    except IOError:
        pass
    raw_data = get(
        'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js')
    match = re.search('\'(.*)\'', raw_data)
    content = match.group(1)
    raw_stations = content.split('@')
    stations = []
    for station in raw_stations:
        if not station:
            continue
        sta_attrs = station.split('|')
        station_obj = Station(sta_attrs[1], sta_attrs[2], sta_attrs[3])
        stations.append(station_obj)

    with open('stations.txt', 'wb') as f:
        pickle.dump(stations, f)
    return stations
Exemple #18
0
 def get(self):
     return Station.getStationOptions(request.args['id'])
    def parseV2(js, city):

        for record in js['records']:
            properties = record['fields']
            station = Station()

            station.setName(properties.get('nom'))
            st_id = properties.get('idstation')
            station.setId(int(st_id) if st_id else st_id)
            coords = properties.get('coordonnees')
            if coords:
                station.setLattitude(float(coords[0]))
                station.setLongitude(float(coords[1]))
            total = properties.get('nombreemplacementsactuels')
            station.setTotal(int(total) if total else total)
            avail = properties.get('nombrevelosdisponibles')
            station.setAvailable(int(avail) if avail else avail)
            free = properties.get('nombreemplacementsdisponibles')
            station.setFree(int(free) if free else free)

            city.addStation(station)
 def get_station_data(self):
     return [
         Station(station['name'], station['id'], station['coordinates'],
                 station['capacity']) for station in self.stations
     ]
Exemple #21
0
def _load_bounds():
    stations = Station.select(lambda c: c.processed == False)[0:100]
    for station in stations:
        BoundParser(None, station=station).parse()
        commit()
    return len(stations)
    def parseV1(js, city):

        for feature in js['features']:
            properties = feature['properties']
            station = Station()
            station.setName(properties.get('name'))
            st_id = properties.get('number')
            station.setId(int(st_id) if st_id else st_id)
            lat = properties.get('lat')
            station.setLattitude(float(lat) if lat else lat)
            lon = properties.get('lng')
            station.setLongitude(float(lon) if lon else lon)
            total = properties.get('bike_stands')
            station.setTotal(int(total) if total else total)
            avail = properties.get('available_bikes')
            station.setAvailable(int(avail) if avail else avail)
            free = properties.get('available_bike_stands')
            station.setFree(int(free) if free else free)
            card = properties.get('banking')
            station.setCardPaiement(card == "true" if card else card)

            city.addStation(station)
Exemple #23
0
def _load_addresses():
    stations = Station.select(lambda c: c.processed_address == False)[0:100]
    for station in stations:
        AddressParser(None, station=station).parse()
    return len(stations)
    def parseV3(js, city):

        for record in js['records']:
            properties = record['fields']
            station = Station()

            station.setName(properties.get('name'))
            station.setId(properties.get('recordid'))
            coords = properties.get('geo_point_2d')
            if coords:
                station.setLattitude(float(coords[1]))
                station.setLongitude(float(coords[0]))
            total = properties.get('capacity')
            station.setTotal(int(total) if total else total)

            city.addStation(station)
Exemple #25
0
 def get(self):
     return Station.getAllStations(Station)
Exemple #26
0
#!/usr/bin/env python3
import folium
import folium.plugins
import os
from models.station import Station, Stop
from models.line import Line

m = folium.Map(location=[52, 13],
               tiles='stamentoner',
               max_zoom=18,
               zoom_start=4)
marker_cluster = folium.plugins.MarkerCluster().add_to(m)

stations = Station.get_stations()
lines = Line.get_lines()

for station in stations:
    folium.Marker(station.location, popup=station.name).add_to(marker_cluster)

#is_ubahn = False
#colors = ['red', 'green', 'yellow', 'black', 'pink', 'brown', 'red', 'green', 'yellow', 'black', 'pink', 'brown', 'red', 'green', 'yellow', 'black', 'pink', 'brown', 'red', 'green', 'yellow', 'black', 'pink', 'brown']
#for line in lines:
#    # if not line.mode == 'train':
#    if line.name != 'U8':
#        continue
#    color = 'green'
#    if line.product == 'subway':
#        color = 'blue'
#    multipolyline = []
#    i = 0
#    for variant in line.variants:
    def parseDecaux(js, city):

        for record in js['records']:
            properties = record['fields']
            station = Station()

            station.setName(properties.get('name'))
            st_id = properties.get('number')
            station.setId(int(st_id) if st_id else st_id)

            coords = properties.get('position')
            if coords:
                station.setLattitude(float(coords[0]))
                station.setLongitude(float(coords[1]))

            total = properties.get('bike_stands')
            station.setTotal(int(total) if total else total)
            avail = properties.get('available_bikes')
            station.setAvailable(int(avail) if avail else avail)
            free = properties.get('available_bike_stands')
            station.setFree(int(free) if free else free)
            card = properties.get('banking')
            station.setCardPaiement(card != "False" if card else card)

            city.addStation(station)
    def parseV4(js, city):
        for feature in js['features']:
            properties = feature['properties']
            station = Station()

            voie = properties.get('NOM_VOIE')
            voie = "" if not voie else voie
            compl = properties.get("COMPL_LOC")
            compl = "" if not compl else compl
            name = voie + " " + compl
            station.setName(name if name != " " else None)

            st_id = feature.get('id')
            station.setId(int(st_id) if st_id else st_id)

            coords = feature.get('geometry')
            if coords and coords.get('coordinates'):
                coords = coords.get('coordinates')
                station.setLattitude(float(coords[1]))
                station.setLongitude(float(coords[0]))
            total = properties.get('NBR_PT_ACC')
            station.setTotal(int(total) if total else total)
            avail = properties.get('NBR_VELO')
            station.setAvailable(int(avail) if avail else avail)
            if total and avail:
                free = int(total) - int(avail)
                station.setFree(free)

            city.addStation(station)
    def parse(content, city):
        root = ET.fromstring(content)
        elements = root[0]

        for element in elements:
            station = Station()
            properties = element.attrib

            station.setName(properties.get('na'))
            st_id = properties.get('id')
            station.setId(int(st_id) if st_id else st_id)
            lat = properties.get('la')
            station.setLattitude(float(lat) if lat else lat)
            lon = properties.get('lg')
            station.setLongitude(float(lon) if lon else lon)
            total = properties.get('to')
            station.setTotal(int(total) if total else total)
            avail = properties.get('av')
            station.setAvailable(int(avail) if avail else avail)
            free = properties.get('fr')
            station.setFree(int(free) if free else free)

            city.addStation(station)
    def parseV5(js, city):
        stations = js['data']['stations']
        for properties in stations:
            station = Station()
            station.setName(properties.get('name'))
            st_id = properties.get('station_id')
            station.setId(int(st_id) if st_id else st_id)
            lat = properties.get('lat')
            station.setLattitude(float(lat) if lat else lat)
            lon = properties.get('lon')
            station.setLongitude(float(lon) if lon else lon)
            total = properties.get('capacity')
            station.setTotal(int(total) if total else total)

            city.addStation(station)