Esempio n. 1
0
def adddata(option, form):
    add_item = None
    if option == 'media':
        # Use the NewComponent object to add this
        #        fileobj = FileLoad('PASS', session)
        formdata = []
        loc = LocationObject(session, Locations)
        locdata = loc.getdatabyid(form.location.data)
        for field in form:
            if field.label.text == 'Location':
                #               fileobj.titles.append('Sublocation')
                formdata.append(locdata.Sublocation)
                #               fileobj.titles.append(field.label.text)
                formdata.append(locdata.Name)
            else:
                #                fileobj.titles.append(field.label.text)
                formdata.append(field.data)


#        component = NewComponent(fileobj, formdata)
#        status = component.parsedata()
#        print status

    elif option == 'location':
        staticid = getnewstaticid(Locations)
        add_item = Locations(locationid=staticid,
                             name=form.title.data,
                             description=form.description.data,
                             sublocation=form.sublocation.data)
    else:
        querytable = Locations
    if add_item is not None:
        session.add(add_item)
        session.commit()
        flash('Added {} {}'.format(option, form.title.data))
Esempio n. 2
0
    def get(self):
        self.response.content_type = 'text/json'  #return text of json when accessed
        lat = float(self.request.get('lat'))  #'lat' and 'lng' are query
        lng = float(self.request.get('lng'))
        print(lat)
        print(lng)
        new_locations = Locations.query().fetch()
        new_location_list = []

        #dictionary is converted to json

        for location in new_locations:
            print(location.lat)
            print(location.lng)
            if location.lat <= lat + 0.05 and location.lat >= lat - 0.05 and location.lng <= lng + 0.05 and location.lng >= lng - 0.05:
                new_location_list.append({
                    'host_name': location.host_name,
                    'address': location.address,
                    'comment': location.comment,
                    'lat': location.lat,
                    'lng': location.lng
                })
        self.response.write(
            json.dumps(new_location_list)
        )  #converts to json and shows pure json file /map can cation locations as a list
Esempio n. 3
0
    def post(self):  #upload as a datastore entries
        host_name = self.request.get('host_name')
        address = self.request.get('address')
        comment = self.request.get('comment')
        created_at = datetime.datetime.now()
        encode_query = {"address": address}
        geocode_url = "https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyCdoUTgBiki0q2SOugXKk1mfzYYDYW_CLo&address=" + urllib.urlencode(
            encode_query)

        fetch_result = urlfetch.fetch(geocode_url)
        geocode_result = json.loads(fetch_result.content)
        if (geocode_result['status'] == "OK"):
            longitude = geocode_result['results'][0]['geometry']['location'][
                'lng']
            latitude = geocode_result['results'][0]['geometry']['location'][
                'lat']

            Locations(host_name=host_name,
                      address=address,
                      comment=comment,
                      created_at=created_at,
                      lat=latitude,
                      lng=longitude).put()
            print("this shouldnt happen")
            self.redirect('/map')  #redirected to the map
        else:
            print(geocode_result)
            self.redirect('/locations')
Esempio n. 4
0
    def test_6_Locations_delete(self):
        '''
        Testing Deletion of Records on Locations

        '''

        new_l = Locations(
            "00003",  # zip
            3.0,  # avg rate
            3.0,  # avg price
            "$$$$",  # high price
            "$",  # low price
            "Italian",  # popular food type
            "Little Italy",  # highest rated restaurant
            "Pizza Joint",  # most popular restaurant
            40  # number restaurants
        )

        self.session_token.add(new_l)
        self.session_token.commit()

        l = self.session_token.query(Locations).filter_by(
            zipcode="00003").first()

        self.session_token.delete(l)
        self.session_token.commit()

        l = self.session_token.query(Locations).filter_by(
            zipcode="00003").first()

        assert l is None
        print("Passed Test6")
Esempio n. 5
0
 def test_02_00(self):
     dbsession = createdbsession('sqlite:///testdatabase.db',
                                 sqlecho=False,
                                 cleardown=True)
     with open('testlocations.csv', mode='r') as fp:
         csvreader = csv.reader(fp)
         for data in csvreader:
             add_location = Locations(locationid=data[0],
                                      name=data[1],
                                      description=data[2],
                                      sublocation=data[3])
             dbsession.add(add_location)
             print data
     with open('testmedia.csv', mode='r') as fp:
         csvreader = csv.reader(fp)
         for data in csvreader:
             add_media = Media(mediaid=data[0],
                               mediatype=data[1],
                               title=data[2],
                               description=data[3],
                               url=data[4],
                               barcode=data[5],
                               locationid=data[6])
             dbsession.add(add_media)
             print data
     dbsession.commit()
Esempio n. 6
0
def get_all_animals():
    # Open a connection to the database
    with sqlite3.connect("./kennel.db") as conn:

        # Just use these. It's a black box
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Write the SQL query to get the info you want
        db_cursor.execute("""
            SELECT
                a.id,
                a.name,
                a.breed,
                a.status,
                a.location_id,
                a.treatment,
                a.customer_id,
                l.name location_name,
                l.address location_address,
                c.name customer_name,
                c.address customer_address,
                c.email customer_email,
                c.password customer_password
            FROM animal a
            JOIN location l
                ON l.id = a.location_id
            JOIN customer c
                ON c.id = a.customer_id
        """)

        # Initialize an empty list to hold all animal representations 
        animals = []

        # Convert rows of data into a Python list
        dataset = db_cursor.fetchall()

        # Iterate list of data returned from database
        for row in dataset:

            # Create an animal instance from the current row.
            # Note that the database fields are specified in
            # the exact order of the parameters defined in the
            # Animal class above
            animal = Animal(row['id'], row['name'], row['breed'], row['status'], row['location_id'], row['treatment'], row['customer_id'])

            location = Locations(row['location_id'], row['location_name'], row['location_address'])

            customer = Customer(row['customer_id'], row['customer_name'], row['customer_address'], row['customer_email'], row['customer_password'])

            animal.location = location.__dict__

            animal.customer = customer.__dict__

            animals.append(animal.__dict__)

        # Use json package to properly serialize list as JSON
        return json.dumps(animals)
Esempio n. 7
0
 def add(self):
     if self.Description is None:
         self.Description = self.Name
     add_location = Locations(ID=self.ID,
                              Name=self.Name,
                              Description=self.Description,
                              Sublocation=self.Sublocation)
     self.dbsession.add(add_location)
     self.dbsession.commit()
     return 'Adding location {} - {}, {}, {}\n'.format(
         self.ID, self.Name, self.Description, self.Sublocation)
Esempio n. 8
0
def get_single_location(id):
    with sqlite3.connect("./kennel.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute("""
            SELECT
                l.id,
                l.name,
                l.address
            FROM location l
            WHERE l.id = ?
        """, (id,))

        data = db_cursor.fetchone()
        location = Locations(data['id'], data['name'], data['address'])

        return json.dumps(location.__dict__)
Esempio n. 9
0
def main(args):
    with open(args[0], 'r') as file:
        tt_data = literal_eval(file.read())
    for loc in tt_data:
        currrent_loc = Locations(loc[0], loc[1])
        session.add(currrent_loc)
        session.flush()

        song_dict = tt_data[loc]
        for song_id in song_dict:
            count = song_dict[song_id][0]
            artist_id = song_dict[song_id][2]
            create_if_not_exists(Artists, id=artist_id)
            create_if_not_exists(Songs, tunes_id=song_id, artist_id=artist_id)

            session.refresh(currrent_loc)
            session.flush()
            current_play = Plays(currrent_loc.id, song_id, count)
            session.add(current_play)
        print(currrent_loc.id)

    session.commit()
Esempio n. 10
0
def get_all_locations():
    with sqlite3.connect("./kennel.db") as conn:

        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute("""
            SELECT
                l.id,
                l.name,
                l.address
            FROM location l
        """)

        locations = []
        dataset = db_cursor.fetchall()

        for row in dataset:

            location = Locations(row['id'], row['name'], row['address'])
            locations.append(location.__dict__)

        return json.dumps(locations)
Esempio n. 11
0
def result():
    zip_code = request.form['zip_code']
    url = 'https://maps.googleapis.com/maps/api/geocode/json?address='+zip_code+'&sensor=true&key=AIzaSyCDKSQdglP_kfxPsZsDfqXxO0T193LJZfs'

    params = {
        'address': zip_code,
        'sensor': 'true',
        'key': 'AIzaSyCDKSQdglP_kfxPsZsDfqXxO0T193LJZfs'
    }
    req = requests.get(url, params=params)
    res = req.json()
    address = res['results'][0]['formatted_address']
    latitude = res['results'][0]['geometry']['location']['lat']
    lat = str(latitude)
    longitude = res['results'][0]['geometry']['location']['lng']
    long = str(longitude)
    from models import Locations
    new_zip_code = Locations(zip_code=zip_code, address=address, latitude=lat, longitude=long)

    db.session.add(new_zip_code)
    db.session.commit()

    return render_template('result.html', zip_code=zip_code, address=address, lat=lat, long=long)
Esempio n. 12
0
    def test_5_Locations_manual_integrity(self):
        '''
        Testing query data on Locations

        '''

        new_l = Locations(
            "00002",  # zip
            3.0,  # avg rate
            3.0,  # avg price
            "$$$$",  # high price
            "$",  # low price
            "Italian",  # popular food type
            "Little Italy",  # highest rated restaurant
            "Pizza Joint",  # most popular restaurant
            40  # number restaurants
        )

        self.session_token.add(new_l)
        self.session_token.commit()

        loc = self.session_token.query(Locations).filter_by(
            zipcode="00002").first()

        assert not self.session_token.query(Locations) is None

        # test serialize
        assert isinstance(loc.to_dict(), dict)

        # test query
        assert loc.zipcode == "00002"
        assert loc.average_rating == 3.0
        assert loc.average_price == 3.0
        assert loc.highest_price == "$$$$"
        assert loc.popular_food_type == "Italian"
        assert loc.highest_rated_restaurant == "Little Italy"
        print("Passed Test5")
Esempio n. 13
0
from app import db
from models import Locations, TempHistory
from datetime import datetime

#create
db.create_all()

#insert
db.session.add_all([
    Locations('Tokio', 35.6584421, 139.7328635),
    Locations('Helsinki', 60.1697530, 24.9490830),
    Locations('New York', 40.7406905, -73.9938438),
    Locations('Amsterdam', 52.3650691, 4.9040238),
    Locations('Dubai', 25.092535, 55.1562243)
])

db.session.add_all([
    TempHistory(1, 0),
    TempHistory(2, 0),
    TempHistory(3, 0),
    TempHistory(4, 0),
    TempHistory(5, 0)
])

#commit
db.session.commit()