示例#1
0
    def test_endpoint_listing_origin_and_destiny(self):
        loc1, loc2, loc3 = baker.make(Location, 3)
        baker.make(Driver, origin=loc1, destiny=loc2,
                   vehicle_type=VehicleType.CAMINHAO_TOCO.value)
        baker.make(Driver, origin=loc1, destiny=loc3,
                   vehicle_type=VehicleType.CAMINHAO_TRUCK.value)
        baker.make(Driver, origin=loc3, destiny=loc2,
                   vehicle_type=VehicleType.CARRETA_SIMPLES.value)

        response = self.client.get(ORIGINS_AND_DESTINYS_URL)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        for vehicle_type in VehicleType:
            self.assertIn(vehicle_type.name, response.data)

        self.assertIn(
            LocationSerializer(loc1).data,
            response.data[VehicleType.CAMINHAO_TOCO.name]
        )
        self.assertIn(
            LocationSerializer(loc1).data,
            response.data[VehicleType.CAMINHAO_TRUCK.name]
        )
        self.assertIn(
            LocationSerializer(loc3).data,
            response.data[VehicleType.CARRETA_SIMPLES.name]
        )
示例#2
0
文件: views.py 项目: CMUJIN/meetup
def update_location(request):
    serializer = LocationSerializer(data=request.DATA)
    json_response = simplejson.loads(JSONRenderer().render(serializer.data))
    location = get_location(json_response['user_id'])
    if location != None:
        serializer = LocationSerializer(location, data=request.DATA)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
示例#3
0
def account_create(request):
    """
    Creates a new Account and saves it in the database.

    Args:
            request (Request): An object containing data needed to create a new Account.

    Returns:
            Reponse: An HTTP response indicating that the new Account was successfully saved in the database or that there
            was an error and the Account object was not created.
    """
    data = request.data
    if 'loc' in data:
        loc_data = data.pop('loc')
        if type(
                loc_data
        ) == dict:  # If we've got a dict, that means the Location object should be created from the lat/lng
            loc_serializer = LocationSerializer(data=loc_data)
            if loc_serializer.is_valid():
                loc_obj = loc_serializer.save()
                data['cur_loc'] = loc_obj.loc_id
            else:
                return Response(
                    {
                        'STATUS': '1',
                        'REASON': 'LOCATION SERIALIZER ERROR',
                        'ERRORS': {
                            **loc_serializer.errors
                        }
                    },
                    status=status.HTTP_400_BAD_REQUEST)
        else:  # For testing purposes, don't create a Location object but just toss in an existing primary key
            data['cur_loc'] = loc_data
    acc_serializer = AccountSerializer(data=data)
    if acc_serializer.is_valid():
        acc_obj = acc_serializer.save()
        return Response(
            {
                'STATUS': '0',
                'REASON': 'SUCCESSFULLY CREATED ACCOUNT OBJECT',
                'user_id': acc_obj.user_id
            },
            status=status.HTTP_200_OK)
    else:
        return Response(
            {
                'STATUS': '1',
                'REASON': 'ACCOUNT SERIALIZER ERROR',
                'ERRORS': {
                    **acc_serializer.errors
                }
            },
            status=status.HTTP_400_BAD_REQUEST)
示例#4
0
 def post(self, request):
     print("inside vote", request.data)
     g = Group.objects.get(
         groupName=bleach.clean(request.data.get('groupname')))
     locationname = bleach.clean(request.data.get('locationname'))
     location = Location.objects.get(group=g, locationName=locationname)
     location.vote = location.vote + 1
     location.save()
     print("vote api ", location)
     serializer = LocationSerializer(location)
     print(serializer.data)
     # jsonRes = serializers.serialize('json',location)
     return Response({'location': serializer.data})
示例#5
0
def location_list(request):
    if request.method == 'GET':
        locations = Location.objects.all()
        serializer = LocationSerializer(locations, many=True)
        return JSONResponse(serializer.data)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = LocationSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)
示例#6
0
    def list(self, request, *args, **kwargs):
        truck_types_dict = {}
        for vehicle_type in VehicleType:
            truck_types_dict[vehicle_type.name] = set()

        for driver in Driver.objects.all():
            driver_truck_type_name = VehicleType(driver.vehicle_type).name
            truck_types_dict[driver_truck_type_name].add(driver.origin)
            truck_types_dict[driver_truck_type_name].add(driver.destiny)

        response_data = {
            truck_type: LocationSerializer(locations, many=True).data
            for truck_type, locations in truck_types_dict.items()
        }

        return Response(response_data)
示例#7
0
def nearby_locations(request):
    if not request.method == 'GET':
        return HttpResponse(status=404)

    # Radius in meters
    radius = request.GET.get('radius', 1000)
    lat = request.GET.get('latitude')
    lon = request.GET.get('longitude')

    if not (lat and lon):
        return HttpResponse(status=422)

    query = Location.objects.in_distance(int(radius),
                                         fields=['latitude', 'longitude'],
                                         points=[float(lat),
                                                 float(lon)])
    return JSONResponse(LocationSerializer(query.all(), many=True).data)
示例#8
0
def location_detail(request, pk):
    try:
        location = Location.objects.get(pk=pk)
    except Location.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        serializer = LocationSerializer(location)
        return JSONResponse(serializer.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = LocationSerializer(location, data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)
        return JSONResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        location.delete()
        return HttpResponse(status=204)
 def create(self, request, organization):
     serializer = LocationSerializer(data=request.data)
     return save_serializer_with_organization(serializer, organization)
示例#10
0
    def test_location_serializer_create_object(self):
        json_payload = """
            {
                "uprn": "123456789AB",
                "ba_ref": "468765672358",
                "name": "St James C E Secondary School (10910)",
                "authority": "Bolton",
                "owner": "Test owner",
                "unique_asset_id": "10910",
                "full_address": "Full address of St James School",
                "estimated_floor_space": 140.24,
                "geom": {
                    "type": "MultiPolygon",
                    "coordinates": [
                    [
                        [
                        [
                            -2.1614837256814963,
                            53.07183331520438
                        ],
                        [
                            -2.161440204004493,
                            53.07167876512527
                        ],
                        [
                            -2.161426422046515,
                            53.07158231050548
                        ],
                        [
                            -2.161412261861244,
                            53.07128283205548
                        ],
                        [
                            -2.161373377871479,
                            53.071211109880664
                        ],
                        [
                            -2.161369504865456,
                            53.07118401041043
                        ],
                        [
                            -2.1617677327485008,
                            53.07111245525075
                        ],
                        [
                            -2.1617682739467705,
                            53.071109120469266
                        ],
                        [
                            -2.1620568237599738,
                            53.07147709017702
                        ],
                        [
                            -2.162246918923053,
                            53.07170561414385
                        ],
                        [
                            -2.162193868651531,
                            53.07171503969784
                        ],
                        [
                            -2.162142294698858,
                            53.07172373689699
                        ],
                        [
                            -2.1621361236605248,
                            53.07171871503741
                        ],
                        [
                            -2.1614837256814963,
                            53.07183331520438
                        ]
                        ]
                    ]
                    ]
                },
                "srid": 4326
            }
        """

        data = json.loads(json_payload)
        serializer = LocationSerializer(data=data)
        self.assertTrue(serializer.is_valid())

        serializer.save()
        self.assertEqual(Location.objects.count(), 1)
示例#11
0
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
示例#12
0
def account_update(request):
    """
    Updates the information in an existing Account within the database.

    Args:
        request (Request): An object containing the new data to be placed into the Account object.

    Returns:
        Response: An HTTP response that indicates whether the Account was successfully updated or if there was an error.
    """

    data = request.data
    if 'email' not in data:
        return Response(
            {
                'STATUS': '1',
                'REASON': 'MISSING REQUIRED EMAIL ARGUMENT'
            },
            status=status.HTTP_400_BAD_REQUEST)
    try:
        acc_obj = Account.objects.get(email=data['email'])
    except Account.DoesNotExist:
        return Response(
            {
                'STATUS': '1',
                'REASON': 'NO ACCOUNT EXISTS WITH GIVEN USER_ID'
            },
            status=status.HTTP_400_BAD_REQUEST)
    if 'loc' in data:
        loc_data = data.pop('loc')
        loc_serializer = LocationSerializer(acc_obj.cur_loc, data=loc_data)
        if loc_serializer.is_valid():
            loc_obj = loc_serializer.save()
            if acc_obj.cur_loc is None:  # Since location is optional on registration, we might need to assign a location ID if it's null in the existing object
                data['cur_loc'] = loc_obj.loc_id
        else:
            return Response(
                {
                    'STATUS': '1',
                    'REASON': 'LOCATION SERIALIZER ERROR',
                    'ERRORS': {
                        **loc_serializer.errors
                    }
                },
                status=status.HTTP_400_BAD_REQUEST)
    acc_serializer = AccountSerializer(acc_obj, data=data, partial=True)
    if acc_serializer.is_valid():
        acc_serializer.save()
        return Response(
            {
                'STATUS': '0',
                'REASON': 'SUCCESSFULLY UPDATED ACCOUNT'
            },
            status=status.HTTP_200_OK)
    return Response(
        {
            'STATUS': '1',
            'REASON': 'ACCOUNT SERIALIZER ERROR',
            'ERRORS': {
                **acc_serializer.errors
            }
        },
        status=status.HTTP_400_BAD_REQUEST)
示例#13
0
def account_updatelocation(request):
    """
    Updates the location associated with an account.

    Args:
        request (Request): The HTTP Request containing the user_id and lat/lng field that needs to be updated.

    Returns:
        Reponse: The reponse denoting success or failure of the update.
    """

    data = request.data
    if 'user_id' not in data:
        return Response(
            {
                'STATUS': '1',
                'REASON': 'MISSING REQUIRED USER_ID ARGUMENT'
            },
            status=status.HTTP_400_BAD_REQUEST)
    if 'lat' not in data or 'lng' not in data:
        return Response(
            {
                'STATUS': '1',
                'REASON': 'MISSING REQUIRED LAT/LNG ARGUMENTS'
            },
            status=status.HTTP_400_BAD_REQUEST)
    try:
        acc_obj = Account.objects.get(user_id=data['user_id'])
        # No partial=True since we always need to specify a full location
        loc_serializer = LocationSerializer(acc_obj.cur_loc, data=data)
        if loc_serializer.is_valid():
            loc_obj = loc_serializer.save()
            # No location currently associated with account [either never existed or nothing currently there], assign the two together
            if acc_obj.cur_loc is None:
                acc_serializer = AccountSerializer(
                    acc_obj, data={'cur_loc': loc_obj.loc_id}, partial=True)
                if acc_serializer.is_valid():
                    acc_serializer.save()
                else:
                    return Response(
                        {
                            'STATUS': '1',
                            'REASON': 'ACCOUNT SERIALIZER ERROR',
                            'ERRORS': {
                                **acc_serializer.errors
                            }
                        },
                        status=status.HTTP_400_BAD_REQUEST)
            return Response(
                {
                    'STATUS': '0',
                    'REASON': 'ACCOUNT LOCATION SUCCESSFULLY UPDATED'
                },
                status=status.HTTP_200_OK)
        else:
            return Response(
                {
                    'STATUS': '1',
                    'REASON': 'LOCATION SERIALIZER ERROR',
                    'ERRORS': {
                        **loc_serializer.errors
                    }
                },
                status=status.HTTP_400_BAD_REQUEST)
    except Account.DoesNotExist:
        return Response(
            {
                'STATUS': '1',
                'REASON': 'NO ACCOUNT EXISTS WITH GIVEN USER_ID'
            },
            status=status.HTTP_400_BAD_REQUEST)