def test_update_location(self): project = Project.create(name='tomate', description='tomatensalat', url='hallo') Location.create(title='funfunfun', lat=0.0, lng=0.0, description='nochmehrfun', project=project) response = self.client.put('/tomate/funfunfun/', '{"description":"wenigerfunohhhh"}', **{'Authorization':'Bearer '+self.login.token()}) self.assertEqual(response.status_code, 200) location = Location.objects.get(title='funfunfun') self.assertEqual(location.description, 'wenigerfunohhhh')
def change_beer(request): json_string = request.REQUEST["json"] data = json.loads(json_string) tap_id = data["tap"] # try to grab the brewery id. if there is none, create the brewery if "breweryId" in data: brewery = Brewery.objects.get(id = data["breweryId"]) else: location = Location(lon = 0, lat = 0) location.save() brewery = Brewery(name = data["breweryName"], location = location) brewery.save() if "beerId" in data: beer = Beer.objects.get(id = data["beerId"]) else: beer = Beer(name = data["beerName"], maker = brewery) beer.save() tap = Tap.objects.get(id = tap_id) tap.beer = beer tap.save() return HttpResponse("success")
def test_delete_location(self): project = Project.create(name='tomate', description='tomatensalat', url='hallo') Location.create(title='funfunfun', lat=0.0, lng=0.0, description='nochmehrfun', project=project) response = self.client.delete('/tomate/funfunfun/', **{'Authorization':'Bearer '+self.login.token()}) self.assertEqual(response.status_code, 200) location = Location.objects.filter(title='funfunfun') self.assertEqual(len(location), 0)
def test_creating_hour(self): location = { 'name': 'Youth Green', 'category': 'Community Garden', 'address_1': '12467 W. Osborne Street', 'city': 'Los Angeles', 'state': 'CA', 'zipcode': '91331', 'latitude': 34.25777331, 'longitude': -118.4046685 } loc = Location(**location) loc.save() hour = Hour(day='AllMo', open_time='08:00', close_time='14:00', location_id=loc.id) hour.save() query = Hour.objects.filter(day='AllMo') hour = query[0] self.assertEqual(1, len(query)) self.assertEqual('AllMo', hour.day) self.assertEqual('08:00:00', str(hour.open_time)) self.assertEqual('14:00:00', str(hour.close_time)) self.assertEqual(loc.id, hour.location_id)
def handle(self, *args, **options): module_dir = os.getcwd() # get current directory file_path = os.path.join(module_dir, options['file']) with open(file_path) as f: content = f.readlines() # you may also want to remove whitespace characters like `\n` at the end of each line lines = [x.strip() for x in content] lines.pop(0) for curr_line in lines: fields = curr_line.split('\t') try: product = Product.objects.get(product_id=fields[0]) except: product = None if not product: print('adding product') product = Product(product_id=fields[0], description=fields[1]) product.save() location = Location(product=product, datetime=fields[2], \ longitude=fields[3], latitude=fields[4], elevation=fields[5]) location.save()
def test_get_location(self): project = Project.create(name='tomate', description='tomatensalat', url='hallo') Location.create(title='funfunfun', lat=0.0, lng=0.0, description='nochmehrfun', project=project) response = self.client.get('/tomate/funfunfun/', **{'Authorization':'Bearer '+self.login.token()}) self.assertEqual(response.status_code, 200) data = response.content.decode('utf-8') self.assertJSONEqual(data, {'title':'funfunfun', 'description':'nochmehrfun', 'lat':0.0, 'lng':0.0})
def add_bar(request): json_string = request.REQUEST["json"] data = json.loads(json_string) bar_name = data["barName"] location = Location(lon = 0, lat = 0) location.save() b = Bar(name = bar_name, location = location) b.save() return HttpResponse(json.dumps({"bar": {"name": b.name, "id": b.id}}))
def test_creating_location(self): loc = Location(**self.sample_location_data) loc.save() query = Location.objects.filter(name='Youth Green') self.assertEqual(1, len(query)) loc = query[0] self.assertEqual('Los Angeles', loc.city) self.assertEqual('91331', loc.zipcode) self.assertEqual(34.257773, float(loc.latitude))
def update_court_locations_in_db(self): court_locations = self.client.service.getCourtLocations() efiling_locations = self.efiling_interface.get_court_locations_address( ) for court_location in court_locations: court_type = ("", "P")[court_location['isProvincialYn'] == "Y"] + ( "", "S")[court_location['isSupremeYn'] == "Y"] court_address = "" court_city = "" court_province = "" court_postcode = "" matched_efiling_location = [ loc for loc in efiling_locations if (loc["short_description"] == court_location['agenAgencyIdentifierCd']) ] if (len(matched_efiling_location) == 1): efiling_location = matched_efiling_location[0] court_address = convert_full_address( efiling_location["address_line1"], efiling_location["address_line2"], efiling_location["address_line3"]) court_city = efiling_location["city"] court_province = efiling_location["province"] court_postcode = efiling_location["postal_code"] try: court_result = Location.objects.get( location_code=court_location['agenAgencyIdentifierCd']) court_result.name = court_location['agenAgencyNm'] court_result.location_id = str(court_location['agenId']) court_result.type = court_type court_result.address = court_address court_result.city = court_city court_result.province = court_province court_result.postcode = court_postcode court_result.save() except: new_court_result = Location( location_code=court_location['agenAgencyIdentifierCd'], name=court_location['agenAgencyNm'], location_id=str(court_location['agenId']), type=court_type, address=court_address, city=court_city, province=court_province, postcode=court_postcode) new_court_result.save()
def account_organization(request): s = Sponsor.objects.filter(user__email=request.session['email']).first() message = None class OrganizationForm(forms.ModelForm): class Meta: model = Organization exclude = ('location', ) if request.method == "POST": org_form = OrganizationForm(request.POST, request.FILES, instance=s.organization) if org_form.is_valid(): org_form.save() location_obj = json.loads(request.POST['j_string']) full_name = location_obj['formatted_address'] try: pos_loc = Location.objects.get(full_name__icontains=full_name) s.organization.location = pos_loc s.organization.save() message = 'Location found in database! (using exsiting)' except Exception as e: message = 'Location added to database!' try: pos_loc = Location(place=location_obj) pos_loc.save() s.organization.location = pos_loc s.organization.save() except Exception as e: message = 'Invalid location! (%s)' % str(e) else: org_form = OrganizationForm(instance=s.organization) try: location = s.organization.location.full_name except: location = None print(location, message) return render(request, 'sponsor/dashboard/account/organization.html.j2', context={ 'title': 'Account - Organization', 'org_form': org_form, 'location': location, 'message': message, })
def create_location(): body = request.get_json() owner_id = body['owner_id'] user = User.query.get(owner_id) if user is None: return error.not_found('User not found') location = Location(owner_id=user.id, name=body['name']) db.session.add(location) db.session.commit() return jsonify(location.to_dict())
def post(self, request): if request.data.get('type') == 'get': print("inside views post ", request.data) #For getting an individual group that a user is part of g = Group.objects.get(groupName=request.data.get('groupname')) m = MemberShip.objects.filter(group=g) m = m.values_list('person', flat=True) profiles = Profile.objects.filter(pk__in=m) jsonRes = serializers.serialize('json', profiles) #locations - all nearby locations to the midpoint of the group. locations = Location.objects.filter(group=g) locationsJson = serializers.serialize('json', locations) print('locations:', locationsJson) return Response({ 'members': jsonRes, 'locations': locationsJson, 'midpoint': g.midpoint }) else: g = Group() #For creating a new group. print("inside views post ", request.data) g.groupName = request.data.get('groupname') g.save() p = Profile.objects.get(user=request.user) g.midpoint = getCoordinates(p.Location) m1 = MemberShip(group=g, person=p) m1.save() g.save() print('membership', m1, g.midpoint) #midpoint created of the creating users location. places = getPlaces(g.midpoint) print(places) #get locations close to them for place in places: l = Location(locationName=place['name'], latLong=place['coordinates'], rating=place['rating'], types=place['types'], group=g) l.save() serializer = GroupSerializer(g) l = Location.objects.filter(group=g) jsonRes = serializers.serialize('json', l.all()) print("locations:", jsonRes) print('gorupL', serializer.data) return Response({'group': serializer.data, 'locations': jsonRes})
def handle(self, *args, **options): for filename in os.listdir('csv_hours_test_data'): print('importing CSV file {0}'.format(filename)) with open(os.path.join('csv_hours_test_data', filename), 'r') as f: reader = csv.reader(f) next(f) for r in reader: print('populating row: {0}'.format(r)) loc = Location(name=r[0], address_1=r[1], address_2=r[2], city=r[3], state=r[ 4], zipcode=r[5], phone=r[6], latitude=r[7], longitude=r[8], category=r[9], website=r[10], active=True) loc.save() hours = list(filter(None, r[11:])) for i in [hours[i:i + 3] for i in range(0, len(hours), 3)]: h = Hour(day=i[0], open_time=i[1], close_time=i[2], location=loc) h.save()
def test_fetches_index(self): Location(name='Test Community Garden', latitude=0, longitude=0).save() response = self.client.get('/locations') self.assertEqual(200, response.status_code) self.assertEqual(1, len(response.json())) self.assertEqual('Test Community Garden', response.json()[0]['name'])
def test_fetches_by_location(self): Location(name='Test Community Garden', latitude=12.345678, longitude=12.345678).save() # query within radius response = self.client.get('/nearby_locations', { 'latitude': 12.345678, 'longitude': 12.345678 }) self.assertEqual(200, response.status_code) self.assertEqual(1, len(response.json())) self.assertEqual('Test Community Garden', response.json()[0]['name']) # query outside of radius response = self.client.get('/nearby_locations', { 'latitude': 12.30, 'longitude': 12.345678 }) self.assertEqual(200, response.status_code) self.assertEqual(0, len(response.json())) # query with radius override response = self.client.get('/nearby_locations', { 'radius': 15000, 'latitude': 12.30, 'longitude': 12.345678 }) self.assertEqual(200, response.status_code) self.assertEqual(1, len(response.json()))
def handle(self, *args, **options): Location.objects.all().delete() Hour.objects.all().delete() csv_files = [ 'farmers-market.csv', 'community_gardens.csv', 'food-pantry.csv', 'supermarket.csv' ] location_count = 0 for file in csv_files: try: with open('csv_files/{}'.format(file), 'r') as f: reader = csv.reader(f) next(f) for r in reader: loc = Location(name=r[0], address_1=r[1], address_2=r[2], city=r[3], state=r[4], zipcode=r[5], phone=r[6], latitude=r[7], longitude=r[8], category=r[9], website=r[10], active=True) loc.save() hours = list(filter(None, r[11:])) for i in range(0, len(hours), 3): day, open_time, close_time = hours[i:i + 3] hour = Hour( day=day, open_time=self._format_time(open_time), close_time=self._format_time(close_time), location=loc) hour.save() location_count += 1 except: self.stdout.write( "Not all rows loaded to the database. The last row loaded was {0} {1}. The ingest failed in file {2}" .format(loc.name, loc.address_1, file)) self.stdout.write( "{} locations have been added to the database.".format( location_count))
def handle(self, *args, **options): for filename in os.listdir('csv_files'): print('importing CSV file {0}'.format(filename)) with open(os.path.join('csv_files', filename), 'r') as f: reader = csv.reader(f) next(f) # skips first line so we don't import headers for r in reader: print('populating row: {0}'.format(r)) loc = Location(name=r[1], category=r[2], address_1=r[3], city=r[4], state=r[5], zipcode=r[6], latitude=float(r[7]), longitude=float(r[8])) loc.save()
def put(self, request): #for adding a user to a group try: p = Profile.objects.get(EmailAddress=request.data.get('email')) g = Group.objects.get(groupName=request.data.get('groupname')) m1 = MemberShip(group=g, person=p) m1.save() #update the midpoint members = MemberShip.objects.filter(group=g) locationtexts = [] #get the coordinates of all members in the group - need to recalculate midpoint based on new coords. for m in members: coord = getCoordinates(m.person.Location) if coord != (0, 0): locationtexts.append(m.person.Location) g.midpoint = finalmidpoint(locationtexts) g.save() #delete all old places. Location.objects.filter(group=g).delete() #get new locations places = getPlaces(g.midpoint) for place in places: l = Location(locationName=place['name'], latLong=place['coordinates'], rating=place['rating'], types=place['types'], group=g) l.save() locations = Location.objects.filter(group=g) jsonRes = serializers.serialize('json', locations.all()) serializer = GroupSerializer(g) print('locations:', jsonRes) return Response({ 'group': serializer.data, 'success': 'success', 'locations': jsonRes }) except Exception as e: print('not saved', e) return Response({'success': 'fail'})
def handle(self, *args, **options): Location.objects.all().delete() Hour.objects.all().delete() csv_files = ['farmers-market.csv', 'community_gardens.csv', 'food-pantry.csv', 'supermarket.csv'] location_count = 0 for file in csv_files: try: with open('csv_files/{}'.format(file), 'r') as f: reader = csv.reader(f) next(f) for r in reader: loc = Location(name=r[0], address_1=r[1], address_2=r[2], city=r[3], state=r[4], zipcode=r[5], phone=r[6], latitude=r[7], longitude=r[8], category=r[9], website=r[10], active=True) loc.save() hours = list(filter(None, r[11:])) for i in range(0, len(hours), 3): day, open_time, close_time = hours[i:i + 3] hour = Hour(day=day, open_time=self._format_time(open_time), close_time=self._format_time( close_time), location=loc) hour.save() location_count += 1 except: self.stdout.write( "Not all rows loaded to the database. The last row loaded was {0} {1}. The ingest failed in file {2}".format(loc.name, loc.address_1, file)) self.stdout.write( "{} locations have been added to the database.".format(location_count))
def handle(self, *args, **options): with open('data/locations.json', 'r') as f: location_str = f.read() locations = json.loads(location_str) province = Province.objects.get(name="Islas Baleares") for location in locations: l = Location() l.lat = location.get('lat') l.lng = location.get('lng') l.name = location.get('name') l.province = province l.save()
def test_querying_by_location(self): Location(**self.sample_location_data).save() query = Location.objects.in_distance(1, fields=['latitude', 'longitude'], points=[34.257773, -118.404669]) self.assertEqual(1, len(query)) query = Location.objects.in_distance(1, fields=['latitude', 'longitude'], points=[0, 0]) self.assertEqual(0, len(query))
def post(self, request): pathlist = request.data.get('path') path_objects = [] for sets in json.loads(pathlist): path_objects.append(Location(latitude=sets["latitude"], longitude=sets["longitude"])) Location.objects.bulk_create(path_objects) trip = Trip.objects.create(device=request.user) trip.path.add(*path_objects) return Response({ "status": "OK", "tripKey": trip.trip_key }, status=status.HTTP_200_OK )
def handle(self, *args, **options): with open('data/locations.json', 'r') as f: location_str = f.read() locations = json.loads(location_str) for location in locations: l = Location() l.lat = location.get('lat') l.lng = location.get('lng') l.name = location.get('name') l.save()
def test_creating_hour(self): location = {'name': 'Youth Green', 'category': 'Community Garden', 'address_1': '12467 W. Osborne Street', 'city': 'Los Angeles', 'state': 'CA', 'zipcode': '91331', 'latitude': 34.25777331, 'longitude': -118.4046685} loc = Location(**location) loc.save() hour = Hour(day='AllMo', open_time='08:00', close_time='14:00', location_id=loc.id) hour.save() query = Hour.objects.filter(day='AllMo') hour = query[0] self.assertEqual(1, len(query)) self.assertEqual('AllMo', hour.day) self.assertEqual('08:00:00', str(hour.open_time)) self.assertEqual('14:00:00', str(hour.close_time)) self.assertEqual(loc.id, hour.location_id)
def process_feature(self, feature): if feature['geometry']['type'] == 'MultiPolygon': multi_polygon = GEOSGeometry( json.dumps(feature['geometry']), srid=3857) try: location = Location.objects.get( name=feature['properties']['address']) except Location.DoesNotExist: location = Location() location.name = feature['properties']['address'] location.geom = multi_polygon location.point = location.geom.centroid location.authority = feature['properties']['la'] location.owner = feature['properties']['la'] try: location.save() except Exception as e: print('Could not add: {0} because: {1}'.format( location.name, e))
def handle(self, *args, **options): """ Insert all location.json file locations on data base """ print("Inserting data...") p = Province() p.name = "Islas Baleares" p.save() with open('data/locations.json', 'r') as f: location_str = f.read() locations = json.loads(location_str) province = Province.objects.get(name="Islas Baleares") for location in locations: l = Location() l.lat = location.get('lat') l.lng = location.get('lng') l.name = location.get('name') l.name_ca = location.get('name') l.province = province l.save()
def contact(request): me = User.objects.get(pk=request.session['pk']) p = Seeker.objects.filter(user=me).first() location = p.location message = None if request.method == "POST": data = parser.parse(request.POST.urlencode()) extra_info = data['extra'] loc_json = json.loads(data['location']) print(json.dumps(loc_json,indent=4)) location = Location.objects.filter(full_name__icontains=loc_json['formatted_address']).first() message = "Location same as before!" if location is None : try: location = Location(place=loc_json) location.extra = extra_info location.save() p.location = location message = "Location successfully added & updated!" except Exception as e: message = "Invalid location! Please re-enter! (%s)" % str(e) elif location != p.location: location.extra = extra_info location.save() p.location = location message = "Location successfully updated!" p.save() return render(request, 'healthseeker/contact_details.html', { 'title' : "Account - Location Settings", 'seeker' : p, 'message' : message, 'location' : p.location.full_name, 'extra_info' : p.location.extra, })
def account_contact(request): me = User.objects.get(pk=request.session['pk']) p = me.provider_set.filter(poc__id=request.session['pk']).first() if request.method == "POST": data = parser.parse(request.POST.urlencode()) place = data['place'] place['address_components'] = list( place['address_components'].values()) for comp in place['address_components']: comp['types'] = comp['types'][''] if isinstance(comp['types'], str): comp['types'] = [comp['types']] print(json.dumps(place, indent=4)) try: l = Location(place=place) l.save() status = True data = place except Exception as e: print(e) temp_loc = Location.objects.filter( full_name__icontains=place['formatted_address']).first() l = temp_loc or p.location if l == p.location: status = True data = ["Same Location as before!"] elif temp_loc is None: status = False data = [str(e)] else: status = True data = l p.location = l p.save() if isinstance(data, Location): class LocationSerializer(ModelSerializer): class Meta: depth = 1 fields = ( 'lat', 'long', 'full_name', 'name', ) model = Location data = LocationSerializer(data).data return JsonResponse({ 'status': status, 'data': data, }) return render(request, 'healthprovider/dashboard/account/contact.html.j2', { 'title': "Account - Location Settings", 'hospital': p, })
def create(self, validated_data): location = Location(**validated_data) location.save() location.users.add(self.context['request'].user) return location
from api.models import Location, Place import csv """ Script to import data from .csv file to Model Database DJango This mus to be in same folder of the manage.py file To execute this script run: 1) manage.py shell 2) exec(open('upload_data_from_file.py').read()) """ path = 'places_london.csv' with open(path, encoding="ISO-8859-1") as csvfile: reader = csv.DictReader(csvfile) for row in reader: # print(row) try: place = Place.objects.get(name__exact = row['place']) except: break p = Location(name = row['location'], latitude = row['latitude'], longitude = row['longitude'], place = place) p.save() exit()
def step4(request): ''' enter the location details ''' >>>>>>> dev me = User.objects.get(pk=request.session['pk']) p = Seeker.objects.filter(user=me).first() message = None if request.method == "POST": data = parser.parse(request.POST.urlencode()) place = json.loads(data['location']) extra_info = ', '.join(data['extra']).strip(' ') print(extra_info, json.dumps(place, indent=4), sep="\n") try: location = Location.objects.filter(full_name__icontains=place['formatted_address']).first() if not location: location = Location(place=place) location.extra = extra_info location.save() p.location = location p.save() return redirect('healthseeker:step5') except Exception as e: message = "Invalid Location! Please re-renter! (%s)" % str(e) return render(request, 'healthseeker/registration/form4.html', { 'title' : "Account - Location Settings", 'seeker' : p, 'message' : message, })
def create_location(self): return Location()
from api.models import Location from api.serializers import LocationSerializer from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser location = Location(source='test1', country_id=1, country='testcountry1') location.save() location = Location(source='test2', country_id=2, country='testcountry2') location.save() locationSerialize = LocationSerializer(location) locationSerialize.data