def bo_administrator_set_password(self): try: logger.info('Handling /backoffice/users/set-password.') if self.method == 'POST': stream = BytesIO(self.body) data = JSONParser().parse(stream) if not 'token' in data or not 'new_password' in data: return HttpResponse(status=401) token = data.get('token', None) new_password = data['new_password'].encode('utf-8') user = jwt_util.jwt_auth_get_user(token) hashed_password = bcrypt.hashpw(new_password, bcrypt.gensalt()) user.password = hashed_password user.save() return HttpResponse(status=200) else: return HttpResponse(status=405) except CustomException as ce: return HttpResponse(ce.message, status=450) except: logger.error(traceback.format_exc()) return HttpResponse(CustomErrorMessages.UNEXPECTED_ERROR, status=500)
def bo_administrator_recover_password(self): try: logger.info('Handling /backoffice/users/recover-password.') if self.method == 'POST': stream = BytesIO(self.body) data = JSONParser().parse(stream) if 'email' not in data: return HttpResponse(status=401) user_credentials = dict() user_credentials['email'] = data.get('email', None) if not Administrator.objects.filter(email=user_credentials['email']).exists(): raise CustomException(CustomErrorMessages.USER_NOT_FOUND) token = jwt_util.jwt_recovery_generate_token(user_credentials) thread.start_new_thread(email_sender.send_password_recovery_email, (user_credentials['email'], token)) logger.info('Recovery token: ' + str(token)) return HttpResponse(status=200) else: return HttpResponse(status=405) except CustomException as ce: return HttpResponse(ce.message, status=450) except: logger.error(traceback.format_exc()) return HttpResponse(CustomErrorMessages.UNEXPECTED_ERROR, status=500)
def login_account(request): """ Login the current user, after authenticating the credentials. :param request: :return: """ if request.method == 'POST': data = JSONParser().parse(request) username = data.get('username', None) password = data.get('password', None) account = authenticate(username=username, password=password) if account is not None: if not account.is_email_verified: return Response({ 'status': 'Unverified', 'message': 'This account is not verified.' }, status=status.HTTP_401_UNAUTHORIZED) if not account.is_active: return Response({ 'status': 'Unauthorized', 'message': 'This account has been disabled.' }, status=status.HTTP_401_UNAUTHORIZED) auth_login(request, account) serialized = LoginSerializer(account) return Response(serialized.data, status=status.HTTP_200_OK) else: return Response({ 'status': 'Unauthorized', 'message': 'Username/password combination invalid.' }, status=status.HTTP_401_UNAUTHORIZED)
def post(self, request): data = JSONParser().parse(request) access_token = data.get('access_token', '') try: app = SocialApp.objects.get(provider="facebook") token = SocialToken(app=app, token=access_token) # check token against facebook login = fb_complete_login(app, token) login.token = token login.state = SocialLogin.state_from_request(request) # add or update the user into users table ret = complete_social_login(request, login) # if we get here we've succeeded return Response(status=200, data={ 'success': True, 'username': request.user.username, 'user_id': request.user.pk, }) except: return Response(status=401 ,data={ 'success': False, 'reason': "Bad Access Token", })
def bo_administrator_login(self): try: logger.info('Handling /backoffice/users/login.') if self.method == 'POST': stream = BytesIO(self.body) data = JSONParser().parse(stream) credentials = dict() credentials['email'] = data.get('email', None) credentials['password'] = data['password'].encode('utf-8') try: administrator = Administrator.objects.get(email=credentials['email'], password__isnull=False, active=True) except Administrator.DoesNotExist: logger.warning('Login with administrator ({email}) failed. Administrator not found.'.format(email=credentials['email'])) raise CustomException(CustomErrorMessages.USER_NOT_FOUND) if not bcrypt.hashpw(credentials['password'], administrator.password.encode('utf-8')) == administrator.password.encode('utf-8'): logger.warning('Login with administrator ({email}) failed. Password doesn\'t match.'.format(email=credentials['email'])) raise CustomException(CustomErrorMessages.INVALID_CREDENTIALS) response = dict() response['token'] = jwt_util.jwt_auth_generate_token(credentials) return HttpResponse(json.dumps(response), status=200) else: return HttpResponse(status=405) except CustomException as ce: return HttpResponse(ce.message, status=450) except: logger.error(traceback.format_exc()) return HttpResponse(CustomErrorMessages.UNEXPECTED_ERROR, status=500)
def parse_request(request): content = {} # POST request from mobile client try: # fetch data from request object logger.debug("Trying to fetch data from request using JSONParser method") content = JSONParser().parse(request) except: # DRF panel try: # fetch data from _content parameter in drf request object logger.debug("Trying to fetch data from request.POST['_content']") content = json.loads(request.POST["_content"]) except: # POST request through web-site ajax request logger.debug("Trying to fetch from request.POST") content = request.POST if request.FILES: content.update(request.FILES) # fetch data from request.data try: logger.debug("Trying to fetch data from request.data") content = request.data except: logger.debug("Unable to fetch data from request.") logger.debug("content in parse_request: %s" %content) return content
def update_name_about(request): """ update name update about update contact No :param request: :return: """ context = {} if request.method == 'POST': data = JSONParser().parse(request) user = str(request.user.id) name = data.get('name', None) about = data.get('about', None) contact = data.get('contact', None) update_about = ProfileDetails.objects.get(user_id=user) update_name = Account.objects.get(pk=user) if name is not None: name = name.split() update_name.first_name = name[0] update_name.last_name = name[1] update_name.save() if contact is not None: update_name.contact_number = contact update_name.save() if about is not None: update_about.about = about update_about.save() context['status'] = 'success' return HttpResponse(json.dumps(context)) else: context['status'] = 'failed' return HttpResponse(json.dumps(context))
def forgot_password(request): if request.method == 'POST': data = JSONParser().parse(request) email = data.get('email', None) salt = hashlib.sha1(str(random.random())).hexdigest()[:5] activation_key = hashlib.sha1(email+salt).hexdigest() try: # user = User.objects.get(email=email) user=Account.objects.get(email=email) log.info(user) except user.DoesNotExist: request.session['error1']="Email Id Doesn't exist" user.reset_password_key = activation_key user.save() email_subject = 'Reset Password.' activation_url = "{1}/accounts/update_password/{0}".format(activation_key, os.environ.get('HOST_NAME')) rendertxt = render_to_string('email/reset_password.html', {'user': user, 'activation_url': activation_url}) msg = EmailMultiAlternatives(subject=email_subject, body=rendertxt, from_email="*****@*****.**", to=[email]) msg.attach_alternative(rendertxt, "text/html") msg.send() response = msg.mandrill_response[0] mandrill_status = response['status'] return redirect('/accounts/forget_pwd/')
def post (self,request): original_request = request._request data = JSONParser().parse(request) access_token = data.get('access_token', '') try: app = SocialApp.objects.get(provider='facebook') fb_auth_token = SocialToken(app=app, token=access_token) login = fb_complete_login(original_request, app, fb_auth_token) login.token = fb_auth_token login.state = SocialLogin.state_from_request(original_request) complete_social_login(original_request, login) token, _ = Token.objects.get_or_create(user=original_request.user) data_response ={ 'username': original_request.user.username, 'objectId': original_request.user.pk, 'firstName': original_request.user.first_name, 'lastName': original_request.user.last_name, 'email': original_request.user.email, 'sessionToken': token.key, } return Response(status=status.HTTP_200_OK, data=data_response) except: return Response(status=status.HTTP_401_UNAUTHORIZED,data={ 'detail': 'Bad Access Token', })
def add_dynamic_filter(request): """ Add a filter with its default parameters in the registry (redis). List all the dynamic filters registered. """ try: r = get_redis_connection() except: return JSONResponse('Error connecting with DB', status=500) if request.method == 'GET': keys = r.keys("filter:*") dynamic_filters = [] for key in keys: dynamic_filter = r.hgetall(key) dynamic_filter["name"]=key.split(":")[1] dynamic_filters.append(dynamic_filter) return JSONResponse(dynamic_filters, status=200) if request.method == 'POST': data = JSONParser().parse(request) name = data.pop("name", None) if not name: return JSONResponse('Filter must have a name', status=400) r.hmset('filter:'+str(name), data) return JSONResponse('Filter has been added in the registy', status=201) return JSONResponse('Method '+str(request.method)+' not allowed.', status=405)
def update_password_new(request): if request.method == 'POST': data = JSONParser().parse(request) # if form.is_valid(): password = data.get('password',None) confirm_password = data.get('confirm_password',None) key = data.get('key') log.info(key) if password != confirm_password: request.session['error1']= "passwords doesn't match" try: user = Account.objects.get(reset_password_key=key) except user.DoesNotExist: request.session['error1']="Invalid URL" if user is not None: user.set_password(password) user.reset_password_key = '' user.save() email_subject = 'Password changed for your commonproject account!' message = render_to_string('email/password_changed.html') msg = EmailMultiAlternatives(subject=email_subject, body=message, from_email="*****@*****.**", to=[user.email]) msg.attach_alternative(message, "text/html") msg.send() request.session['error1']="password updated successfully" return redirect('/accounts/login/') else: request.session['error1']="password is not valid "
def post(self, request): print "posting data" data = JSONParser().parse(request) access_token = data.get('access_token', '') try: print request app = SocialApp.objects.get(provider="facebook") token = SocialToken(app=app, token=access_token) login = fb_complete_login(app, token) login.token = token login.state = SocialLogin.state_from_request(request) print login ret = complete_social_login(request, login) return Response(status=200, data={ 'success': True, 'username': request.user.username, 'user_id': request.user.pk, }) except: return Response(status=401 ,data={ 'success': False, 'reason': "Bad Access Token", })
def passwordSendEmail(request, format=None): if request.method == 'PUT': data = JSONParser().parse(request) email = getPropertyByName('email', data.items()) token = getPropertyByName('token', data.items()) if correctForgotPasswordToken(email, token): TO = email tmpPassword = tokenGenerator() code = md5Encoding(tmpPassword) SUBJECT = "AliveTracker reset password message. (DO NOT REPLY)" FROM = "*****@*****.**" MESSAGE = """ You requested to have your password reset, below is your new password. Username:""" + TO + """ New Password: """ + tmpPassword + """ To login your new password, please go to http://www.alivetracker.com Thanks, AliveTracker Team""" try: User.objects.filter(email=TO).update(password=code, entity_status=2) except: return responseJsonUtil(False, 'ERROR000', None) try: sendEmail(FROM, TO, SUBJECT, MESSAGE) return responseJsonUtil(True, None, None) except: return responseJsonUtil(False, 'ERROR002', None) else: return responseJsonUtil(False, 'ERROR100', None)
def post(self, request): data = JSONParser().parse(request) access_token = data.get('access_token', '') try: app = SocialApp.objects.get(provider="facebook") token = SocialToken(app=app, token=access_token) # return SocialLogin(account) login = fb_complete_login(app, token) login.token = token login.state = SocialLogin.state_from_request(request) # add or update the user ret = complete_social_login(request, login) # if we get here we've succeeded return Response(status=200, data={ 'success': True, 'username': request.user.username, 'user_id': request.user.pk, 'csrf_token': unicode(csrf(request)['csrf_token']) }) except: # FIXME: Catch only what is needed #, HttpForbidden return Response(status=401 ,data={ 'success': False, 'reason': "Bad Access Token", })
def get_phone_num(request, ver): if request.method == 'GET': return JSONResponse("GET_PHONE") elif request.method == 'POST': data = JSONParser().parse(request) flg_identity = data.has_key('identity') flg_credit = data.has_key('credit') flg_token = data.has_key('token') flg_phone = data.has_key('phone') if not flg_token: return JSONResponse('Token is empty!') if not data['token'] == 'n35FudlypEEd0SSodacAWUc1sbhFD4': return JSONResponse('Token is invalid!') if not flg_phone: return JSONResponse('Phone is empty!') phone_num = data['phone'] tmp_data = { 'query': { 'match': { 'phone': phone_num }}} res = es.search( index='wafdata', body = tmp_data ) ret_cnt = res['hits']['total'] return JSONResponse(ret_cnt)
def post(self, request): try: data = JSONParser().parse(request) data = data.get(PARAMETER_DATA) except JSONDecodeError: raise ParseError(detail="No data found on the request") ''' check all values ''' catid = WebRequestParameter.get_data(PARAMETER_CATEGORY, data) question = WebRequestParameter.get_data(PARAMETER_QUESTION, data) options = WebRequestParameter.get_data(PARAMETER_OPTIONS, data) answer = WebRequestParameter.get_data(PARAMETER_ANSWER, data) if not all( (catid, question, options, answer ) ): raise ParseError(detail="Some parameters are missing from request") ''' search for category ''' category = Category.objects(catid = int(catid)).first() if category is None: raise APIException("Category not exists!") try: self.add_question(category, question, options, answer) except: traceback.print_exc() raise APIException("Unable to add question. Try again later!") return Response(True)
def forgotPassword(request, format=None): if request.method == 'PUT': data = JSONParser().parse(request) TO = getPropertyByName('email', data.items()) if emailExists(TO): code = md5Encoding(tokenGenerator()) SUBJECT = "AliveTracker forgot password instructions. (DO NOT REPLY)" FROM = "*****@*****.**" MESSAGE = """ Hey, we heard you lost your AliveTracker password. Use the following link to reset your password: http://www.alivetracker.com/#resetPasswordPage?email=""" + TO + """&token=""" + code + """ Ignore this email if you haven't experienced any password trouble. Thanks, AliveTracker Team""" try: tmpUser = User.objects.get(email=TO) User_Forgot_Password.objects.get_or_create(user=tmpUser) User_Forgot_Password.objects.filter(user=tmpUser).update(token=code) except: return responseJsonUtil(False, 'ERROR000', None) try: sendEmail(FROM, TO, SUBJECT, MESSAGE) return responseJsonUtil(True, None, None) except: return responseJsonUtil(False, 'ERROR002', None) else: return responseJsonUtil(False, 'ERROR102', None)
def sentiments_endpoint(request): """ List all sentiments or create a new one. """ if request.method == 'POST': data = JSONParser().parse(request) data['ip_address'] = get_ip(request) data['created'] = data.get('created') or datetime.datetime.now() data['twitter_user'] = '******' location_match = geolite2.lookup(data['ip_address']) if location_match: print(location_match.location) data['latitude'], data['longitude'] = location_match.location serializer = models.SentimentSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) return JSONResponse(serializer.errors, status=400) elif request.method == 'GET': max_items = request.GET.get('max_items') or 100 do_analyze = request.GET.get('analyze') or False if do_analyze: _do_analysis() sentiments = models.Sentiment.objects.filter(latitude__isnull=False)[:max_items] serializer = models.SentimentSerializer(sentiments, many=True) return JSONResponse(serializer.data) return JSONResponse([], status=400)
def post(self, request): ''' check user token ''' token = TokenMiddleware.get_token(request) if token is None: raise NotAuthenticated("Token invalid or expired!") try: data = JSONParser().parse(request) data = data.get(PARAMETER_DATA) except JSONDecodeError: raise ParseError(detail="No data found on the request") game_type = WebRequestParameter.get_data(PARAMETER_TYPE, data) ''' extract user from token ''' if not token.has_key(PARAMETER_USER): raise NotAuthenticated() ''' get user object from request ''' user = token.get(PARAMETER_USER) if user is None: raise NotAuthenticated("User not exists!") score = WebRequestParameter.get_data(PARAMETER_SCORE, data) if not isinstance(score, list): raise APIException("Object must be an instance of list") ''' update user score ''' user, score_detail = self.update_score(user, score, game_type) if score_detail.has_key("levelup"): token = TokenMiddleware.get_token(request) if token: from engine.util.const import ten_minutes_in_seconds cache_data = dict(uid=user.id, name=user.name, user=user) cache.set(user.auth_token, cache_data, ten_minutes_in_seconds) return Response(score_detail)
def add_metric(request): """ Add a metric workload in the registry (redis) """ try: r = get_redis_connection() except: return JSONResponse('Error connecting with DB', status=500) if request.method == 'GET': keys = r.keys("metric:*") print 'keys', keys metrics = [] for key in keys: metric = r.hgetall(key) metric["name"]=key.split(":")[1] metrics.append(metric) return JSONResponse(metrics, status=200) if request.method == 'POST': data = JSONParser().parse(request) name = data.pop("name", None) if not name: return JSONResponse('Metric must have a name', status=400) r.hmset('metric:'+str(name), data) return JSONResponse('Metric has been added in the registy', status=201) return JSONResponse('Method '+str(request.method)+' not allowed.', status=405)
def __call__(self, request, content_object, **kwargs): submit_data = {'authenticated_username': request.user.username} ws_delete_content_uri = settings.ZTREE_WS_BASE_URL + request.tree_context.node.absolute_path + '/delete' resp = dispatch_request_json(ws_delete_content_uri, method='POST', data=submit_data) #resp_py = simplejson.load(StringIO(resp)) resp_py = JSONParser().parse( BytesIO(resp) ) if resp_py.get('status'): return 1 return 0
def setPassword(request, format=None): if request.method == 'PUT': if not userAuthentication(request): return responseJsonUtil(False, 'ERROR103', None) data = JSONParser().parse(request) tmpPassword = getPropertyByName('password', data.items()) User.objects.filter(session_key=request.session._session_key).update(password=tmpPassword) tmpUser = getUserByRequest(request) tmpSerializer = UserSerializer(tmpUser) return responseJsonUtil(True, None, tmpSerializer)
def register_user(request): try: data = JSONParser().parse(request) tmpNewUser = User.objects.create(email=getPropertyByName('email', data.items()), password=getPropertyByName('password', data.items())); newSessionHandler(request, tmpNewUser); tmpUserSerializer = UserSerializer(tmpNewUser) return responseJsonUtil(True, None, tmpUserSerializer) except BaseException: return responseJsonUtil(False, 'ERROR101', None)
def update_default_group(request, pk, format=None): try: user = User.objects.get(pk=pk) except User.DoesNotExist: return responseJsonUtil(False, 404, None) data = JSONParser().parse(request) tmpDefaultGroup = getPropertyByName('default_group', data.items()) user.default_group = tmpDefaultGroup user.save() serializer = UserSerializer(user, data=data) return responseJsonUtil(True, None, serializer)
def make_guess(self, request): """ Following a player "buzzing in" this should be called to supply that players guess having been speech recognised. This adds the guess to the queued player. """ data = JSONParser().parse(request) queue = GuessQueue.objects.all()[0] queue.guess = data.get('guess') queue.save() print 'Guess: %s' % data.get('guess') return Response({'status': 'ok'})
def groupsServices(argRequest, format=None): if userAuthentication(argRequest): if argRequest.method == 'POST': try: tmpData = JSONParser().parse(argRequest) tmpNewGroup = Group.objects.create(name=getPropertyByName('name', tmpData.items()), description=getPropertyByName('description', tmpData.items()), logo_url=getPropertyByName('logo_url', tmpData.items()), web_site_url=getPropertyByName('web_site_url', tmpData.items()), created=date.today()) tmpUser = getUserByRequest(argRequest) Group_User.objects.create(user=tmpUser, group=tmpNewGroup, role=getAdminRole()) tmpSerializer = GroupSerializer(tmpNewGroup) return responseJsonUtil(True, None, tmpSerializer) except BaseException: return responseJsonUtil(False, 'ERROR000', None) if argRequest.method == 'PUT': tmpData = JSONParser().parse(argRequest) tmpidtoevaluate = getPropertyByName('id', tmpData.items()) if tmpidtoevaluate == 0: try: tmpnewgroup = Group.objects.create(name=getPropertyByName('name', tmpData.items()), description=getPropertyByName('description', tmpData.items()), logo_url=getPropertyByName('logo_url', tmpData.items()), web_site_url=getPropertyByName('web_site_url', tmpData.items()), created=date.today()) tmpuser = getUserByRequest(argRequest) Group_User.objects.create(user = tmpuser, group = tmpnewgroup, role = getAdminRole()) tmpserializer = GroupSerializer(tmpnewgroup) return responseJsonUtil(True, None, tmpserializer) except BaseException: return responseJsonUtil(False,'ERROR000', None) else: try: Group.objects.filter(id=getPropertyByName('id', tmpData.items())).update( name=getPropertyByName('name', tmpData.items()), description=getPropertyByName('description', tmpData.items()), logo_url=getPropertyByName('logo_url', tmpData.items()), web_site_url=getPropertyByName('web_site_url', tmpData.items())) modifiedGroup = Group.objects.get(id=getPropertyByName('id', tmpData.items())) tmpSerializer = GroupSerializer(modifiedGroup) return responseJsonUtil(True, None, tmpSerializer) except Group.DoesNotExist: return responseJsonUtil('False', 'ERROR000', None) if argRequest.method == 'GET': return responseJsonUtil(True, None, None) else: return responseJsonUtil(False, 'ERROR103', None)
def media_upload(request, id): if request.method == 'POST': user_id = str(request.user.id) user = get_object_or_404(Account, pk=user_id) project = user.projects_set.get(id=id) new_media = project.media_set.create(created=timezone.now()) data = request.FILES.get('files') media_type = request.POST.get('type') # file_static_dir = "/static/user-temp-data/"+user_id+'/media/'+media_type+'/' file_static_dir = "/static/user-temp-data/{0}/projects/project_{1}/media/{2}/"\ .format(user_id, project.id, media_type) name, ext = os.path.splitext(data.name) new_name = '{0}user_{1}_{2}_media_{3}{4}'.format(file_static_dir, str(request.user.id), media_type, new_media.id, ext) img_static_url = upload_save_get_url(data, new_name) if media_type == 'Images': media_type = 1 elif media_type == 'Tracks': media_type = 2 elif media_type == 'Videos': media_type = 3 elif media_type == 'Articles': media_type = 4 thumb_img = get_thumbnail(img_static_url, media_type) new_media.url=img_static_url new_media.thumb_img=thumb_img new_media.type=media_type new_media.save() db_media = Media.objects.get(pk=new_media.id) serial_media = MediaSerializer(db_media) return Response(serial_media.data, status=status.HTTP_200_OK) if request.method == 'PUT': # print 'put req' data = JSONParser().parse(request) title = data.get('title', None) description = data.get('description', None) try: media = Media.objects.get(pk=id) if title is not None: media.name = title if description is not None: media.description = description media.save() serial_media = MediaSerializer(media) return Response({'id': id, 'title': title, 'description': description}) except Media.DoesNotExist: pass return Response({'error': 'media not available'})
def updateUserRole(argRequest, format=None): if not userAuthentication(argRequest): return responseJsonUtil(False, 'ERROR103', None) try: tmpData = JSONParser().parse(argRequest) tmpGroupId = getPropertyByName('id', tmpData.items()) deleteUsersBelongGroup(tmpGroupId) insertProjectUsers(tmpData, tmpGroupId) return responseJsonUtil(True, None, None) except Group_User.DoesNotExist: return responseJsonUtil(False, 'ERROR300', None) except BaseException: return responseJsonUtil(False, 'ERROR000', None)
def buzz_in(self, request): """ This method is called by the controller when a button is pressed and queues the player to await a guess to be made. """ queue_size = len(GuessQueue.objects.all()) if queue_size == 0: data = JSONParser().parse(request) print 'Queuing player %d' % data.get('player_id') new_queue = GuessQueue() new_queue.player = data.get('player_id') new_queue.save() return Response({'status': 'ok'})
def resetPassword(request, format=None): if request.method == 'PUT': data = JSONParser().parse(request) tmpEmail = getPropertyByName('email', data.items()) tmpToken = getPropertyByName('token', data.items()) tmpPassword = getPropertyByName('password', data.items()) if correctForgotPasswordToken(tmpEmail, tmpToken): User.objects.filter(email=tmpEmail).update(password=tmpPassword) tmpUser = User.objects.get(email=tmpEmail) newSessionHandler(request, tmpUser); tmpSerializer = UserSerializer(tmpUser) return responseJsonUtil(True, None, tmpSerializer) else: return responseJsonUtil(False, 'ERROR104', None)
def legislation_detail(request, pk): """ Legislation, update or delete a code Legislation. """ try: legislation = Legislation.objects.get(pk=pk) except Legislation.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = LegislationSerializer(legislation) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = LegislationSerializer(legislation, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': legislation.delete() return HttpResponse(status=204)
def SP(request, pk): """ Retrieve, update or delete a code snippet. """ try: one_SP = Student_Period.objects.get(pk=pk) except Student_Period.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = SPSerializer(one_SP) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = SPSerializer(one_SP, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': one_SP.delete() return HttpResponse(status=204)
def attendance(request, SID): """ Retrieve, update or delete a code snippet. """ try: one_attendance = Attendance.objects.filter(Student_ID=SID) except Attendance.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = AttendanceSerializer(one_attendance) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = AttendanceSerializer(one_attendance, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': one_attendance.delete() return HttpResponse(status=204)
def costeleaccnt_list(request): if request.method == 'GET': query_set = BCosteleaccnt.objects.all() serializer = BCosteleaccntSerializer(query_set, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) if BCosteleaccnt.objects.filter(pl_cd=data['pl_cd'], usage_fg='Y').exists(): raise exceptions.ParseError("Duplicate PL Code") if BCosteleaccnt.objects.filter(accnt_cd=data['accnt_cd'], usage_fg='Y').exists(): raise exceptions.ParseError("Duplicate Account Code") serializer = BCosteleaccntSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
def enfermedad_detail(request, pk): """ recupera, actualiza o elimina una ficha """ try: enfermedad = Enfermedad.objects.get(pk=pk) except Enfermedad.DoesNotExist: return HttpResponse(status=404) if request.method == "GET": serializer = EnfermedadSerializer(enfermedad) return JsonResponse(serializer.data) elif request.method == "PUT": data = JSONParser().parse(request) serializer = EnfermedadSerializer(enfermedad, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == "DELETE": enfermedad.delete() return HttpResponse(status=204)
def comorbilidad_detail(request, pk): """ recupera, actualiza o elimina una ficha """ try: comorbilidad = Comorbilidad.objects.get(pk=pk) except Comorbilidad.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = ComorbilidadSerializer(comorbilidad) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = ComorbilidadSerializer(comorbilidad, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': comorbilidad.delete() return HttpResponse(status=204)
def query_detail(request, pk): """ Retrieve query data """ try: query = VinylQuery.objects.get(pk=pk) except VinylQuery.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = VinylQuerySerializer(query) return JSONResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = VinylQuerySerializer(query, data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data) return JSONResponse(serializer.errors, status=400) elif request.method == 'DELETE': query.delete() return HttpResponse(status=204)
def person(request, pk): """ Retrieve, update or delete a code snippet. """ try: person = Personnel.objects.get(pk=pk) except Personnel.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = PersonnelSerializer(person) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = PersonnelSerializer(person, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': person.delete() return HttpResponse(status=204)
def message_detail(request, pk): """ Retrieve, update or delete a message. """ try: message = Message.objects.get(pk=pk) except Snippet.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = MessageSerializer(message) return JSONResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = MessageSerializers(message, data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data) return JSONResponse(serializer.errors, status=400) elif request.method == 'DELETE': message.delete() return HttpResponse(status=204)
def assignment(request, pk): """ Retrieve, update or delete a code snippet. """ try: one_assignment = Assignment.objects.get(pk=pk) except Assignment.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = AssignmentSerializer(one_assignment) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = AssignmentSerializer(one_document, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': one_assignment.delete() return HttpResponse(status=204)
def doctor_detail(request, pk): """ Retrieve, update or delete a code snippet. """ try: doctor = Doctor.objects.get(pk=pk) except Doctor.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = DoctorSerializer(doctor) return JSONResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = DoctorSerializer(doctor, data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data) return JSONResponse(serializer.errors, status=400) elif request.method == 'DELETE': doctor.delete() return HttpResponse(status=204)
def collect_comment_pages(request): user_data = JSONParser().parse(request) if 'access_token' not in user_data or 'page_id' not in user_data or 'keywords' not in user_data or 'last_collect_time' not in user_data or 'project_id' not in user_data: return JsonResponse({'message': 'Missing fields'}, status=status.HTTP_400_BAD_REQUEST) user_access_token = user_data['access_token'] page_id = user_data['page_id'] keywords = user_data['keywords'] last_collect_time = user_data['last_collect_time'] project_id = user_data['project_id'] try: page_id, page_access_token, keywords = getUserPage( user_access_token, page_id, keywords) # commentRows, likeRows, collectTime = q.enqueue(collectData(page_id,page_access_token, keywords, last_collect_time)) # data = q.enqueue(collectData(page_id,page_access_token, keywords, last_collect_time)) q.enqueue(save_collected_comments, project_id, page_id, page_access_token, keywords, last_collect_time) except: return JsonResponse({'messasge': 'error'}, status=status.HTTP_400_BAD_REQUEST) return JsonResponse({'data': 'currently collecting data'}, status=status.HTTP_200_OK)
def dapp_detail(request, pk): try: dapp = Dapp.objects.get(pk=pk) except Dapp.DoesNotExit: return JsonResponse({'message': 'The data entered doesnot exist'}, status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': dapp_serializer = DappSerializer(dapp) return JsonResponse(dapp_serializer.data) elif request.method == 'PUT': dapp_data = JSONParser().parse(request) dapp_serializer = DappSerializer(dapp, data=dapp_data) if dapp_serializer.is_valid(): dapp_serializer.save() return JsonResponse(dapp_serializer.data) return JsonResponse(dapp_serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': dapp.delete() return JsonResponse({'message': 'deleted successfully'}, status=status.HTTP_204_NO_CONTENT)
def todo_detail(request, pk): """ Retrieve, update or delete a code snippet. """ try: todo = Todo.objects.get(pk=pk) except Todo.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = TodoSerializer(todo) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = TodoSerializer(todo, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': todo.delete() return HttpResponse(status=204)
def snippet_list(request): # function-based list view """ List all code snippets, or create a new snippet. """ if request.method == 'GET': snippets = Snippet.objects.all() serializer = SnippetSerializer( snippets, many=True ) # many=True option to retrieve a list of objects instead of a single object instance return JsonResponse( serializer.data, safe=False) # TODO: Research safe option for JsonResponse elif request.method == 'POST': data = JSONParser().parse(request) serializer = SnippetSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse( serializer.data, status=201 ) # 201 Created: The request has been fulfilled, resulting in the creation of a new resource. return JsonResponse( serializer.errors, status=400 ) # 400 Bad Request: The server cannot or will not process the request due to an apparent client error (e.g., malformed request syntax, size too large, invalid request message framing, or deceptive request routing).
def snippet_detail(request, pk): # Definimos una vista que recibe el objeto request y la primary key del snippet con el cual vamos a operar """ Retrieve, update or delete a code snippet. """ try: # Decalramos un try/catch por si el snippet no se encuentra en la base de datos snippet = Snippet.objects.get(pk=pk) # Intentamos recuperar el snippet con el id pasado como path param except Snippet.DoesNotExist: # Definimos el manejador si el snippet no se encuentra en la base de datos return HttpResponse(status=404) # Le devolvemos al cliente un HTTP status code 404 porque no encontramos el snippet al que quiere acceder if request.method == 'GET': # Implementamos el verbo HTTP GET para un snippet específico serializer = SnippetSerializer(snippet) # Creamos el serializador para serializar el snippet return JsonResponse(serializer.data) # Le devolvemos al cliente el JSON correspondiente al snippet consultado elif request.method == 'PUT': # Implementamos el verbo HTTP PUT para modificar un snippet específico data = JSONParser().parse(request) # Obtenemos el JSON payload del request serializer = SnippetSerializer(snippet, data=data) # Deserializamos el snippet junto con los datos a modificar if serializer.is_valid(): # Corremos las validaciones serializer.save() # Actualizamos el snippet return JsonResponse(serializer.data) # Le devolvemos al cliente el snippet actualizado return JsonResponse(serializer.errors, status=400) # Los datos son incorrectos. Le devolvemos al cliente un HTTP status code 400 elif request.method == 'DELETE': # Implementamos el verbo HTTP DELETE para eliminar un snippet específico snippet.delete() # Eliminamos el snippet de la base de datos return HttpResponse(status=204) # Le devolvemos al usuario un HTTP status code 204 indicando que se proceso el requerimiento y no hay datos para devolver
def pet_detail(request, pk): # find tutorial by pk (id) try: pet = Pet.objects.get(pk=pk) except Pet.DoesNotExist: return JsonResponse({'message': 'The pet does not exist'}, status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': pet_serializer = PetSerializer(pet) return JsonResponse(pet_serializer.data) elif request.method == 'PUT': pet_data = JSONParser().parse(request) pet_serializer = PetSerializer(pet, data=pet_data) if pet_serializer.is_valid(): pet_serializer.save() return JsonResponse(pet_serializer.data) return JsonResponse(pet_serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': pet.delete() return JsonResponse({'message': 'Pet was deleted successfully!'}, status=status.HTTP_204_NO_CONTENT)
def employee_detail(request, pk): """ Get, update or remove an employee instance """ try: employee = Employee.objects.get(pk=pk) except Employee.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = EmployeeSerializer(employee) return Response(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = EmployeeSerializer(employee, data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': employee.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def candidates(request): """ GET requests are handled by returning all candidates. POST requests are interpreted as requests for new candidates. GET requests support optional url query strings as follows: - filter_reviewed will filter the candidate list on the state of candidate.reviewed; either 'reviewed' or 'not_reviewed' - sort_by will sort the result list by the provided option; currently supports 'status' and 'date_applied' """ if request.method == 'GET': candidates = Candidate.objects.all() filter_reviewed = request.GET.get('filter_reviewed') if filter_reviewed == 'reviewed': candidates = candidates.filter(reviewed=True) elif filter_reviewed == 'not_reviewed': candidates = candidates.filter(reviewed=False) sort_by = request.GET.get('sort_by') if sort_by in ['status', 'date_applied']: candidates = candidates.order_by(sort_by) serializer = CandidateSerializer(candidates, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': candidate_data = JSONParser().parse(request) serializer = CandidateSerializer(data=candidate_data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) else: return JsonResponse(serializer.errors, status=400)
def api_contact(request, curent_cat=1): if request.method == 'POST': data = JSONParser().parse(request) logger.debug('api_contact POST: {0}'.format(data)) if 'categories' not in data: data['categories'] = curent_cat else: curent_cat = int(data['categories']) try: cur_cat = Category.objects.get(pk=curent_cat) except Category.DoesNotExist: return JSONResponse({'errors': _(u'Category does not exist')}, status=400) if 'title' not in data: data['title'] = cur_cat.title serializer = QuestionSerializer(data=data) if serializer.is_valid(): serializer.save() if request.user.is_authenticated(): logger.debug("FORM SEND authenticated user") # TODO: отправляем полностью письмо send_mail_full(serializer.data, tpl_subject=cur_cat.tpl_subject, tpl_message=cur_cat.tpl_message, tpl_message_html=cur_cat.tpl_message_html) else: logger.debug("FORM SEND is anonymous") send_mail_full(serializer.data, tpl_subject=cur_cat.tpl_subject, tpl_message=cur_cat.tpl_message, tpl_message_html=cur_cat.tpl_message_html) return JSONResponse(serializer.data, status=201) else: return JSONResponse(serializer.errors, status=400) return JSONResponse({}, status=status.HTTP_400_BAD_REQUEST)
def option_detail(request, slug_option, format=None): """ Retrieve,update or delete an option. """ try: option = Option.objects.get(slug_option=slug_option) except option.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = OptionSerializer(option) return Response(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = OptionSerializer(option, data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': option.delete() return Response(status=204)
def request_parent(request): if not request.body: return HttpResponse(status=404) elif request.method == 'POST': data = JSONParser().parse(request) try: requesting_user = User.objects.get(data['requesting_email']) requested_user = User.objects.get(email=data['requested_email']) htmlMessage = "Hi " + requested_user.get_email( ) + ",<br><br> " + requesting_user.get_email( ) + "is requesting to connect with you.<br>To confirm this connection <a href='safewalk-web.herokuapp.com/confirm?parent=" + requesting_user.get_email( ) + "&child=" + requested_user.get_email( ) + ">please click here.</a>'<br><br> Thank You, SafeWalk" send_mail("Request", "", settings.EMAIL_HOST_USER, requested_user.get_email(), fail_silently=False, html_message=htmlMessage) except: return HttpResponse(status=400) return HttpResponse(status=202) else: return HttpResponse(status=400)
def Stuff_detail(request, pk): """ Retrieve, update or delete a code Stuff. """ try: Stuff = Stuff.objects.get(pk=pk) except Stuff.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = StuffSerializer(Stuff) return JSONResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = StuffSerializer(Stuff, data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data) return JSONResponse(serializer.errors, status=400) elif request.method == 'DELETE': Stuff.delete() return HttpResponse(status=204)
def snippet_detail(request, pk, format=None): """ Retrieve, update or delete a code snippet. """ try: snippet = Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = SnippetSerializer(snippet) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = SnippetSerializer(snippet, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': snippet.delete() return HttpResponse(status=204)
def cstctr_list(request): if request.method == 'GET': query_set = CbCostCenter.objects.all() serializer = CbCostCenterSerializer(query_set, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) if CbCostCenter.objects.filter(cstctr_cd=data['cstctr_cd'], usage_fg='Y').exists(): raise exceptions.ParseError("Duplicate Code") if CbCostCenter.objects.filter(cstctr_nm=data['cstctr_nm'], usage_fg='Y').exists(): raise exceptions.ParseError("Duplicate Name") serializer = CbCostCenterSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
def library_from_nko_detail(request, pk): """ Retrieve, update or delete a code LibraryFromNGO. """ try: library_from_ngo = LibraryFromNGO.objects.get(pk=pk) except LibraryFromNGO.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = LibraryFromNGOSerializer(library_from_ngo) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = LibraryFromNGOSerializer(library_from_ngo, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': library_from_ngo.delete() return HttpResponse(status=204)
def rank_library_detail(request, pk): """ Retrieve, update or delete a code RankLibrary. """ try: rank_library = RankLibrary.objects.get(pk=pk) except RankLibrary.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = RankLibrarySerializer(rank_library) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = RankLibrarySerializer(rank_library, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': rank_library.delete() return HttpResponse(status=204)
def qa_detail(request, pk): """ QA, update or delete a code QA. """ try: qa = QA.objects.get(pk=pk) except QA.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = QASerializer(qa) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = QASerializer(qa, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': qa.delete() return HttpResponse(status=204)
def incident_detail(request, pk): """ Retrieve, update or delete a Incident. """ try: Incident = Incident.objects.get(pk=pk) except Incident.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = IncidentSerializer(Incident) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = IncidentSerializer(Incident, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': Incident.delete() return HttpResponse(status=204)
def IC(request, pk): """ Retrieve, update or delete a code snippet. """ try: one_IC = Instructors_Courses.objects.get(pk=pk) except Instructors_Courses.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = ICSerializer(one_IC) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = ICSerializer(one_IC, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': one_IC.delete() return HttpResponse(status=204)