def custom_exception_handler(exc, context): # Call REST framework's default exception handler first, # to get the standard error response. if isinstance(exc, Http404): exc = exceptions.NotFound() elif isinstance(exc, PermissionDenied): exc = exceptions.PermissionDenied() if isinstance(exc, exceptions.APIException): headers = {} if getattr(exc, 'auth_header', None): headers['WWW-Authenticate'] = exc.auth_header if getattr(exc, 'wait', None): headers['Retry-After'] = '%d' % exc.wait if hasattr(exc, 'get_full_details'): data = exc.get_full_details() else: data = exc.detail set_rollback() return Response(data, status=exc.status_code, headers=headers) return None
def get(self, request, *args, **kwargs): try: book_id = kwargs.get('id') if book_id: book_obj = Book.objects.filter(pk=book_id, is_delete=False) if book_obj: book_ser = BookModelSerializerV2(book_obj) book_info = book_ser.data message = "单个图书查询成功了" else: raise else: book_list = Book.objects.filter(is_delete=False) book_list_ser = BookModelSerializerV2(book_list, many=True) book_info = book_list_ser.data message = "查询所有图书成功" # return Response({ # "status": status.HTTP_200_OK, # "message": message, # "results": book_info # }) return MyResponse(status.HTTP_200_OK, message, results=book_info) except: raise exceptions.NotFound("查询图书失败")
def post(self, request): serializer = GetTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) username = serializer.validated_data['username'] try: user = models.User.objects.get(username=username) except models.User.DoesNotExist: raise exceptions.NotFound( 'No user found with username `%s`' % username, 'does_not_exist') else: if user.check_password(serializer.validated_data['password']): payload = { 'user_id': user.id, 'exp': (timezone.now() + settings.JWT_LIFETIME).timestamp() } token = jwt.encode(payload, settings.JWT_SECRET, settings.JWT_ALGORITHM) return Response({'token': token}, status=200) else: return Response({'status': 'incorrect_password'}, status=status.HTTP_403_FORBIDDEN)
def has_permission(self, request, view): phone, is_valid_phone = utility.normalize_phone( request.data.get('phone')) email = request.data.get('email') username = None if email: username = email if phone: username = phone if not username: raise exceptions.NotFound(_('phone and email field cant empty!')) if not utility.is_valid_username(username): raise exceptions.ValidationError(_('email or phone is invalid!')) if utility.is_valid_email(username) and User.objects.filter( email=username).exists() \ or is_valid_phone and User.objects.filter( phone=username).exists(): return True return False
def update(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) # Revoke certificate try: utils.puppetca_query( 'PUT', 'certificate_status/%s' % kwargs['name'], data={'desired_state': '%s' % serializer.data['state']}) except Exception as e: if isinstance(e, requests.exceptions.HTTPError): if e.response.status_code == 404: raise exceptions.NotFound() if e.response.status_code == 409: raise exceptions.ValidationError({ 'state': 'Can\'t change certificate state to the specified value' }) raise exceptions.APIException( 'Can\'t update certificate in PuppetCA: %s' % e) # Return result return response.Response(status=status.HTTP_204_NO_CONTENT)
def put(self, request, *args, **kwargs): access_token = kwargs['access_token'] id = kwargs['id'] try: user = UserProfileView.get_profile(access_token).user event = Event.objects.get(pk=id) if user in event.admin.all(): user_ = BdayAppUser.objects.get(pk=request.data['user_id']) friends = UserProfileView.get_profile( access_token).app_friends.all() friends_ = UserProfile.objects.get( user=user_).app_friends.all() if user in friends_ and user_ in friends: event.admin.add(user_) event.save() return response.Response(status=status.HTTP_202_ACCEPTED) else: raise exceptions.PermissionDenied() else: raise exceptions.PermissionDenied() except Event.DoesNotExist: raise exceptions.NotFound("event does not exist") except Exception as e: EventAdminView.handle_error(e)
def uploaded(self, request, pk=None, project_pk=None): """ Add images to a task that have already been uploaded via tusd (eg: to S3 object storage) """ get_and_check_project(request, project_pk, ('change_project', )) try: task = self.queryset.get(pk=pk, project=project_pk) except (ObjectDoesNotExist, ValidationError): raise exceptions.NotFound() files = request.data if len(files) == 0: raise exceptions.ValidationError(detail=_("No files uploaded")) with transaction.atomic(): for image in files: #Append the original filename to url imageurl = image["uploadURL"] + '#' + image["name"] models.ImageUpload.objects.create(task=task, image=imageurl) task.create_task_directories() return Response({'success': True}, status=status.HTTP_200_OK)
def join(self, request): form = GroupFansForm(request.GET) if not form.is_valid(): raise exceptions.ValidationError(form.error_message) if not self.activity.is_on(): raise exceptions.ValidationError(u"凉席活动暂不可使用") group_uni_key = form.cleaned_data['group_id'] group = GroupMamaAdministrator.objects.filter( group_uni_key=group_uni_key).first() if not group: raise exceptions.NotFound(u'此妈妈尚未加入微信群组') self.set_appid_and_secret(settings.WX_PUB_APPID, settings.WX_PUB_APPSECRET) # get openid from cookie openid, unionid = self.get_cookie_openid_and_unoinid(request) userinfo = {} if unionid: userinfo_records = WeixinUserInfo.objects.filter(unionid=unionid) record = userinfo_records.first() else: record = None if record: userinfo.update({ "unionid": record.unionid, "nickname": record.nick, "headimgurl": record.thumbnail }) else: # get openid from 'debug' or from using 'code' (if code exists) userinfo = self.get_auth_userinfo(request) unionid = userinfo.get("unionid") if not self.valid_openid(unionid): # if we still dont have openid, we have to do oauth redirect_url = self.get_snsuserinfo_redirct_url(request) return redirect(redirect_url) # if user is xiaolumama, jump to his qr_code page xiaolumama = XiaoluMama.objects.filter(openid=unionid).first() if xiaolumama: mamagroup = GroupMamaAdministrator.objects.filter( mama_id=xiaolumama.id).first() if mamagroup: group = mamagroup # if user already join a group, change group fans = GroupFans.objects.filter( union_id=userinfo.get('unionid')).first() if not fans: # log.error("lx-join:" + str(userinfo) + '|record:' + str(record)) fans = GroupFans.create(group, request.user.id, userinfo.get('headimgurl'), userinfo.get('nickname'), userinfo.get('unionid'), userinfo.get('openid', '')) user_id = None customer = Customer.objects.filter(unionid=unionid).exclude( status=Customer.DELETE).first() if request.user.id: user_id = request.user.id elif customer: user_id = customer.user_id if user_id: ActivityUsers.join(self.activity, user_id, fans.group_id) group = GroupMamaAdministrator.objects.get(id=fans.group_id) response = redirect("/mall/activity/summer/mat/register?groupId=" + group.group_uni_key + '&fansId=' + str(fans.id)) self.set_cookie_openid_and_unionid(response, openid, unionid) return response
def api_not_found(request): raise exceptions.NotFound(detail="Endpoint not found.")
def get(self, request, pk=None, project_pk=None, tile_type=""): """ Get the metadata for this tasks's asset type """ task = self.get_and_check_task(request, pk) formula = self.request.query_params.get('formula') bands = self.request.query_params.get('bands') if formula == '': formula = None if bands == '': bands = None try: expr, hrange = lookup_formula(formula, bands) except ValueError as e: raise exceptions.ValidationError(str(e)) pmin, pmax = 2.0, 98.0 raster_path = get_raster_path(task, tile_type) if not os.path.isfile(raster_path): raise exceptions.NotFound() try: with rasterio.open(raster_path, "r") as src: band_count = src.meta['count'] if has_alpha_band(src): band_count -= 1 info = main.metadata(src, pmin=pmin, pmax=pmax, histogram_bins=255, histogram_range=hrange, expr=expr) except IndexError as e: # Caught when trying to get an invalid raster metadata raise exceptions.ValidationError( "Cannot retrieve raster metadata: %s" % str(e)) # Override min/max if hrange: for b in info['statistics']: info['statistics'][b]['min'] = hrange[0] info['statistics'][b]['max'] = hrange[1] cmap_labels = { "jet": "Jet", "terrain": "Terrain", "gist_earth": "Earth", "rdylgn": "RdYlGn", "rdylgn_r": "RdYlGn (Reverse)", "spectral": "Spectral", "spectral_r": "Spectral (Reverse)", "pastel1": "Pastel", } colormaps = [] algorithms = [] if tile_type in ['dsm', 'dtm']: colormaps = ['jet', 'terrain', 'gist_earth', 'pastel1'] elif formula and bands: colormaps = ['rdylgn', 'spectral', 'rdylgn_r', 'spectral_r'] algorithms = *get_algorithm_list(band_count), info['color_maps'] = [] info['algorithms'] = algorithms if colormaps: for cmap in colormaps: try: info['color_maps'].append({ 'key': cmap, 'color_map': get_colormap(cmap, format="gdal"), 'label': cmap_labels.get(cmap, cmap) }) except FileNotFoundError: raise exceptions.ValidationError( "Not a valid color_map value: %s" % cmap) del info['address'] info['name'] = task.name info['scheme'] = 'xyz' info['tiles'] = [ get_tile_url(task, tile_type, self.request.query_params) ] if info['maxzoom'] < info['minzoom']: info['maxzoom'] = info['minzoom'] info['maxzoom'] += ZOOM_EXTRA_LEVELS info['minzoom'] -= ZOOM_EXTRA_LEVELS return Response(info)
def multi_delete_texts(request): result, _ = models.Text.objects.filter(shared_folder__owner=request.user, id__in=request.data).delete() if result == 0: raise exceptions.NotFound('No texts matched your list of ids') return response.Response(status=204)
def get_queryset(self): try: return MyPicture.objects.get(id=self.kwargs['picture_id']) except MyPicture.DoesNotExist: raise exceptions.NotFound()
def not_found(request): raise exceptions.NotFound( 'The requested resource could not be found. This could be due to invalid input or a malformed url' )
def fetch_data(self, request, resource_type, *args, **kwargs): resource_router = get_resourcerouter(request.crosswalk) # BB2-291 v2 switch enforced here, entry of all fhir resources queries if self.version == 2 and (not waffle.flag_is_active( request, 'bfd_v2_flag')): raise exceptions.NotFound("bfd_v2_flag not active.") target_url = self.build_url(resource_router, resource_type, *args, **kwargs) logger.debug('FHIR URL with key:%s' % target_url) try: get_parameters = { **self.filter_parameters(request), **self.build_parameters(request) } except voluptuous.error.Invalid as e: raise exceptions.ParseError(detail=e.msg) logger.debug('Here is the URL to send, %s now add ' 'GET parameters %s' % (target_url, get_parameters)) # Now make the call to the backend API req = Request('GET', target_url, data=get_parameters, params=get_parameters, headers=backend_connection.headers(request, url=target_url)) s = Session() prepped = s.prepare_request(req) # Send signal pre_fetch.send_robust(FhirDataView, request=req, api_ver='v2' if self.version == 2 else 'v1') r = s.send(prepped, cert=backend_connection.certs(crosswalk=request.crosswalk), timeout=resource_router.wait_time, verify=FhirServerVerify(crosswalk=request.crosswalk)) # Send signal post_fetch.send_robust(FhirDataView, request=prepped, response=r, api_ver='v2' if self.version == 2 else 'v1') response = build_fhir_response(request._request, target_url, request.crosswalk, r=r, e=None) # BB2-128 error = process_error_response(response) if error is not None: raise error self.validate_response(response) out_data = r.json() self.check_object_permissions(request, out_data) return out_data
def get_queryset(self, **kwargs): try: return Assessment.objects.all().filter( organisation=Organisation.objects.get(id=self.kwargs["pk"])) except Organisation.DoesNotExist: raise exceptions.NotFound("Organisation not found")
def get_achievement(pk): try: return Achievement.objects.get(pk=pk) except Achievement.DoesNotExist: raise exceptions.NotFound('Student does not exist')
def create(self, request, *args, **kwargs): """Create a resource.""" collections = request.data.get('collections', []) # check that user has permissions on all collections that Data # object will be added to for collection_id in collections: try: collection = Collection.objects.get(pk=collection_id) except Collection.DoesNotExist: return Response( { 'collections': [ 'Invalid pk "{}" - object does not exist.'.format( collection_id) ] }, status=status.HTTP_400_BAD_REQUEST) if not request.user.has_perm('add_collection', obj=collection): if request.user.has_perm('view_collection', obj=collection): raise exceptions.PermissionDenied( "You don't have `ADD` permission on collection (id: {})." .format(collection_id)) else: raise exceptions.NotFound( "Collection not found (id: {}).".format(collection_id)) # translate processe's slug to id process_slug = request.data.get('process', None) process_query = Process.objects.filter(slug=process_slug) process_query = get_objects_for_user(request.user, 'view_process', process_query) try: process = process_query.latest() except Process.DoesNotExist: return Response( { 'process': [ 'Invalid process slug "{}" - object does not exist.'. format(process_slug) ] }, status=status.HTTP_400_BAD_REQUEST) request.data['process'] = process.pk # perform "get_or_create" if requested - return existing object # if found if kwargs.pop('get_or_create', False): process_input = request.data.get('input', {}) # use default values if they are not given for field_schema, fields, path in iterate_schema( process_input, process.input_schema): if 'default' in field_schema and field_schema[ 'name'] not in fields: dict_dot(process_input, path, field_schema['default']) checksum = get_data_checksum(process_input, process.slug, process.version) data_qs = Data.objects.filter( checksum=checksum, process__persistence__in=[ Process.PERSISTENCE_CACHED, Process.PERSISTENCE_TEMP ], ) data_qs = get_objects_for_user(request.user, 'view_data', data_qs) if data_qs.exists(): data = data_qs.order_by('created').last() serializer = self.get_serializer(data) return Response(serializer.data) # create the objects resp = super(DataViewSet, self).create(request, *args, **kwargs) # run manager manager.communicate() return resp
def has_object_permission(self, request, view, obj): if is_deprecated(request.version, self.min_version, self.max_version): raise exceptions.NotFound(detail=self.deprecated_message) return True
def custom_exception_handler(exc, context=None): """ Custom exception handler for DRF, which ensures every exception we throw is caught, returned as a nice DRF Response, while still going to sentry etc. This is mostly copied from DRF exception handler, with the following changes/additions: - A condition preventing set_rollback() from being called in some cases where we know there might be something to record in the database - Handling of non-API exceptions, returning an 500 error that looks like an API response, while still logging things to Sentry. """ # If propagate is true, bail early. if settings.DEBUG_PROPAGATE_EXCEPTIONS: raise if isinstance(exc, Http404): exc = exceptions.NotFound() elif isinstance(exc, PermissionDenied): exc = exceptions.PermissionDenied() if isinstance(exc, exceptions.APIException): headers = {} if getattr(exc, 'auth_header', None): headers['WWW-Authenticate'] = exc.auth_header if getattr(exc, 'wait', None): headers['Retry-After'] = '%d' % exc.wait if isinstance(exc.detail, (list, dict)): data = exc.detail code_or_codes = exc.get_codes() else: data = {'detail': exc.detail} code_or_codes = exc.get_codes() # If it's not a throttled/permission denied coming from a restriction, # we can roll the current transaction back. Otherwise don't, we may # need to record something in the database. # Note: `code_or_codes` can be a string, or a list of strings, or even # a dict of strings here, depending on what happened. Fortunately the # only thing we care about is the most basic case, a string, we don't # need to test for the rest. if not isinstance(exc, exceptions.Throttled) and not ( isinstance(exc, exceptions.PermissionDenied) and code_or_codes == 'permission_denied_restriction'): set_rollback() if isinstance(exc, UnavailableForLegalReasons): url = 'https://www.mozilla.org/about/policy/transparency/' headers['Link'] = f'<{url}>; rel="blocked-by"' return Response(data, status=exc.status_code, headers=headers) else: # Not a DRF exception, we want to return an APIfied 500 error while # still logging it to Sentry. data = base_500_data() # Send the got_request_exception signal so other apps like sentry # are aware of the exception. The sender does not match what a real # exception would do (we don't have access to the handler here) but it # should not be an issue, what matters is the request. request = context.get('request') sender = context.get('view').__class__ got_request_exception.send(sender, request=request) # Send the 500 response back. response = Response(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return response
def get_teacher(pk): try: teacher = Teacher.objects.get(pk=pk) return teacher except Teacher.DoesNotExist: raise exceptions.NotFound('Teacher does not exist')
def multi_delete_folders(request): result, _ = request.user.folder.filter(id__in=request.data).delete() if result == 0: raise exceptions.NotFound('No folders matched your list of ids') return response.Response(status=204)
def list_related(self, request, pk=None, field_name=None): """Fetch related object(s), as if sideloaded (used to support link objects). This method gets mapped to `/<resource>/<pk>/<field_name>/` by DynamicRouter for all DynamicRelationField fields. Generally, this method probably shouldn't be overridden. An alternative implementation would be to generate reverse queries. For an exploration of that approach, see: https://gist.github.com/ryochiji/54687d675978c7d96503 """ # Explicitly disable filtering support. Applying filters to this # endpoint would require us to pass through sideload filters, which # can have unintended consequences when applied asynchronously. if self.get_request_feature(self.FILTER): raise exceptions.ValidationError( 'Filtering is not enabled on relation endpoints.') # Prefix include/exclude filters with field_name so it's scoped to # the parent object. field_prefix = field_name + '.' self._prefix_inex_params(request, self.INCLUDE, field_prefix) self._prefix_inex_params(request, self.EXCLUDE, field_prefix) # Filter for parent object, include related field. self.request.query_params.add('filter{pk}', pk) self.request.query_params.add(self.INCLUDE, field_prefix) # Get serializer and field. serializer = self.get_serializer() field = serializer.fields.get(field_name) if field is None: raise exceptions.ValidationError('Unknown field: "%s".' % field_name) if not hasattr(field, 'get_serializer'): raise exceptions.ValidationError('Not a related field: "%s".' % field_name) # Query for root object, with related field prefetched queryset = self.get_queryset() queryset = self.filter_queryset(queryset) instance = queryset.first() if not instance: raise exceptions.NotFound() related = field.get_related(instance) if not related: # See: # http://jsonapi.org/format/#fetching-relationships-responses-404 # This is a case where the "link URL exists but the relationship # is empty" and therefore must return a 200. not related: return Response([] if field.many else {}, status=200) # create an instance of the related serializer # and use it to render the data serializer = field.get_serializer( instance=related, envelope=True, ) return Response(serializer.data)
def validate_incident(self, pk): incident = self.queryset.filter(pk=pk).first() if not incident: raise exceptions.NotFound('Incident with id=%s does not exist' % str(pk)) return incident
class NotFoundView(BaseErrorView): exception = exceptions.NotFound("Some detail message")
def get(self, request, pk=None, project_pk=None, tile_type="", z="", x="", y="", scale=1): """ Get a tile image """ task = self.get_and_check_task(request, pk) z = int(z) x = int(x) y = int(y) scale = int(scale) ext = "png" driver = "jpeg" if ext == "jpg" else ext indexes = None nodata = None formula = self.request.query_params.get('formula') bands = self.request.query_params.get('bands') rescale = self.request.query_params.get('rescale') color_map = self.request.query_params.get('color_map') hillshade = self.request.query_params.get('hillshade') if formula == '': formula = None if bands == '': bands = None if rescale == '': rescale = None if color_map == '': color_map = None if hillshade == '' or hillshade == '0': hillshade = None try: expr, _ = lookup_formula(formula, bands) except ValueError as e: raise exceptions.ValidationError(str(e)) if tile_type in ['dsm', 'dtm'] and rescale is None: rescale = "0,1000" if tile_type in ['dsm', 'dtm'] and color_map is None: color_map = "gray" if tile_type == 'orthophoto' and formula is not None: if color_map is None: color_map = "gray" if rescale is None: rescale = "-1,1" if nodata is not None: nodata = np.nan if nodata == "nan" else float(nodata) tilesize = scale * 256 url = get_raster_path(task, tile_type) if not os.path.isfile(url): raise exceptions.NotFound() with rasterio.open(url) as src: minzoom, maxzoom = get_zoom_safe(src) has_alpha = has_alpha_band(src) if z < minzoom - ZOOM_EXTRA_LEVELS or z > maxzoom + ZOOM_EXTRA_LEVELS: raise exceptions.NotFound() # Handle N-bands datasets for orthophotos (not plant health) if tile_type == 'orthophoto' and expr is None: ci = src.colorinterp # More than 4 bands? if len(ci) > 4: # Try to find RGBA band order if ColorInterp.red in ci and \ ColorInterp.green in ci and \ ColorInterp.blue in ci: indexes = ( ci.index(ColorInterp.red) + 1, ci.index(ColorInterp.green) + 1, ci.index(ColorInterp.blue) + 1, ) else: # Fallback to first three indexes = ( 1, 2, 3, ) elif has_alpha: indexes = non_alpha_indexes(src) resampling = "nearest" padding = 0 if tile_type in ["dsm", "dtm"]: resampling = "bilinear" padding = 16 try: if expr is not None: tile, mask = expression(url, x, y, z, expr=expr, tilesize=tilesize, nodata=nodata, tile_edge_padding=padding, resampling_method=resampling) else: tile, mask = main.tile(url, x, y, z, indexes=indexes, tilesize=tilesize, nodata=nodata, tile_edge_padding=padding, resampling_method=resampling) except TileOutsideBounds: raise exceptions.NotFound("Outside of bounds") if color_map: try: color_map = get_colormap(color_map, format="gdal") except FileNotFoundError: raise exceptions.ValidationError("Not a valid color_map value") intensity = None if hillshade is not None: try: hillshade = float(hillshade) if hillshade <= 0: hillshade = 1.0 except ValueError: raise exceptions.ValidationError("Invalid hillshade value") if tile.shape[0] != 1: raise exceptions.ValidationError( "Cannot compute hillshade of non-elevation raster (multiple bands found)" ) delta_scale = (maxzoom + ZOOM_EXTRA_LEVELS + 1 - z) * 4 dx = src.meta["transform"][0] * delta_scale dy = -src.meta["transform"][4] * delta_scale ls = LightSource(azdeg=315, altdeg=45) # Hillshading is not a local tile operation and # requires neighbor tiles to be rendered seamlessly elevation = get_elevation_tiles(tile[0], url, x, y, z, tilesize, nodata, resampling, padding) intensity = ls.hillshade(elevation, dx=dx, dy=dy, vert_exag=hillshade) intensity = intensity[tilesize:tilesize * 2, tilesize:tilesize * 2] rgb, rmask = rescale_tile(tile, mask, rescale=rescale) rgb = apply_colormap(rgb, color_map) if intensity is not None: # Quick check if rgb.shape[0] != 3: raise exceptions.ValidationError( "Cannot process tile: intensity image provided, but no RGB data was computed." ) intensity = intensity * 255.0 rgb = hsv_blend(rgb, intensity) options = img_profiles.get(driver, {}) return HttpResponse(array_to_image(rgb, rmask, img_format=driver, **options), content_type="image/{}".format(ext))
def get_queryset(self): community = community_models.Community.objects.get(slug=self.kwargs.get('community')) if not community.is_active: raise exceptions.NotFound() return models.Post.objects.filter(community=community)
def determine_version(self, request, *args, **kwargs): version = kwargs.get(self.version_param, self.default_version) if not self.is_allowed_version(version): raise exceptions.NotFound(self.invalid_version_message) return version
def put(self, request, *args, **kwargs): try: logger.info("Starting PUT method") access_token = kwargs['access_token'] id = kwargs['id'] global exitFlag exitFlag = 0 logger.info("access token is " + access_token + " event id is" + id) user_profile = UserProfileView.get_profile(access_token) user = user_profile.user event = Event.objects.get(pk=id) logger.info("event obtained from id") if user in event.admin.all(): user_ids = eval(request.data['user_ids']) for user_id in user_ids: user_ = BdayAppUser.objects.get(pk=user_id) friends = UserProfileView.get_profile( access_token).app_friends.all() friends_ = UserProfile.objects.get( user=user_).app_friends.all() if user in friends_ and user_ in friends: event.members.add(user_) event.save() chat_buffer = UnreadChatBuffer.objects.create( event=event, user=user_, last_read_chat=None) chat_buffer.save() chat = EventChat.objects.create_event_chat( Event.objects.get(pk=event.id), user_, wish=None, message_field=str(user_.id) + " joined the event", url_field=None, file_field=None, type='CENTER') chat.save() logger.info("added center chat") notification_message = "Your friend " + user_profile.first_name + " added you to event " + event.name notification = Notification.objects.create_notification( notification_message, user_, None, type="NEW_MEMBER_ADDITION", event=event) notification.save() logger.info("added notification message " + notification_message) serializer = NotificationSerializer(notification) conn = stomp.Connection([(STOMP_SERVER_URL, STOMP_PORT) ]) conn.start() conn.connect(STOMP_ID, STOMP_PASSWORD, wait=True) conn.send(body=json.dumps(serializer.data), destination='/topic/notifications_' + str(user_.id)) logger.info("Sending a message through apollo") time.sleep(2) logger.info("Message Sent.........Disconnecting") conn.disconnect() logger.info("Disconnected !!!") else: raise exceptions.PermissionDenied() event_members = event.members.all() event_admins = event.admin.all() workQueue = Queue.Queue(10) queueLock.acquire() for member in event_members: if member.id is user_.id: continue notification_message = "Your friend " + UserProfile.objects.get( user=user_ ).first_name + " joined the event " + event.name notification = Notification.objects.create_notification( notification_message, member, None, type="NEW_MEMBER_JOINED", event=event) notification.save() serializer = NotificationSerializer(notification) workQueue.put({ "data": serializer.data, "destination": '/topic/notifications_' + str(member.id) }) for admin in event_admins: notification_message = "Your friend " + UserProfile.objects.get( user=user_ ).first_name + " joined the event " + event.name notification = Notification.objects.create_notification( notification_message, admin, None, type="NEW_MEMBER_JOINED", event=event) notification.save() serializer = NotificationSerializer(notification) workQueue.put({ "data": serializer.data, "destination": '/topic/notifications_' + str(admin.id) }) queueLock.release() threads = [] for i in range(0, MAX_THREADS): thread = MultiThreading("WORKER " + str(i), workQueue) thread.start() threads.append(thread) while not workQueue.empty(): pass # Notify threads it's time to exit exitFlag = 1 for t in threads: t.join() logger.info("Sent all notifications") logger.info("Completing PUT method") return response.Response(status=status.HTTP_202_ACCEPTED) else: raise exceptions.PermissionDenied() except Event.DoesNotExist: raise exceptions.NotFound("event does not exist") except Exception as e: EventMembersView.handle_error(e)
def get(self, request, task_id): try: return Response(services.get_scan_result(task_id=task_id)) except: raise exceptions.NotFound()
def delete(self, request, *args, **kwargs): try: logger.info("Starting DELETE method") access_token = kwargs['access_token'] global exitFlag exitFlag = 0 id = kwargs['id'] logger.info("access token is " + access_token + " event id is" + id) user = UserProfileView.get_profile(access_token).user event = Event.objects.get(pk=id) logger.info("event obtained from id") if "user_ids" in request.data: if user in event.admin.all(): user_ids = eval(request.data['user_ids']) for user_id in user_ids: user_ = BdayAppUser.objects.get(pk=user_id) friends = UserProfileView.get_profile( access_token).app_friends.all() friends_ = UserProfile.objects.get( user=user_).app_friends.all() if user in friends_ and user_ in friends: event.members.remove(user_) event.save() members = event.members.all() admins = event.admin.all() workQueue = Queue.Queue(10) queueLock.acquire() for member in members: chat = EventChat.objects.create_event_chat( Event.objects.get(pk=id), user, wish=None, message_field=str(user.id) + " deleted " + str(user_.id) + " from the event", url_field=None, file_field=None, type='CENTER') chat.save() logger.info("added center chat") notification_message = "Admin " + UserProfile.objects.get( user=user ).first_name + " has deleted " + UserProfile.objects.get( user=user_ ).first_name + " from event " + event.name notification = Notification.objects.create_notification( notification_message, member, None, type='MEMBER_DELETION_BY_ADMIN', event=event) notification.save() serializer = NotificationSerializer( notification) workQueue.put({ "data": serializer.data, "destination": '/topic/notifications_' + str(member.id) }) for admin in admins: chat = EventChat.objects.create_event_chat( Event.objects.get(pk=id), user, wish=None, message_field=str(user.id) + " deleted " + str(user_.id) + " from the event", url_field=None, file_field=None, type='CENTER') chat.save() logger.info("added center chat") notification_message = "Admin " + UserProfile.objects.get( user=user ).first_name + " has deleted " + UserProfile.objects.get( user=user_ ).first_name + " from event " + event.name notification = Notification.objects.create_notification( notification_message, admin, None, type='MEMBER_DELETION_BY_ADMIN', event=event) notification.save() serializer = NotificationSerializer( notification) workQueue.put({ "data": serializer.data, "destination": '/topic/notifications_' + str(admin.id) }) queueLock.release() threads = [] for i in range(0, MAX_THREADS): thread = MultiThreading( "WORKER " + str(i), workQueue) thread.start() threads.append(thread) while not workQueue.empty(): pass # Notify threads it's time to exit exitFlag = 1 for t in threads: t.join() logger.info("Sent all Notification") else: raise exceptions.PermissionDenied() #event.members.remove(BdayAppUser.objects.get(pk=request.data['user_id'])) #event.save() logger.info("Completing DELETE method") return response.Response(status=status.HTTP_202_ACCEPTED) else: raise exceptions.PermissionDenied() else: if user in event.members.all() and user not in event.admin.all( ): event.members.remove(user) members = event.members.all() admins = event.admin.all() workQueue = Queue.Queue(10) queueLock.acquire() for member in members: event.save() chat = EventChat.objects.create_event_chat( Event.objects.get(pk=event.id), user, wish=None, message_field=str(user.id) + "left the event", url_field=None, file_field=None, type='CENTER') chat.save() notification_message = "Your friend " + UserProfile.objects.get( user=user ).first_name + " left the event " + event.name notification = Notification.objects.create_notification( notification_message, member, None, type='MEMBER_LEAVING_EVENT', event=event) notification.save() serializer = NotificationSerializer(notification) workQueue.put({ "data": serializer.data, "destination": '/topic/notifications_' + str(member.id) }) for admin in admins: event.save() chat = EventChat.objects.create_event_chat( Event.objects.get(pk=event.id), user, wish=None, message_field=str(user.id) + "left the event", url_field=None, file_field=None, type='CENTER') chat.save() notification_message = "Your friend " + UserProfile.objects.get( user=user ).first_name + " left the event " + event.name notification = Notification.objects.create_notification( notification_message, admin, None, type='MEMBER_LEAVING_EVENT', event=event) notification.save() serializer = NotificationSerializer(notification) workQueue.put({ "data": serializer.data, "destination": '/topic/notifications_' + str(admin.id) }) queueLock.release() threads = [] for i in range(0, MAX_THREADS): thread = MultiThreading("WORKER " + str(i), workQueue) thread.start() threads.append(thread) while not workQueue.empty(): pass # Notify threads it's time to exit exitFlag = 1 for t in threads: t.join() logger.info("Sent all Notification") logger.info("Completing DELETE method") else: raise exceptions.PermissionDenied() except Event.DoesNotExist: raise exceptions.NotFound("event does not exist") except Exception as e: EventMembersView.handle_error(e)