def people_detail_view(request, people_id): """ People `detail` actions: Based on the request method, perform the following actions: * GET: Returns the `People` object with given `people_id`. * PUT/PATCH: Updates the `People` object either partially (PATCH) or completely (PUT) using the submitted JSON payload. * DELETE: Deletes `People` object with given `people_id`. Make sure you add at least these validations: * If the view receives another HTTP method out of the ones listed above, return a `400` response. * If submited payload is not JSON valid, return a `400` response. """ if request.body: try: payload = json.loads(request.body.decode()) except: return JsonResponse({'error': True, 'msg': 'Invalid JSON payload'}, status = 400) try: person = People.objects.get(id=people_id) except People.DoesNotExist: return JsonResponse({'error': True, 'msg': 'Person does not exist'}, status = 400) if request.method == 'GET': data = serialize_people_as_json(person) status = 200 elif request.method in ['PUT', 'PATCH']: for field in payload: setattr(person, field, payload[field]) data = serialize_people_as_json(person) status = 200 elif request.method == 'DELETE': deleted = People.objects.get(id=people_id).delete() deleted.append({'error': False, 'msg': 'Successfully deleted.'}) data = deleted status = 200 else: data = {'error': True, 'message': 'HTTP method must be GET or POST.'} status = 400 return JsonResponse(data=data, status=status, safe=False)
def people_list_view(request): """ People `list` actions: Based on the request method, perform the following actions: * GET: Return the list of all `People` objects in the database. * POST: Create a new `People` object using the submitted JSON payload. Make sure you add at least these validations: * If the view receives another HTTP method out of the ones listed above, return a `400` response. * If submited payload is not JSON valid, return a `400` response. """ if request.method == 'GET': try: people = [serialize_people_as_json(person) for person in People.objects.all()] except: return JsonResponse({ 'error': True, 'msg': 'Error. Please try again.' }, status = 400) data = people status = 200 elif request.method == 'POST': try: payload = json.loads(request.body.decode()) person = People.objects.create( name = payload['name'], homeworld = Planet.objects.get(id=payload['homeworld']), height = payload['height'], mass = payload['mass'], hair_color = payload['hair_color'] ) except: return JsonResponse({ 'error': True, 'msg': 'Error creating person. Please try again.' }, status = 400) data = serialize_people_as_json(person) status = 201 else: data = {'error': True, 'msg': 'HTTP method must be GET or POST.'} status = 400 return JsonResponse(data, status=status, safe=False)
def get(self, request, *args, **kwargs): people_id = kwargs.get('people_id') if people_id: people = self._get_object(people_id) if not people: return JsonResponse({"GET": "Failed", "Problem": "Person not found."}, status=404) data = serialize_people_as_json(people) return JsonResponse(data, status=200, safe=False)
def get(self, *arg, **kwargs): people_id = kwargs.get('people_id') if people_id: people = self._get_object(people_id) if not people: return JsonResponse( { "success": False, "msg": "Could not find people with id: {}".format(people_id) }, status=404) data = serialize_people_as_json(people) else: qs = People.objects.select_related('homeworld').all() data = [serialize_people_as_json(people) for people in qs] return JsonResponse(data, status=200, safe=False)
def _update(self, people, payload, partial=False): for field in ['name', 'homeworld', 'height', 'mass', 'hair_color']: if not field in payload: if partial: continue return JsonResponse({"Update": "Failed", "Problem": "Missing field for full update."}, status=400) try: if field is 'homeworld': payload[field] = Planet.objects.get(pk=payload[field]) setattr(people, field, payload[field]) people.save() except ValueError: return JsonResponse({"Update": "Failed", "Problem": "Provided payload isn't valid."}, status=400) data = serialize_people_as_json(people) return JsonResponse(data, status=200, safe=False)
def post(self, *arg, **kwargs): if 'people_id' in kwargs: return JsonResponse( { "success": False, "msg": "Invalid HTTP request" }, status=400) try: payload = json.loads(self.request.body.decode('utf-8')) except ValueError: return JsonResponse( { "success": False, "msg": "Provide a valid JSON payload" }, status=400) planet_id = payload.get('homeworld', None) try: planet = Planet.objects.get(id=planet_id) # we can do payload['homeworld'] = Planet.objects.get(id=planet_id) # and pass **payload to People.objects.create(**payload) except Planet.DoesNotExist: return JsonResponse( { "success": False, "msg": "Could not find planet with id {}".format(planet_id) }, status=404) try: people = People.objects.create(name=payload['name'], homeworld=planet, height=payload['height'], mass=payload['mass'], hair_color=payload['hair_color']) except (ValueError, KeyError): return JsonResponse( { "success": False, "msg": "Provided payload is not valid" }, status=400) data = serialize_people_as_json(people) return JsonResponse(data, status=201, safe=False)
def _update(self, people, payload, partial=False): for field in ['name', 'homeworld', 'mass', 'height', 'hair_color']: if not field in payload: if partial: continue return JsonResponse( { "success": False, "msg": "Missing field in full update" }, status=400) if field == 'homeworld': try: payload['homeworld'] = Planet.objects.get( id=payload['homeworld']) except Planet.DoesNotExist: return JsonResponse( { "success": False, "msg": "Planet with id {} does not exist".format( payload['homeworld']) }, status=400) try: setattr(people, field, payload[field]) people.save() except ValueError: return JsonResponse( { "success": False, "msg": "Provided Json is not valid" }, status=400) data = serialize_people_as_json(people) return JsonResponse(data, status=200, safe=False)
def people_detail_view(request, people_id): """ People `detail` actions: Based on the request method, perform the following actions: * GET: Returns the `People` object with given `people_id`. * PUT/PATCH: Updates the `People` object either partially (PATCH) or completely (PUT) using the submitted JSON payload. * DELETE: Deletes `People` object with given `people_id`. Make sure you add at least these validations: * If the view receives another HTTP method out of the ones listed above, return a `400` response. * If submited payload is nos JSON valid, return a `400` response. """ try: person = People.objects.get(id=people_id) except People.DoesNotExist: return JsonResponse({ 'msg': 'ID does not exist', 'success': False }, status=400) if request.method == 'GET': return JsonResponse(serialize_people_as_json(person), status=200) elif request.method == 'PATCH' or request.method == 'PUT': # edge cases try: body = request.body.decode('utf-8') data = json.loads(body) except: return JsonResponse( { 'msg': 'Provide a valid JSON payload', 'success': False }, status=400) # check if planet exists try: planet_id = data['homeworld'].split('/')[-2] planet = Planet.objects.get(id=planet_id) except Planet.DoesNotExist: return JsonResponse( { 'msg': 'Could not find planet with id: {}'.format(planet_id), 'success': False }, status=404) # check if height and mass are integers try: if type(data['height']) != int or type(data['mass']) != int: return JsonResponse( { "success": False, "msg": "Provided payload is not valid" }, status=400) except KeyError: pass # if put (full update), ensure each field matches and exists in data if request.method == 'PUT': fields = ['name', 'height', 'mass', 'homeworld', 'hair_color'] match = False if all(field in data.keys() for field in fields) and\ len(set(data))-len(set(fields)) == 0: match = True else: return JsonResponse( { 'msg': 'Missing field in full update', 'success': False }, status=400) for key, val in data.items(): if key == 'homeworld': person.key = planet else: setattr(person, key, val) person.save() return JsonResponse(serialize_people_as_json(person), status=200) elif request.method == 'DELETE': try: person = People.objects.get(id=people_id) except People.DoesNotExist: return JsonResponse( { 'msg': 'Provide a valid JSON payload', 'success': False }, status=400) person.delete() return JsonResponse( { 'msg': 'deleted {} from the database'.format(person.name), 'success': True }, status=200) else: return JsonResponse({ 'msg': 'Invalid HTTP method', 'success': False }, status=400)
def people_list_view(request): """ People `list` actions: Based on the request method, perform the following actions: * GET: Return the list of all `People` objects in the database. * POST: Create a new `People` object using the submitted JSON payload. Make sure you add at least these validations: * If the view receives another HTTP method out of the ones listed above, return a `400` response. * If submited payload is nos JSON valid, return a `400` response. """ if request.method == 'GET': people = People.objects.all() myList = [] for eachperson in people: myList.append(serialize_people_as_json(eachperson)) return JsonResponse(myList, safe=False) elif request.method == 'POST': body = request.body.decode('utf-8') try: data = json.loads(body) print(data) except: return JsonResponse( { "success": False, "msg": "Provided payload is not valid" }, status=400) planet_id = data['homeworld'].split('/')[-2] # check for valid planet try: planet = Planet.objects.get(id=planet_id) except Planet.DoesNotExist: return JsonResponse( { "success": False, "msg": "Could not find planet with id: {}".format(planet_id) }, status=404) if type(data['height']) != int or type(data['mass']) != int: return JsonResponse( { "success": False, "msg": "Provided payload is not valid" }, status=400) person = People.objects.create(name=data['name'], homeworld=planet, height=data['height'], mass=data['mass'], hair_color=data['hair_color'], created=data['created']) return JsonResponse(serialize_people_as_json(person), status=201) else: return JsonResponse({'err': 'a bad request'}, status=400)
def people_detail_view(request, people_id): """ People `detail` actions: Based on the request method, perform the following actions: * GET: Returns the `People` object with given `people_id`. * PUT/PATCH: Updates the `People` object either partially (PATCH) or completely (PUT) using the submitted JSON payload. * DELETE: Deletes `People` object with given `people_id`. Make sure you add at least these validations: * If the view receives another HTTP method out of the ones listed above, return a `400` response. * If submited payload is nos JSON valid, return a `400` response. """ if request.method == 'GET': try: people_details = People.objects.get(id=people_id) except People.DoesNotExist: return JsonResponse({ "success": False, "msg": "Id does not exist" }, status=400) return JsonResponse(serialize_people_as_json(people_details), safe=False, status=200) elif request.method == 'DELETE': try: People.objects.get(pk=people_id).delete() except People.DoesNotExist: return JsonResponse({ "success": False, "msg": "Id does not exist" }, status=400) return JsonResponse({"success": True}, status=200) elif request.method == 'PATCH': if not request.body: return JsonResponse({ "success": False, "msg": "Empty payload" }, status=400) else: try: payload = json.loads(request.body) except ValueError: return JsonResponse( { "success": False, "msg": "Provide a valid JSON payload" }, status=400) try: people_details = People.objects.get(id=people_id) for key in payload.keys(): setattr(people_details, key, payload[key]) people_details.save() except (ValueError, KeyError): return JsonResponse( { "success": False, "msg": "Provided payload is not valid" }, status=400) return JsonResponse(serialize_people_as_json( People.objects.get(id=people_id)), status=200) elif request.method == 'PUT': if not request.body: return JsonResponse({ "success": False, "msg": "Empty payload" }, status=400) else: try: payload = json.loads(request.body) except ValueError: return JsonResponse( { "success": False, "msg": "Provide a valid JSON payload" }, status=400) try: People.objects.filter(id=people_id).update( name=payload['name'], height=payload['height'], mass=payload['mass'], hair_color=payload['hair_color']) except ValueError: return JsonResponse( { "success": False, "msg": "Provided payload is not valid" }, status=400) except KeyError: return JsonResponse( { "success": False, "msg": "Missing field in full update" }, status=400) return JsonResponse(serialize_people_as_json( People.objects.get(id=people_id)), status=200) else: return JsonResponse({ "success": False, "msg": "Invalid HTTP method" }, status=400)
def people_list_view(request): """ People `list` actions: Based on the request method, perform the following actions: * GET: Return the list of all `People` objects in the database. * POST: Create a new `People` object using the submitted JSON payload. Make sure you add at least these validations: * If the view receives another HTTP method out of the ones listed above, return a `400` response. * If submited payload is nos JSON valid, return a `400` response. """ if request.method == 'GET': people_data = [ serialize_people_as_json(people) for people in People.objects.all() ] return JsonResponse(people_data, safe=False, status=200) elif request.method == 'POST': if not request.body: return JsonResponse({ "success": False, "msg": "Empty payload" }, status=400) else: try: payload = json.loads(request.body) except ValueError: return JsonResponse( { "success": False, "msg": "Provide a valid JSON payload" }, status=400) try: newly_created_people = People.objects.create( name=payload['name'], height=payload['height'], mass=payload['mass'], hair_color=payload['hair_color']) except (ValueError, KeyError): return JsonResponse( { "success": False, "msg": "Provided payload is not valid" }, status=400) return JsonResponse(serialize_people_as_json(newly_created_people), status=201) else: return JsonResponse({ "success": False, "msg": "Invalid HTTP method" }, status=400)
def people_detail_view(request, people_id): """ People `detail` actions: Based on the request method, perform the following actions: * GET: Returns the `People` object with given `people_id`. * PUT/PATCH: Updates the `People` object either partially (PATCH) or completely (PUT) using the submitted JSON payload. * DELETE: Deletes `People` object with given `people_id`. Make sure you add at least these validations: * If the view receives another HTTP method out of the ones listed above, return a `400` response. * If submited payload is nos JSON valid, return a `400` response. """ try: people = People.objects.get(id=people_id) except people.DoesNotExist: return JsonResponse( { "success": False, "msg": "Could not find people with id: {}".format(people_id) }, status=404) if request.body: try: payload = json.loads(request.body.decode('utf-8')) except ValueError: return JsonResponse( { "success": False, "msg": "Provide a valid JSON payload" }, status=400) status = 200 if request.method == 'GET': data = serialize_people_as_json(people) status = 200 elif request.method in ['PUT', 'PATCH']: for field in ['name', 'homeworld', 'mass', 'height', 'hair_color']: if not field in payload: if request.method == 'PATCH': continue return JsonResponse( { "success": False, "msg": "Missing field in full update" }, status=400) if field == 'homeworld': try: payload['homeworld'] = Planet.objects.get( id=payload['homeworld']) except Planet.DoesNotExist: return JsonResponse( { "success": False, "msg": "Could not find planet with id: {}".format( payload['homeworld']) }, status=404) try: setattr(people, field, payload[field]) #instance,attribute,value people.save() except ValueError: return JsonResponse( { "success": False, "msg": "Provided payload is not valid" }, status=400) data = serialize_people_as_json(people) elif request.method == 'DELETE': # DELETE /people/:id people.delete() data = {"success": True} else: data = {"success": False, "msg": "Invalid HTTP method"} status = 400 return JsonResponse(data, safe=False, status=status)
def people_list_view(request): """ People `list` actions: Based on the request method, perform the following actions: * GET: Return the list of all `People` objects in the database. * POST: Create a new `People` object using the submitted JSON payload. Make sure you add at least these validations: * If the view receives another HTTP method out of the ones listed above, return a `400` response. * If submited payload is nos JSON valid, return a `400` response. """ if request.body: try: payload = json.loads(request.body.decode('utf-8')) except ValueError: return JsonResponse( { "success": False, "msg": "Provide a valid JSON payload" }, status=400) status = 200 if request.method == 'GET': qs = People.objects.all() data = [serialize_people_as_json(people) for people in qs] status = 201 elif request.method == 'POST': planet_id = payload.get('homeworld', None) try: planet = Planet.objects.get(id=planet_id) except Planet.DoesNotExist: return JsonResponse( { "success": False, "msg": "Could not find planet with id: {}".format(planet_id) }, status=404) try: people = People.objects.create(name=payload['name'], homeworld=planet, height=payload['height'], mass=payload['mass'], hair_color=payload['hair_color']) except (ValueError, KeyError): return JsonResponse( { "success": False, "msg": "Provided payload is not valid" }, status=400) data = serialize_people_as_json(people) status = 201 else: data = {"success": False, "msg": "Invalid HTTP method"} status = 400 return JsonResponse(data, status=status, safe=False)
def people_detail_view(request, people_id): """ People `detail` actions: Based on the request method, perform the following actions: * GET: Returns the `People` object with given `people_id`. * PUT/PATCH: Updates the `People` object either partially (PATCH) or completely (PUT) using the submitted JSON payload. * DELETE: Deletes `People` object with given `people_id`. Make sure you add at least these validations: * If the view receives another HTTP method out of the ones listed above, return a `400` response. * If submited payload is nos JSON valid, return a `400` response. """ # Test for valid JSON and type check if request.body: try: payload = json.loads(request.body) except (ValueError, KeyError): return JsonResponse( { 'msg': 'Provide a valid JSON payload', 'success': False }, status=400) # Find the specified person, or return an error if not found try: queried_person = People.objects.get(id=people_id) json_person = serialize_people_as_json(queried_person) except People.DoesNotExist: return JsonResponse( { "msg": "Requested person not found", "success": False }, status=404) # Process the HTTP request if (request.method == 'GET'): return JsonResponse(json_person, safe=False) elif (request.method in ['PUT', 'PATCH']): for field in People._meta.get_fields(): # payload.keys(): if (field.name == 'created' or field.name == 'id'): # Not user-defined fields continue if (field.name not in payload.keys() ): # Error if fields are missing for PUT, ok for PATCH if request.method == 'PATCH': continue else: return JsonResponse( { 'msg': 'Missing field in full update', 'success': False }, status=400) if field.name == 'homeworld': homeworld_id = payload['homeworld'] try: homeworld = Planet.objects.get(id=homeworld_id) setattr(queried_person, field.name, homeworld) queried_person.save() except Planet.DoesNotExist: return JsonResponse( { "success": False, "msg": "Could not find planet with id: {}".format( homeworld_id) }, status=404) else: try: setattr(queried_person, field.name, payload[field.name]) queried_person.save() except (TypeError, ValueError, KeyError): return JsonResponse( { "success": False, "msg": "Provided payload is not valid" }, status=400) return JsonResponse(serialize_people_as_json(queried_person), status=200) elif (request.method == 'DELETE'): delete_response = queried_person.delete() if delete_response[0] > 0: return JsonResponse({'success': True}, status=200) else: return JsonResponse({'Delete Failed': 'Server error'}, status=500) else: return JsonResponse({ 'msg': 'Invalid HTTP method', 'success': False }, status=400)
def people_list_view(request): """ People `list` actions: Based on the request method, perform the following actions: * GET: Return the list of all `People` objects in the database. * POST: Create a new `People` object using the submitted JSON payload. Make sure you add at least these validations: * If the view receives another HTTP method out of the ones listed above, return a `400` response. * If submited payload is not JSON valid, return a `400` response. """ # Test for valid JSON and type check if request.body: try: payload = json.loads(request.body) except json.JSONDecodeError: return JsonResponse( { "msg": "Provide a valid JSON payload", 'success': False }, status=400) # GET will return a list of all people and POST will create a new person # All other methods are forbidden if (request.method == 'GET'): people = [ serialize_people_as_json(person) for person in People.objects.all() ] return JsonResponse(people, safe=False) elif (request.method == 'POST'): homeworld_id = payload['homeworld'] try: homeworld = Planet.objects.get(id=homeworld_id) except Planet.DoesNotExist: return JsonResponse( { "success": False, "msg": "Could not find planet with id: {}".format(homeworld_id) }, status=404) try: new_person = People.objects.create( name=payload['name'], homeworld=homeworld, height=payload['height'], mass=payload['mass'], hair_color=payload['hair_color']) return JsonResponse(serialize_people_as_json(new_person), status=201) except (TypeError, ValueError, KeyError): return JsonResponse( { 'msg': 'Provided payload is not valid', 'success': False }, status=400) else: return JsonResponse({ 'msg': 'Invalid HTTP method', 'success': False }, status=400)