def handle(self, *args, **options): conn = sqlite3.connect(settings.DATABASES['default']['NAME']) for folder in options['folder']: try: # List all files in folder route_files = [f for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))] for route_file in route_files: rf = Route(name=route_file) rf.save() route_df = pd.read_csv(os.path.join(folder, route_file)) # standardize the table columns route_df.columns = ['timestamp', 'longitude', 'latitude', 'accuracy', 'speed'] route_df['route_id'] = rf.id # clean data from speed 0.0 and -1.0 and accuracy more then 200 meters # !!! part of data came with timestamp in milliseconds, part in seconds !!! route_df = route_df[(route_df["speed"] > 0) & (route_df["accuracy"] <= 200)] route_df.to_sql('routes_location', conn, if_exists='append', index=False) route_df except Exception as e: raise CommandError('Error importing data', e) self.stdout.write(self.style.SUCCESS('Successfully imported data from folder: %s' % folder))
def seedRoutes(request): existArray = [] noRouteArray = [] routeCount = 0 tbaTotal = 0 tbaCount = 0 data = fakeRoute() for item in data: print item tba = item['tba'] route = item['route'] try: r = Route.objects.get(route=route) except ObjectDoesNotExist: if route != "": cluster = filter(lambda x: x.isalpha(), route) routeCount += 1 r = Route(route=route, cluster=cluster) r.save() try: tba = Tba.objects.get(tba=tba) except ObjectDoesNotExist: tbaCount += 1 tbaTotal += 1 route = item['route'] r = Route.objects.get(route=route) # change status to at station for seed data ##status = item['status'] status = "At Station" #link not needed anymore since since is obsolete # link = item['link'] link = 'na' address = item['address'] city = item['city'] zipCode = item['zipCode'] tba = Tba(route=r, tba=tba, status=status, link=link, address=address, city=city, zipCode=zipCode) tba.save() else: tbaTotal += 1 existArray.append(tba.tba) existArrayLength = len(existArray) allRoutes = Route.objects.all() return render(request, 'seed/index.html')
def add_route(request): if request.method == 'POST': form = RouteModelForm(request.POST or None) if form.is_valid(): data = form.cleaned_data name = data['name'] from_city = data['from_city'] to_city = data['to_city'] travel_times = data['travel_times'] # Убираем пробелы из ID поездов transit_cities = data['transit_cities'].split(' ') trains = [int(x) for x in transit_cities if x.isalnum()] qs = Train.objects.filter(id__in=trains) route = Route(name=name, from_city=from_city, to_city=to_city, travel_times=travel_times) route.save() for train in qs: route.transit_cities.add(train.id) messages.success(request, 'Маршрут успешно сохранен!') return redirect('/') else: data = request.GET if data: from_city = data['from_city'] to_city = data['to_city'] travel_times = data['travel_times'] # Убираем пробелы из ID поездов transit_cities = data['transit_cities'].split(' ') trains = [int(x) for x in transit_cities if x.isnumeric()] qs = Train.objects.filter(id__in=trains) form = RouteModelForm( initial={ 'from_city': from_city, 'to_city': to_city, 'travel_times': travel_times, 'transit_cities': data['transit_cities'] }) route_descriptions = [] for train in qs: dsc = f'Поезд № {train.name} следующий из г. {train.from_city} в г. {train.to_city}. ' \ f'Время в пути {train.travel_time}' route_descriptions.append(dsc) context = { 'form': form, 'description': route_descriptions, 'from_city': from_city, 'to_city': to_city, 'travel_times': travel_times } return render(request, 'routes/create.html', context=context) else: messages.error(request, 'Невозможно сохранить несуществующий маршрут') redirect('/')
def handle(self, *args, **options): all_routes = set() all_stations = [] with open('moscow_bus_stations.csv', 'r', encoding="cp1251") as csvfile: reader = csv.reader(csvfile, delimiter=';') # пропускаем заголовок next(reader) for line in reader: routes = set(i.strip() for i in line[7].split(sep=';')) all_routes.update(routes) all_stations.append( (line[1], float(line[2]), float(line[3]), routes, line[7])) Station.objects.all().delete() Route.objects.all().delete() Route.objects.bulk_create(objs=[Route(name=r) for r in all_routes]) for st in all_stations: station = Station.objects.create(name=st[0], longitude=st[1], latitude=st[2], route_numbers=st[4]) rr = tuple(r for r in Route.objects.filter(name__in=st[3])) station.routes.add(*rr) station.save()
def get_directions(self, coords): # flip flop lat/lng because mapbox expects it that way coords_joined = ';'.join(Route.coords_lng_lat(coords)) params = { 'steps': 'true', 'continue_straight': 'true', 'access_token': os.getenv('MAPBOX_ACCESS_TOKEN'), } url = '%s%s?%s' % (DIRECTIONS_URL, coords_joined, urlencode(params)) return requests.get(url)
def saveRoute(request): points = [] if request.POST.has_key("points"): points = request.POST.getlist("points") routeName = request.POST.get("routeName") route = Route(name=routeName) route.save() for point in points: print "KURWA TU" print point address = getAddress(point).split(" ")[1:] saveAddress = Address( street=getStreet(address), number=getNumber(address), postCode=getCode(address), city=getCity(address) ) saveAddress.save() savePoint = Point( route=route, address=saveAddress, longitude=getLongitude(point), latitude=getLatitude(point) ) savePoint.save() return HttpResponse("Trasa zapisana") return HttpResponse("Wybierz conajmniej jeden punkt")
def addRoute(request): if request.method == "POST": type = request.POST.get('type') route = request.POST.get('route') quantity = request.POST.get('quantity') tbas = request.POST.get('tbas') tbasList = tbas.split("\n") if type == "Split": routeValue = route + "-" + type route = Route(route=routeValue, tbaCount=quantity, isSplit=True, cluster=routeValue) route.save() else: routeValue = type + "-" + route route = Route(route=routeValue, tbaCount=quantity, isUnplanned=True, cluster=type) route.save() for tba in tbasList: try: tba = Tba.objects.get(tba=tba).update(route=addRoute) tba.route = addRoute if type == "Split": tba.update(isSplit=True) else: tba.update(isUnplanned=True) tba.save() except: if type == "Split": newTba = Tba(tba=tba, route=route) newTba.save() else: newTba = Tba(tba=tba, route=route) newTba.save() message = "Route Addded Successfully!" return render(request, 'routes/index.html', {'message': message})
def planner(request, load = None): route = None if (load): try: route = Route.objects.get(owner = request.user, pk = int(load)) except: return render(request, 'route_list.html', {'error': 'Attempt to access invalid route'}) if (request.method == 'GET'): data = {} if route: data['load_route'] = json.dumps(route.as_json()) return render(request, 'routing.html', data) else: #TODO: 'Invalid data' responses should be more graceful try: data = json.loads(request.REQUEST.get('json', '{}')) if type (data) is not dict: return HttpResponse('Invalid data a') except: return HttpResponse('Invalid data b') if not route: route = Route(owner = request.user) #Round trip round_trip = request.REQUEST.get('round_trip', False) if type (round_trip) is not bool: round_trip = (str(round_trip) == 'on') route.roundtrip = round_trip route.name = request.REQUEST.get('name', 'Untitled') route.save() route.waypoint_set.all().delete() waypoints = data.get('waypoints', []) if type (waypoints) is not list: return HttpResponse('Invalid data c') for i in range(len(waypoints)): Waypoint(route = route, index = i, latitude = waypoints[i].get('lat', 0), longitude = waypoints[i].get('lng', 0)).save() route.calculate_distance() return HttpResponseRedirect('/routes/');
def handle(self, *args, **options): # import all the kml routes for filename in glob.glob('routes/kml/*.kml'): coords = [] # build route name from file name route_name = self.get_route_name(filename) # existing route found so delete coords route = Route.objects.all().filter(name=route_name) if route: route = route[0] self.stdout.write( self.style.WARNING('Found existing route %s' % route_name)) self.stdout.write( self.style.NOTICE('Deleting %s coords' % len(route.coords))) # create new route else: self.stdout.write( self.style.SUCCESS('Importing new route %s' % route_name)) route = Route(name=route_name) route.save() tree = etree.parse(filename) tracks = tree.xpath( '//gx:Tour//x:LookAt', namespaces=self.ns, ) # assign coordinates for track in tracks: coords.append('%s,%s' % ( track.xpath('./x:latitude', namespaces=self.ns)[0].text, track.xpath('./x:longitude', namespaces=self.ns)[0].text, )) self.stdout.write(self.style.SUCCESS('Saving coords')) route.coords = coords route.save() self.stdout.write(self.style.SUCCESS('Successfully imported'))
def main(): rjs = json.load(open('routes_detail.json', 'r')) from routes.models import Route, RouteStage from stages.models import Stage # For every route number in the dictionary for rj in rjs: # if the route is present already, edit it if not Route.objects.filter(city='delhi').filter(mtc_name=rj): new_route = Route() else: new_route = Route.objects.filter(city='delhi').get(mtc_name=rj) # Add/Reset details of the route new_route.display_name = rj new_route.city = 'delhi' new_route.mtc_name = rj new_route.types = "O" #FIXME: Classify routes under appropriate types new_route.fare = -1 #TODO: Scrape fare data new_route.time = -1 #TODO: Scrape time data new_route.slug = slugify(rj) # Add new/existing stage object as route's start stage try: sstage = rjs[rj][0] ssobj = Stage.objects.filter(city='delhi').get(mtc_name=sstage) except Stage.DoesNotExist: ssobj = Stage() ssobj.mtc_name = sstage ssobj.display_name = sstage ssobj.city = 'delhi' ssobj.save() new_route.start = ssobj # Add new/existing stage object as route's end stage try: estage = rjs[rj][-1] esobj = Stage.objects.filter(city='delhi').get(mtc_name=estage) except Stage.DoesNotExist: esobj = Stage() esobj.mtc_name = estage esobj.display_name = estage esobj.city = 'delhi' esobj.save() new_route.end = esobj # Save the route new_route.save() # Add RouteStage object for every stage in route sequence = 100 for stage in rjs[rj]: # Get or create stage object try: sobj = Stage.objects.filter(city='delhi').get(mtc_name=stage) except Stage.DoesNotExist: sobj = Stage() sobj.mtc_name = stage sobj.display_name = stage sobj.city = 'delhi' sobj.save() # Get or create RouteStage object try: rs = RouteStage.objects.filter(route=new_route).get( stage__display_name=stage) except RouteStage.DoesNotExist: rs = RouteStage() rs = RouteStage() rs.route = new_route rs.stage = sobj rs.sequence = sequence rs.save() # Increment sequence of stage sequence += 100
def _migrate(self): # Drop all tables print('Dropping tables...') auth.models.User.objects.all().delete() Administrator.objects.all().delete() User.objects.all().delete() Folder.objects.all().delete() Message.objects.all().delete() Announcement.objects.all().delete() ApplyAnnouncement.objects.all().delete() ApplyRoute.objects.all().delete() Comment.objects.all().delete() CommentAnnouncement.objects.all().delete() CommentRoute.objects.all().delete() Day.objects.all().delete() Route.objects.all().delete() StopAnnouncement.objects.all().delete() StopRoute.objects.all().delete() print("Dropping tables OK!") print('Create administrators accounts...') admin1 = auth.models.User.objects.create_superuser(username='******', email='*****@*****.**', password='******') print('Create administrators accounts OK!') print('Create users accounts...') user_account1 = auth.models.User.objects.create_user(username='******', email='*****@*****.**', password='******') user_account2 = auth.models.User.objects.create_user(username='******', email='*****@*****.**', password='******') print('Create users accounts OK!') print('Create administrators...') administrator = Administrator(user_account = admin1) administrator.save() print('Create administrators OK!') print('Create users...') user1 = User(user_account = user_account1,name = "Nombre", surnames = "Apellido1 Apellido2", city = "Sevilla", birthdate = date(1993, 4, 6), phone = "666999888",searchingCar = True) user1.save() user2 = User(user_account = user_account2,name = "Nombre2", surnames = "Apellido1 Apellido2", city = "Sevilla", birthdate = date(1993, 4, 6), phone = "666999888",searchingCar = True) user2.save() print('Create user OK!') print('Create folders...') folder1 = Folder(name = "1", actor = user1) folder1.save() folder2 = Folder(name = "2", actor = user1) folder2.save() folder3 = Folder(name = "3", actor = user1) folder3.save() folder4 = Folder(name = "1", actor = user2) folder4.save() folder5 = Folder(name = "2", actor = user2) folder5.save() folder6 = Folder(name = "3", actor = user2) folder6.save() folder7 = Folder(name = "1", actor = administrator) folder7.save() folder8 = Folder(name = "2", actor = administrator) folder8.save() folder9 = Folder(name = "3", actor = administrator) folder9.save() print('Create folders OK!') print('Create messages...') message1 = Message(subject = "Asunto 1", body = "Este es un mensaje de prueba enviado", folder = folder1, sender = user1, recipient = user2) message1.save() message2 = Message(subject = "Asunto 1", body = "Este es un mensaje de prueba enviado", folder = folder5, sender = user1, recipient = user2) message2.save() print('Create messages OK!') print('Create comments...') comment1 = Comment(subject = "Muy bueno", comment = "Muy buen conductor, totalmente recomendable", rating = 9, referrer = user1, evaluated = user2) comment1.save() comment2 = Comment(subject = "Regular", comment = "Como pasajero deja mucho que desear", rating = 4, referrer = user2, evaluated = user1) comment2.save() print('Create comments OK!') print('Create routes...') route1 = Route(origin = "Alcalá de Guadaíra", destination = "Facultad de Informática", description = "Viaje regular durante 3 meses", kind = "1", seating = 4, unitPrice = 2.00, user = user2) route1.save() route2 = Route(origin = "Arahal", destination = "Isla de la cartuja", description = "Viaje regular durante 6 meses", kind = "1", seating = 4, unitPrice = 2.00, user = user1) route2.save() print('Create routes OK!') print('Create stop routes...') stopRoute1 = StopRoute(stop = "Alcalá de Guadaíra", sequence = 1, route = route2) stopRoute1.save() print('Create stop routes OK!') print('Create days...') day1 = Day(day = 1, departTime = "7:55", returnTime = "14:00", route = route2, active = True) day1.save() day2 = Day(day = 2, departTime = "7:55", returnTime = "14:00", route = route2, active = True) day2.save() day3 = Day(day = 3, departTime = "7:55", returnTime = "14:00", route = route2, active = True) day3.save() day4 = Day(day = 4, departTime = "7:55", returnTime = "14:00", route = route2, active = True) day4.save() day5 = Day(day = 5, departTime = "7:55", returnTime = "14:00", route = route2, active = True) day5.save() day6 = Day(day = 6, route = route2, active = False) day6.save() day7 = Day(day = 7, route = route2, active = False) day7.save() day8 = Day(day = 1, departTime = "7:55", returnTime = "14:00", route = route1, active = True) day8.save() day9 = Day(day = 2, departTime = "7:55", returnTime = "14:00", route = route1, active = True) day9.save() day10 = Day(day = 3, departTime = "7:55", returnTime = "14:00", route = route1, active = True) day10.save() day11 = Day(day = 4, departTime = "7:55", returnTime = "14:00", route = route1, active = True) day11.save() day12 = Day(day = 5, departTime = "7:55", returnTime = "14:00", route = route1, active = True) day12.save() day13 = Day(day = 6, route = route1, active = False) day13.save() day14 = Day(day = 7, route = route1, active = False) day14.save() print('Create days OK!') print('Create applys routes...') applyRoute1 = ApplyRoute(comment = "Buenas, yo entro a las 9 de la mañana y salgo a las dos, te viene bien en Alcalá de Guadaíra?", route= route2, user = user1) applyRoute1.save() print('Create applys routes OK!') print('Create comments routes...') commentRoute1 = CommentRoute(subject = "Buena ruta!", comment = "Muy buen trayecto, excelente conductor", rating = 10, user = user1, route = route2) commentRoute1.save() print('Create comments routes OK!') print('Create announcements ...') announcement1 = Announcement(origin = "Alcalá de Guadaíra", destination = "Facultad de informática", description = "Viaje puntual" , seating = 2, unitPrice = 2, date = datetime(2015, 12, 6, 16, 29, 43, 79043), user = user1) announcement1.save() print('Create announcements OK!') print('Create applys announcements...') applyAnnouncement1 = ApplyAnnouncement(comment = "Buenas, yo entro a las 17:00 de la tarde te viene bien los arcos?", announcement=announcement1, user=user1) applyAnnouncement1.save() print('Create applys announcements OK!') print('Create stops announcements...') stopAnnouncement1 = StopAnnouncement(stop = "Sevilla", sequence = 1, announcement = announcement1) stopAnnouncement1.save() print('Create stops announcements OK!') print('Create comments announcements...') commentAnnouncement1 = CommentAnnouncement(subject = "Buena ruta!", comment = "Muy buen trayecto, excelente conductor", rating = 10, user = user1, announcement = announcement1) commentAnnouncement1.save() print('Create comments announcements OK!')
def main(): rjs = json.load(open('routes_detail.json', 'r')) from routes.models import Route, RouteStage from stages.models import Stage # For every route number in the dictionary for rj in rjs: # if the route is present already, edit it if not Route.objects.filter(city='delhi').filter(mtc_name=rj): new_route = Route() else: new_route = Route.objects.filter(city='delhi').get(mtc_name=rj) # Add/Reset details of the route new_route.display_name = rj new_route.city = 'delhi' new_route.mtc_name = rj new_route.types = "O" #FIXME: Classify routes under appropriate types new_route.fare = -1 #TODO: Scrape fare data new_route.time = -1 #TODO: Scrape time data new_route.slug = slugify(rj) # Add new/existing stage object as route's start stage try: sstage = rjs[rj][0] ssobj = Stage.objects.filter(city='delhi').get(mtc_name=sstage) except Stage.DoesNotExist: ssobj = Stage() ssobj.mtc_name = sstage ssobj.display_name = sstage ssobj.city = 'delhi' ssobj.save() new_route.start = ssobj # Add new/existing stage object as route's end stage try: estage = rjs[rj][-1] esobj = Stage.objects.filter(city='delhi').get(mtc_name=estage) except Stage.DoesNotExist: esobj = Stage() esobj.mtc_name = estage esobj.display_name = estage esobj.city = 'delhi' esobj.save() new_route.end = esobj # Save the route new_route.save() # Add RouteStage object for every stage in route sequence = 100 for stage in rjs[rj]: # Get or create stage object try: sobj = Stage.objects.filter(city='delhi').get(mtc_name=stage) except Stage.DoesNotExist: sobj = Stage() sobj.mtc_name = stage sobj.display_name = stage sobj.city = 'delhi' sobj.save() # Get or create RouteStage object try: rs = RouteStage.objects.filter(route=new_route).get(stage__display_name=stage) except RouteStage.DoesNotExist: rs = RouteStage() rs = RouteStage() rs.route = new_route rs.stage = sobj rs.sequence = sequence rs.save() # Increment sequence of stage sequence += 100
def main(): rds = json.load(open('routes_detail.json', 'r')) from routes.models import Route, RouteStage, ROUTE_TYPE_MAPPING from stages.models import Stage for r in Route.objects.filter(city=CITY): r.city = CITY + '_old' r.save() # For every route number in the dictionary for mtc_name in rds: display_name, slug = resolve_route_name(mtc_name) rd = rds[mtc_name] if rd["source"] is None or rd["destination"] is None or len(rd["stages"]) == 0: #print "Route %s skipped (Reason: Incomplete)" % mtc_name continue # Skipping Incomplete routes service_type = rd["service_type"] s_type = MTC_TYPE_REVERSE_MAP[service_type] # if the route is present already, edit it if not Route.objects.filter(city=CITY).filter(slug=slug): r = Route() else: r = Route.objects.filter(city=CITY).get(slug=slug) # Add/Reset details of the route r.display_name = display_name r.city = CITY r.mtc_name = mtc_name if r.types is None or r.types == "": r.types = s_type elif s_type not in r.types.split(','): r.types = r.types + "," + s_type r.fare = -1 #TODO: Remove fare data r.time = -1 #TODO: Remove time data r.slug = slugify(slug) # Add new/existing stage object as route's start stage sstage = rd["source"] try: ssobj = Stage.objects.get(city=CITY, mtc_name = sstage) except Stage.DoesNotExist: ssobj = Stage() ssobj.display_name = sstage.title() ssobj.city = CITY ssobj.mtc_name = sstage ssobj.save() r.start = ssobj # Add new/existing stage object as route's end stage estage = rd["destination"] try: esobj = Stage.objects.get(city=CITY, mtc_name = estage) except Stage.DoesNotExist: esobj = Stage() esobj.display_name = estage.title() esobj.city = CITY esobj.mtc_name = estage esobj.save() r.end = esobj # Save the route r.save() # Add RouteStage object for every stage in route sequence = 100 for stage in rd["stages"]: # Get or create stage object try: sobj = Stage.objects.get(city=CITY, mtc_name = stage) except Stage.DoesNotExist: sobj = Stage() sobj.display_name = stage.title() sobj.city = CITY sobj.mtc_name = stage sobj.save() # Get or create RouteStage object try: rs = RouteStage.objects.filter(route=r).get(stage=sobj) except RouteStage.DoesNotExist: rs = RouteStage() rs.route = r rs.stage = sobj rs.sequence = sequence rs.save() # Increment sequence of stage sequence += 100
def main(): rds = json.load(open('routes_detail.json', 'r')) from routes.models import Route, RouteStage, ROUTE_TYPE_MAPPING from stages.models import Stage for r in Route.objects.filter(city=CITY): r.city = CITY + '_old' r.save() # For every route number in the dictionary for mtc_name in rds: display_name, slug = resolve_route_name(mtc_name) rd = rds[mtc_name] if rd["source"] is None or rd["destination"] is None or len( rd["stages"]) == 0: #print "Route %s skipped (Reason: Incomplete)" % mtc_name continue # Skipping Incomplete routes service_type = rd["service_type"] s_type = MTC_TYPE_REVERSE_MAP[service_type] # if the route is present already, edit it if not Route.objects.filter(city=CITY).filter(slug=slug): r = Route() else: r = Route.objects.filter(city=CITY).get(slug=slug) # Add/Reset details of the route r.display_name = display_name r.city = CITY r.mtc_name = mtc_name if r.types is None or r.types == "": r.types = s_type elif s_type not in r.types.split(','): r.types = r.types + "," + s_type r.fare = -1 #TODO: Remove fare data r.time = -1 #TODO: Remove time data r.slug = slugify(slug) # Add new/existing stage object as route's start stage sstage = rd["source"] try: ssobj = Stage.objects.get(city=CITY, mtc_name=sstage) except Stage.DoesNotExist: ssobj = Stage() ssobj.display_name = sstage.title() ssobj.city = CITY ssobj.mtc_name = sstage ssobj.save() r.start = ssobj # Add new/existing stage object as route's end stage estage = rd["destination"] try: esobj = Stage.objects.get(city=CITY, mtc_name=estage) except Stage.DoesNotExist: esobj = Stage() esobj.display_name = estage.title() esobj.city = CITY esobj.mtc_name = estage esobj.save() r.end = esobj # Save the route r.save() # Add RouteStage object for every stage in route sequence = 100 for stage in rd["stages"]: # Get or create stage object try: sobj = Stage.objects.get(city=CITY, mtc_name=stage) except Stage.DoesNotExist: sobj = Stage() sobj.display_name = stage.title() sobj.city = CITY sobj.mtc_name = stage sobj.save() # Get or create RouteStage object try: rs = RouteStage.objects.filter(route=r).get(stage=sobj) except RouteStage.DoesNotExist: rs = RouteStage() rs.route = r rs.stage = sobj rs.sequence = sequence rs.save() # Increment sequence of stage sequence += 100
def index(request): #get request routeDict = {} if request.method == 'GET': allTbas = Tba.objects.all() allRoutes = Route.objects.all() for tba in allTbas: cluster = tba.route.cluster route = tba.route.route if routeDict.get(cluster) == None: routeDict[cluster] = {'count': 0, 'routes': {}} if routeDict[cluster]['routes'].get(route) == None: routeDict[cluster]['routes'][route] = {'count': 0, 'tbas': []} routeDict[cluster]['count'] += 1 routeDict[cluster]['routes'][route]['tbas'].append(tba) routeDict[cluster]['routes'][route]['count'] += 1 for cluster in routeDict: routes = routeDict[cluster]['routes'] for route in routes: count = routes[route]['count'] r = Route.objects.get(route=route) r.tbaCount = count r.save(update_fields=['tbaCount']) return render(request, 'routes/index.html', {'routeDict': routeDict}) else: return redirect('../') #post requeest if request.method == 'POST': cj = request.COOKIES tbas = request.POST.get('tbas') searchForm = sessionHelper.searchForm searchForm['shipmentSearchIds'] = tbas data = sessionHelper.getTbasFromComp(cj, searchForm) tbaCount = 0 routeCount = 0 tbaTotal = 0 print data existArray = [] noRouteArray = [] for item in data: tba = item['tba'] route = item['route'] try: r = Route.objects.get(route=route) except ObjectDoesNotExist: if route != "": cluster = filter(lambda x: x.isalpha(), route) routeCount += 1 r = Route(route=route, cluster=cluster) r.save() try: tba = Tba.objects.get(tba=tba) except ObjectDoesNotExist: tbaCount += 1 tbaTotal += 1 route = item['route'] r = Route.objects.get(route=route) status = item['status'] link = item['link'] address = item['address'] tba = Tba(route=r, tba=tba, status=status, link=link, address=address) tba.save() else: tbaTotal += 1 existArray.append(tba.tba) existArrayLength = len(existArray) allRoutes = Route.objects.all() message = { 'tbaCount': tbaCount, 'tbaTotal': tbaTotal, 'existArray': existArray, 'existArrayLength': existArrayLength, 'routeCount': routeCount } return render(request, 'routes/index.html', { 'message': message, 'allRoutes': allRoutes })
def home_view(request): #Make sure the user is logged in if request.user.is_authenticated(): #get all the rides that their apart of as a passenger user = User.objects.get(username=request.session['username']) rider = Users.objects.get(user=user) #Explination of whats going on here: In order to allow a person to remove themselves from a ride # we need to have the id of the ride they belong to as well as the id of the Users trip (Waypoint id) acceptedRideIDs =[] waypointName = [] ridersTripId = [] acceptedRides = Trip.objects.filter(acceptedPassengers__user__id__exact=rider.id, active=True) for x in acceptedRides: #This will append the id of the ride to the acceotedRideIDs list acceptedRideIDs.append(x.id) for y in x.acceptedPassengers.all(): #This will append the riders tripId and the waypoint name for easy viewing in the template ridersTripId.append(y.id) waypointName.append(y.waypoint.title) #This will combine the three lists above into one list. This needs to be done because in the django template # system there is no way to iterate over multiple lists in one pass like there is in regular python lst = [{'waypointName':t[0],'acceptedRides': t[1], 'id':t[2]} for t in zip(waypointName,acceptedRideIDs, ridersTripId)] #get all rides that their still pending on as a passenger pendingRides = Trip.objects.filter(pendingPassengers__user__id__exact=rider.id, active=True) #This gets all available rides exlcluding the user from being an acceptedPassenger, pendingPassenger or host # Basically any ride they have nothing to do with allRides = Trip.objects.filter(host__university=rider.university, active=True).exclude(acceptedPassengers__user__id__exact=rider.id).exclude(pendingPassengers__user__id__exact=rider.id).exclude(host=rider) #All the rides that the user is hosting HostedRides = Trip.objects.filter(host=rider, active=True) #Check to see if they've added a new ride. #The ride information is all going to be created client side # with javascript. We will be recieving the following information about # the trip, Start Address, Start Zip, End Address, End Zip, Duration, # Miles, and free seats if request.method =='POST': form = tripForm(request.POST) if form.is_valid(): #The trip information startAddress = form.cleaned_data['startAddress'] startZip = form.cleaned_data['startZip'] endAddress = form.cleaned_data['endAddress'] endZip = form.cleaned_data['endZip'] leavingDate = form.cleaned_data['leavingDate'] public = form.cleaned_data['public'] customEndpoints = form.cleaned_data['customEndpoints'] #Car information freeSeats = form.cleaned_data['freeSeats'] host = User.objects.get(username=request.session['username']) host = Users.objects.get(user=host) host.car = Car.objects.get(seats=int(freeSeats)) host.save() latStart, lngStart = ziptrailUtils.getGeocode(startAddress, startZip) latEnd, lngEnd = ziptrailUtils.getGeocode(endAddress, endZip) if latStart and lngStart and latEnd and lngEnd: startLatLong, createdStart = Position.objects.get_or_create(latitude=latStart, longitude=lngStart) endLatLong, createdEnd = Position.objects.get_or_create(latitude=latEnd, longitude=lngEnd) #calculate the total miles dist = getDistance(latStart, lngStart, latEnd, lngEnd) gas = dist/16 route = Route(startAddress=startAddress, startZip=ZipCode.objects.get(zip=startZip), startLat_Long=startLatLong, endAddress=endAddress, endZip=ZipCode.objects.get(zip=endZip), endLat_Long=endLatLong, totalMiles=dist, gallonsGas=gas) route.save() #Create a new Trip, newRide = Trip(host=host, trip=route, public=public, customEndpoints=customEndpoints) newRide.save() return HttpResponseRedirect(settings.BASE_URL + '/rides/home') else: return HttpResponse('Couldn\'t geocode') user = User.objects.get(username=request.session['username']) user = Users.objects.get(user=user) badges = getBadges(request) form = tripForm() return direct_to_template(request, 'home.html', { 'rides' : acceptedRides, 'form' : form, 'availableRides' : allRides, 'hostedRides' : HostedRides, 'userInfo': user, 'lst' : lst, 'badges' : badges }) else: form = loginForm() return direct_to_template(request, 'login.html', { 'form' : form })
def index(request): #get request if request.method == 'GET': #sort route with tbas allTbas = Tba.objects.all() allRoutes = Route.objects.all() clusterCount = {} routeCount = {} for route in allRoutes: if route.cluster not in clusterCount: clusterCount[route.cluster] = 1 else: clusterCount[route.cluster] += 1 for tba in allTbas: if tba.route not in routeCount: routeCount[tba.route] = 1 else: routeCount[tba.route] += 1 for route, count in routeCount.items(): if route.isSplit == False and route.isUnplanned == False: r = Route.objects.get(route=route.route) r.tbaCount = count r.save(update_fields=['tbaCount']) return render( request, 'routes/index.html', { 'clusterCount': clusterCount, 'routeCount': routeCount, 'allTbas': allTbas, 'allRoutes': allRoutes }) #post request if request.method == 'POST': tbas = request.POST.get('tbas') existArray = [] noRouteArray = [] for item in data: tba = item['tba'] route = item['route'] try: r = Route.objects.get(route=route) except ObjectDoesNotExist: if route != "": cluster = filter(lambda x: x.isalpha(), route) routeCount += 1 r = Route(route=route, cluster=cluster) r.save() try: tba = Tba.objects.get(tba=tba) except ObjectDoesNotExist: tbaCount += 1 tbaTotal += 1 route = item['route'] r = Route.objects.get(route=route) status = item['status'] link = item['link'] address = item['address'] tba = Tba(route=r, tba=tba, status=status, link=link, address=address) tba.save() else: tbaTotal += 1 existArray.append(tba.tba) existArrayLength = len(existArray) allRoutes = Route.objects.all() message = { 'tbaCount': tbaCount, 'tbaTotal': tbaTotal, 'existArray': existArray, 'existArrayLength': existArrayLength, 'routeCount': routeCount } return render(request, 'routes/index.html', { 'message': message, 'allRoutes': allRoutes })
def tbas(request): if request.method == 'GET': data = serializers.serialize("json", Tba.objects.all()) return HttpResponse(data, content_type='application/json') if request.method == 'POST': req = json.loads(request.body) for item in req: tba = item['tba'] link = item['link'] status = item['status'] city = item['city'] zipCode = item['zipCode'] route = item['route'] associate = item['associate'] sortZone = item['sortZone'] address = item['address'] if route != "" or route != None: try: Route.objects.get(route=route) except ObjectDoesNotExist: cluster = filter(lambda x: x.isalpha(), route) aRoute = Route( route=route, cluster = cluster, tbaCount = 0 ) aRoute.save() try: Tba.objects.get(tba=tba) except ObjectDoesNotExist: routeToUpdate = Route.objects.get(route=route) tba = Tba( tba=tba, link=link, status=status, city=city, route=routeToUpdate, zipCode=zipCode, sortZone=sortZone, address=address ) tba.save() else: tba = Tba( tba=tba, link=link, status=status, city=city, zipCode=zipCode, sortZone=sortZone, address=address ) tba.save() #tbaCount is updated in route app fyi return HttpResponse("Tbas were saved successfully!!")