def test_create_and_read(self): """Test create user""" user = User(name='Nicholas Cage', age=49, gender='m') db.session.add(user) db.session.commit() user = User.query.filter_by(name='Nicholas Cage').first() location1 = Location(city="Los Angeles", latitude=34.063566, longitude=-118.421092) location2 = Location(city="San Francisco", latitude=37.69841, longitude=-122.454232) user.locations.extend([location1, location2]) db.session.add(user) db.session.commit() user = User.query.filter_by(name='Nicholas Cage').first() locations = Location.query.all() self.assertGreater(len(locations), 2) location = Location.query.filter_by(city='Los Angeles').first() self.assertEqual(location.city, 'Los Angeles') self.assertEqual(location.latitude, 34.062264) self.assertEqual(location.longitude, -118.340361)
def test_get_location_coordinates(app): location = Location(location='POINT(-94.782234 38.880684)') coords = location.coords assert coords.get('latitude') == 38.880684 assert coords.get('longitude') == -94.782234 bad_location = Location(location=None) bad_coords = bad_location.coords assert bad_coords.get('latitude') == None assert bad_coords.get('longitude') == None
def init_db(): # Locations storage = Location(name='Storage Room') storage.save() assembly = Location(name='Assembly Room') assembly.save() electronics = Location(name='Electronics') electronics.save() # Materials in storage room plywood2mm = Item(name='Plywood 2mm 900x600mm Sheet', location=storage, price=11.15) plywood2mm.save() mdf4mm = Item(name='MDF 4mm 900x600mm Sheet', location=storage, price=5.67) mdf4mm.save() acrylic5mm = Item(name='Acrylic 5mm 900x600mm Sheet', location=storage, price=19.34) acrylic5mm.save() # Supplies in assembly room woodGlue = Item(name='Wood Glue', location=assembly, price=9.0) woodGlue.save() nails1mm2cm = Item(name='Nails 1mm 2cm Long', location=assembly, price=0.7) nails1mm2cm.save() screws3mm3cm = Item(name='Wood Screws 3mm 3cm Long', location=assembly, price=0.8) screws3mm3cm.save() drill5mm = Item(name='Drill 5mm for Wood', location=assembly, price=5.05) drill5mm.save() # Electroncs items resistor200ohm = Item(name='Resistor SMT 200', location=electronics, price=0.2) resistor200ohm.save() resistor22k = Item(name='Resistor SMT 22K', location=electronics, price=0.2) resistor22k.save() openpir = Item(name='Sparkfun OPENPIR Motion Sensor', location=electronics, price=20.0) openpir.save()
def construct_Location(): location_dict = {} u_locations =list(set([row['work_location2'] for index, row in complete_data2.iterrows()])) for u_location in u_locations: geo = geocoder.google(u_location).latlng if not type(geo) == type(geocoder.google('').latlng): location_dict[u_location] = Location(address = u_location, lat = geo[0], long = geo[1], geocodeBool = 1) else: location_dict[u_location] = Location(address = u_location, geocodeBool = 0) time.sleep(2) db.session.add_all([location_dict[key] for key in location_dict.keys()]) db.session.commit()
def test_get_locations_list(app): """ GIVEN a Flask application WHEN the '/locations' page is requested (GET) THEN check the response is valid """ # insert a location into the database location_1 = Location(address='123 test street', city='Kansas City', state='MO', zip_code=66213, location='POINT(-83.123456 39.123432)') location_2 = Location(address='456 test way', city='Kansas City', state='KS', zip_code=66210, location='POINT(-83.654321 39.654321)') db.session.add(location_1) db.session.add(location_2) db.session.commit() with app.test_client() as client: response = client.get('/locations') assert response.status_code == 200 data = response.get_json() resp_locations = sorted(data.get('locations'), key=itemgetter('address')) assert resp_locations is not None test_location1 = { "id": resp_locations[0].get("id"), "address": "123 test street", "city": "Kansas City", "state": "MO", "zipCode": 66213, "longitude": -83.123456, "latitude": 39.123432 } test_location2 = { "id": resp_locations[1].get("id"), "address": "456 test way", "city": "Kansas City", "state": "KS", "zipCode": 66210, "longitude": -83.654321, "latitude": 39.654321 } assert resp_locations == [test_location1, test_location2]
def test_delete_restaurant(self): ''' removes all instances of the above created restaurant objects includes: [restaurant, location, restaurant_info] ''' ins_restaurant = Restaurant('John Doe', '5103388949') ins_restaurant.insert() restaurant_id = ins_restaurant.id print(f'INSERTED for DELETION: {restaurant_id}') ins_location = Location(restaurant_id=restaurant_id, address='1234 John Doe Ave', city='San Francisco', zipcode=94502, state='CA') ins_ri = RestaurantInfo(restaurant_id=restaurant_id, website='DELETION', description='John Doe Bakery', classification='type_all', yelp_link='yelp.com/1') ins_location.insert() ins_ri.insert() print(ins_ri) res = self.client().delete(f'/restaurants/{restaurant_id}') data = json.loads(res.data) self.assertEqual(res.status_code, 200)
def api_user_activities(): data = request.get_json() try: old_achievements = utils.get_user_achievements(current_user) transitions = data["transitions"] locations = data["locations"] transitions_array = [] locations_array = [] for transition in transitions: transitions_array.append(Transition(transition["activityType"], transition["transitionType"], transition["timestamp"])) for location in locations: locations_array.append(Location(location["latitude"], location["longitude"], location["timestamp"], location["speed"], location["accuracy"])) activities = Activity.transitions_to_activity(transitions_array) merged_activities = Activity.merge_nears(activities) located_activities = Activity.add_locations(merged_activities, locations_array) utils.activity_handler(located_activities, current_user) new_achievements = utils.get_user_achievements(current_user) ret_object = list(set(new_achievements).difference(set(old_achievements))) return jsonify(ret_object) except Exception as e: print(type(e)) print(e) return jsonify({"message": str(e)}), 500
def test_get_location_by_id(app): """ GIVEN a Flask application WHEN the '/api/locations/{id}' page is requested (GET) THEN check the response is valid """ # insert a location into the database location = Location(address='123 test street', city='Kansas City', state='MO', zip_code=66213, location='POINT(-83.123456 39.123432)') db.session.add(location) db.session.commit() id = db.session.scalar(func.max(Location.id)) with app.test_client() as client: response = client.get(f'/locations/{id}') assert response.status_code == 200 data = response.get_json() assert data == { 'address': '123 test street', 'city': 'Kansas City', 'state': 'MO', 'zipCode': 66213, 'latitude': 39.123432, 'longitude': -83.123456 }
def get_single_location(id): with sqlite3.connect("./kennel.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() # Use a ? parameter to inject a variable's value # into the SQL statement. db_cursor.execute( """ SELECT l.id, l.name, l.address FROM location l WHERE l.id = ? """, (id, )) # Load the single result into memory data = db_cursor.fetchone() # Create an animal instance from the current row location = Location(data['id'], data['name'], data['address']) return json.dumps(location.__dict__) for location in LOCATIONS: if location["id"] == id: requested_location = location return requested_location
def get_single_employee(id): with sqlite3.connect("./kennel.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() # Use a ? parameter to inject a variable's value # into the SQL statement. db_cursor.execute( """ SELECT e.id, e.name, e.address, e.location_id, l.name location_name, l.address location_address FROM employee e JOIN Location l ON l.id = e.location_id WHERE e.id = ? """, (id, )) # Load the single result into memory data = db_cursor.fetchone() # Create an employee instance from the current row employee = Employee(data['id'], data['name'], data['address'], data['location_id']) # Create a Location instance from the current row location = Location(data['id'], data['location_name'], data['location_address']) # Add the dictionary representation of the location to the animal employee.location = location.__dict__ return json.dumps(employee.__dict__)
def admin_home(): locform = LocationForm() if locform.validate_on_submit(): ids = request.form.getlist('id') name = request.form.getlist('name') longitude = request.form.getlist('longitude') latitude = request.form.getlist('latitude') type = request.form.getlist('types') for (i, id) in enumerate(ids): if id.isdigit(): loc = Location.query.get(id) loc.longitude = longitude[i] loc.latitude = latitude[i] loc.name = name[i] loc.type = type[i].lower() db.session.commit() else: if longitude[i] and latitude[i] and name[i]: loc = Location(float(longitude[i]), float(latitude[i]), name[i], 'N/A', 'N/A') loc.type = type[i].lower() db.session.add(loc) db.session.commit() locations = Location.query.all() type_list = list() for type in location_type._asdict().values(): type_list.append(type.capitalize()) return render_template('admin.html', locations=locations, location_types=type_list, form=locform, username=current_user.username)
def new_location(request): """ New Location """ data = {} template = 'itembase/simpleform.djhtml' data['message'] = None data['headstring'] = 'New Location' if request.method == "POST": form = LocationForm(request.POST) if form.is_valid(): location = Location( lc_name=form.cleaned_data['lc_name'], lc_geo=form.cleaned_data['lc_geo'], lc_adr=form.cleaned_data['lc_adr'], lc_city=form.cleaned_data['lc_city'], lc_www=form.cleaned_data['lc_www'], lc_mail=form.cleaned_data['lc_mail'], lc_info=form.cleaned_data['lc_info'], ) location.save() print(location) membership = Membership( me_user=request.user, me_location=location, me_trust1=request.user, me_trust2=request.user, ) membership.save() print membership return redirect('itembase/home') return redirect('itembase/home') else: data['form'] = LocationForm() return render(request, template, data)
def __get_empty_location(self): # 每次统计空位置,都先清空之前的数据,避免影响本次数据. self.__list_empty_location.clear() for r in range(len(self.__map)): for c in range(len(self.__map[r])): if self.__map[r][c] == 0: self.__list_empty_location.append(Location(r, c))
def from_db_object(self, db_object): return SampleStamp(mac=Mac(db_object['mac']), location=Location(x=db_object['location']['x'], y=db_object['location']['y'], z=db_object['location']['z']), start_time=Time(int(db_object['start_time'])), end_time=Time(int(db_object['end_time'])))
def geocode_course(course: Course, session=None) -> Location: GOOGLE_GEOCODE_API = "https://maps.googleapis.com/maps/api/geocode/json" GOOGLE_GEOCODE_API_KEY = os.environ['GOOGLE_GEOCODE_API_KEY'] params = { "address": f"{course.name}, {course.city}, {course.state}", "key": GOOGLE_GEOCODE_API_KEY } if session is not None: resp = session.get(GOOGLE_GEOCODE_API, params=params) else: resp = requests.get(GOOGLE_GEOCODE_API, params=params) data = resp.json() if data['status'] != 'OK': raise ValueError(data['error_message']) addr = data['results'][0]['formatted_address'] loc = data['results'][0]['geometry']['location'] lat, lng = loc['lat'], loc['lng'] return Location(addr, lat, lng)
def add_data(): if request.method == 'POST': place = request.form.get('place') beacon1 = request.form.get('beacon1') beacon2 = request.form.get('beacon2') beacon3 = request.form.get('beacon3') beacon1x = request.form.get('beacon1x') beacon1y = request.form.get('beacon1y') beacon2x = request.form.get('beacon2x') beacon2y = request.form.get('beacon2y') beacon3x = request.form.get('beacon3x') beacon3y = request.form.get('beacon3y') try: location = Location(place=place, beacon1=beacon1, beacon1x=beacon1x, beacon1y=beacon1y, beacon2=beacon2, beacon2x=beacon2x, beacon2y=beacon2y, beacon3=beacon3, beacon3x=beacon3x, beacon3y=beacon3y) db.session.add(location) db.session.commit() return getqr(location.id) except: return "Operation Fail" return render_template("getdata.html")
def get_all_animals(): with sqlite3.connect('./kennels.db') as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() db_cursor.execute(""" SELECT a.id, a.name, a.breed, a.status, a.location_id, a.customer_id, l.name location_name, l.address location_address FROM Animal a JOIN Location l ON l.id = a.location_id """) animals = [] dataset = db_cursor.fetchall() for row in dataset: animal = Animal(row['id'], row['name'], row['breed'], row['status'], row['location_id'], row['customer_id']) location = Location(id=row['location_id'], address=row['location_address'], name=row['location_name']) animal.location = location.__dict__ animals.append(animal.__dict__) return json.dumps(animals)
def test01_setup(self): "Setting up for related model tests." for name, state, lon, lat in cities: loc = Location(point=Point(lon, lat)) loc.save() c = City(name=name, state=state, location=loc) c.save()
def addLocation(_, info, **kwargs): print("kwargs>>", kwargs) new_location_dict = {x: kwargs[x] for x in kwargs} print("new_location_dict>>>", new_location_dict) newlocation = Location(**new_location_dict) newlocation.save() return newlocation
def get_all_locations(): # Open a connection to the database with sqlite3.connect("./kennel.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() # Write the SQL query to get the information you want db_cursor.execute(""" SELECT l.id, l.name, l.address FROM location l """) # Initialize an empty list to hold all location representations locations = [] dataset = db_cursor.fetchall() # Iterate all rows of data returned from database for row in dataset: # Create an location instance from the current row location = Location(row['name'], row['address']) location.id = row['id'] locations.append(location.__dict__) return json.dumps(locations)
def fetch_all_stores_in_zip(self, zipcode): """ Fetches all of the stores for a given zip code :param zipcode: the zip code - int :returns a list of Stores found - list<Store> """ # Build URL to make API call url = self.build_url(self.REQUEST_NAME, ZipCode=zipcode) # Request data from server (XML) xml_str = requests.get(url, headers=self.HEADERS).text # Parse XML into an XML object xml = untangle.parse(xml_str) stores = list() try: # Create a Store object for each XML element and add it to the list for elem in xml.ArrayOfStore.Store: store_id = elem.StoreId.cdata name = elem.Storename.cdata.strip() address = elem.Address.cdata.strip() city = elem.City.cdata.strip() state = elem.State.cdata.strip() zip_str = elem.Zip.cdata.strip()[:5] zipcode = int(zip_str) if len(zip_str) > 0 else None # phone = elem.Phone.cdata.strip() loc = Location(address, city, state, zipcode) store = Store(store_id, name, loc) stores.append(store) except IndexError: pass return stores
def get_single_location(id): with sqlite3.connect("./kennel.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() # Use a ? parameter to inject a variable's value # into the SQL statement. db_cursor.execute( """ SELECT a.id, a.name, a.address FROM location a WHERE a.id = ? """, (id, )) # Load the single result into memory data = db_cursor.fetchone() # Create an location instance from the current row location = Location( data['id'], data['name'], data['address'], ) return json.dumps(location.__dict__)
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 = Location(row['id'], row['name'], row['address']) # location.animals = json.loads(get_animals_by_location(int(row['id']))) # location.employees = json.loads(get_employees_by_location(int(row['id']))) locations.append(location.__dict__) return json.dumps(locations)
def get_all_locations(): with sqlite3.connect("./kennel.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() db_cursor.execute(""" SELECT a.id, a.name, a.address FROM location a """) locations = [] dataset = db_cursor.fetchall() for row in dataset: location = Location(row['id'], row['name'], row['address']) locations.append(location.__dict__) return json.dumps(locations)
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 information you want db_cursor.execute(""" SELECT a.id, a.name, a.breed, a.status, a.location_id, 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 animal = Animal(row['id'], row['name'], row['breed'], row['status'], row['location_id'], row['customer_id']) # Create a Location instance from the current row location = Location(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']) # Add the dictionary representation of the location to the animal animal.location = location.__dict__ animal.customer = customer.__dict__ # Add the dictionary representation of the animal to the list animals.append(animal.__dict__) # Use `json` package to properly serialize list as JSON return json.dumps(animals)
def location_list(request): if request.method == 'GET': return get_location_list() if request.method == 'POST': if not request.user.is_authenticated(request): return HttpResponse('Unauthorized', status=401) data = json.loads(request.body) l = None if not data.get('id'): l = Location(user=request.user, data=json.dumps(data), name=data['name']) l.save() data["id"] = l.id l.data = json.dumps(data) l.save() else: l = Location.objects.get(pk=int(data['id'])) if (request.user.is_staff == False): if (l.user.pk != request.user.pk): return HttpResponse(json.dumps({'error': 'not authorized'}), content_type="application/json") l.data = json.dumps(data) l.name = data['name'] l.save() return HttpResponse(json.dumps(l.data), content_type="application/json") return HttpResponse(json.dumps({'error': 'must be get or post request'}), content_type="application/json")
def new_location(id=None): """Agregado y actualizacion de ojetos Location""" locations = Location.query.order_by('location_name').all() form = forms.CreateLocation(request.form) if request.method == 'GET' and id is not None: loc = Location.query.filter(Location.id == id).one_or_none() if loc is not None: form.name.data = loc.location_name else: abort(404) if request.method == 'POST' and form.validate(): if id is not None: loc = Location.query.filter(Location.id == id).one() loc.location_name = form.name.data else: loc = Location(name=form.name.data) try: if loc.id is None: loc.add() else: loc.update() flash(('success', 'Locacion guardado exitosamente!.')) return redirect(url_for('new_location')) except Exception as e: print(e) flash(('danger', 'Lo sentimos algo salio mal!.')) return render_template('new_location.html', form=form, locations=locations)
def test_users_show_location(self): """This test method will confirm that a logged in user location is displayed on the page when a user logs in. """ L = Location(name="Home", address="False Test Creek SW, Long Beach CA", long=143.12, lat=-234.5, city="Long Beach", state="CA", user_id=self.testuser_id) L_id = 124 L.id = L_id db.session.add(L) db.session.commit() with self.client as c: with c.session_transaction() as sess: sess[CURR_USER_KEY] = self.testuser_id sess[CURR_LOCATION] = L_id resp = c.get("/users/datelocations") self.assertIn("False Test Creek SW, Long Beach CA", str(resp.data)) self.assertIn("Home", str(resp.data))
def get_all_employees(): with sqlite3.connect("./kennel.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() db_cursor.execute(""" SELECT e.id, e.name, e.location_id, l.name location_name, l.address location_address FROM Employee e JOIN Location l ON l.id = e.location_id""") employees = [] dataset = db_cursor.fetchall() for row in dataset: employee = Employee(row['id'], row['name'], row['location_id']) location = Location(row['location_id'], row['location_name'], row['location_address']) employee.location = location.__dict__ employees.append(employee.__dict__) return json.dumps(employees)
def from_db_object(self, db_object): return Position(mac=Mac(db_object['mac']), location=Location(x=db_object['location']['x'], y=db_object['location']['y'], z=db_object['location']['z']), created_at=Time(int(db_object['created_at'])), _id=db_object['_id'])