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 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_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 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 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 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 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 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 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 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 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 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 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 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 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 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 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, })
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 create(self, validated_data): location = Location(**validated_data) location.save() location.users.add(self.context['request'].user) return location
>>>>>>> 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 step5(request):
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, })