class UploadedDataResource(ModelResource): """ API for accessing UploadedData. """ user = ForeignKey(ProfileResource, 'user') file_size = CharField(attribute='filesize', readonly=True) layers = ToManyField(UploadedLayerResource, 'uploadlayer_set', full=True) file_url = CharField(attribute='file_url', readonly=True, null=True) class Meta: queryset = UploadedData.objects.all() resource_name = 'data' allowed_methods = ['get', 'delete'] authorization = UserOwnsObjectAuthorization() authentication = SessionAuthentication() filtering = {'user': ALL_WITH_RELATIONS} def get_object_list(self, request): """ Filters the list view by the current user. """ queryset = super(UploadedDataResource, self).get_object_list(request) if not request.user.is_superuser: return queryset.filter(user=request.user) return queryset
class AudienceResource(ProtectedModelResource): id = IntegerField('id', readonly=True) is_deleted = BooleanField('is_deleted', default=False, readonly=True) owner = CharField(readonly=True) tracking_code = CharField(readonly=True) piggyback_url = CharField(readonly=True) class Meta: authorization = Auth('owner') allowed_methods = ('get', 'post', 'get', 'put', 'delete') always_return_data = True filtering = {"is_deleted": (ALL)} fields = ('name', 'id_random') validation = FormValidation(form_class=AudienceForm) queryset = Audience.objects.all() resource_name = 'audience' def hydrate(self, bundle): bundle.obj.owner = bundle.request.user.account return bundle def dehydrate(self, bundle): # We need to use public_id here public_id = bundle.obj.public_id bundle.data['tracking_code'] = get_audience_code(public_id) bundle.data['piggyback_url'] = get_audience_piggyback_url(public_id) return bundle
class BrandResource(ProtectedModelResource): class Meta: resource_name = 'brand' authorization = Auth('owner') allowed_methods = ('get', 'post', 'get', 'put', 'delete') always_return_data = True filtering = { 'is_deleted': (ALL), 'appnexus_access_status': ( 'exact', 'startswith', ), } validation = BrandValidation() queryset = Brand.objects.all() fields = ('brand_id', 'check_access_status', 'page_name') id = IntegerField('id', readonly=True) facebook_page_id = CharField('thirdparty_page_id') appnexus_access_status = CharField('appnexus_access_status', readonly=True) owner = CharField('owner', readonly=True) # Get only not deleted Brands def get_object_list(self, request): return super(BrandResource, self).get_object_list(request).filter(is_deleted=False) def raise_appnexus_error(self, request, error_msg): "" from tastypie.exceptions import ImmediateHttpResponse errors = {'brand': {'error': error_msg}} raise ImmediateHttpResponse( response=self.error_response(request, errors)) def hydrate(self, bundle): bundle.obj.owner = bundle.request.user.account # Send for confirmation if bundle.data['check_access_status'] is True: bundle.obj.appnexus_access_status = ACCESS_STATUS['pending'] return bundle # Before save call AppNexus API to check brand id and facebook page id def save(self, bundle, skip_errors=False): if bundle.request.method == 'POST': self.is_valid(bundle) if not bundle.errors: result = bundle.obj.update_access_status() if 'error' in result: self.raise_appnexus_error(bundle.request, result['error']) return super(BrandResource, self).save(bundle, skip_errors) def dehydrate_appnexus_access_status(self, bundle): return bundle.obj.get_appnexus_access_status_display() def dehydrate(self, bundle): return bundle
class ConfigEntityResource(FootprintResource, PolicySetsResourceMixin, BuiltFormSetsResourceMixin, DbEntityResourceMixin, PresentationResourceMixin, CategoryResourceMixin, CloneableResourceMixin, PermissionResourceMixin, EditorResourceMixin): def get_object_list(self, request): return self.permission_get_object_list( request, super(ConfigEntityResource, self).get_object_list(request)) media = fields.ToManyField(MediumResource, 'media', full=False, null=True) # These should never be written, they are calculated automatically behavior = fields.ToOneField(BehaviorResource, 'behavior', full=False, null=True) creator = fields.ToOneField(UserResource, 'creator', full=True, null=True, readonly=True) updater = fields.ToOneField(UserResource, 'updater', full=True, null=True) # The GroupHierarchies associated with the ConfigEntity. This is a reverse relationship and is thus readonly # groups_map = lambda bundle: Group.objects.filter(group_hierarchy__in=bundle.obj.group_hierarchies.all()) # groups = fields.ToManyField(GroupResource, attribute=groups_map, readonly=True) schema = CharField(attribute='schema', readonly=True) scope = CharField(attribute='scope', readonly=True) # The client of the ConfigEntity. client is the top-level region in the ConfigEntity's ancestry. # Thus GlobalConfig has no client client = CharField(attribute='client', readonly=True, null=True) _content_type_ids = None _perm_ids = None def hydrate(self, bundle): """ Set the user who created the ConfigEntity :param bundle: :return: """ if not bundle.obj.id: bundle.obj.creator = self.resolve_user(bundle.request.GET) # Mark the ConfigEntity as incomplete if new. This will be 100 after the post-save finished bundle.obj.setup_percent_complete = 0 bundle.obj.updater = self.resolve_user(bundle.request.GET) return super(ConfigEntityResource, self).hydrate(bundle) class Meta(FootprintResource.Meta): abstract = True always_return_data = True queryset = ConfigEntity.objects.filter(deleted=False) resource_name = 'config_entity' filtering = { # Accept the parent_config_entity to limit the ConfigEntity instances to a certain id # (i.e. parent_config_entity__id=n) "parent_config_entity": ALL_WITH_RELATIONS, "id": ALL, "name": ("exact", ) }
class UploadedDataResource(ModelResource): """ API for accessing UploadedData. """ user = ForeignKey(UserResource, 'user') file_size = CharField(attribute='filesize', readonly=True, null=True) layers = ToManyField(UploadedLayerResource, 'uploadlayer_set', full=True) file_url = CharField(attribute='file_url', readonly=True, null=True) class Meta: queryset = UploadedData.objects.all() resource_name = 'data' allowed_methods = ['get', 'delete'] authorization = UserOwnsObjectAuthorization() authentication = SessionAuthentication() filtering = {'user': ALL_WITH_RELATIONS} def get_object_list(self, request): """ Filters the list view by the current user. """ queryset = super(UploadedDataResource, self).get_object_list(request) if not request.user.is_superuser: return queryset.filter(user=request.user) return queryset def import_all_layers(self, request, api_name=None, resource_name=None, pk=None): ud = UploadedData.objects.get(id=pk) n_layers_imported = import_all_layers(ud, owner=request.user) resp = self.create_response(request, {'layer_count': n_layers_imported}) return resp def prepend_urls(self): pu = super(UploadedDataResource, self).prepend_urls() pu.extend([ url(r'^(?P<resource_name>{0})/(?P<pk>\w[\w/-]*)/import_all_layers{1}$' .format(self._meta.resource_name, trailing_slash()), self.wrap_view('import_all_layers'), name='import_all_data') ]) return pu
class ContentTypeResource(ModelResource): username = CharField() class Meta: cache = SimpleCache() queryset = ContentType.objects.all() serializer = api.Serializer()
class ArticleResource(MongoEngineResource): author_ids = ReferencedListField(AuthorResource, 'authors', null=True) # Gosh. "url" is reserved in EmberJS… We need to map our # internal `Article.url` to Ember's `Article.public_url`. public_url = CharField(attribute='url', readonly=True) class Meta: queryset = Article.objects.all() # Ember-data expect the following 2 directives always_return_data = True allowed_methods = ( 'get', 'post', 'put', 'delete', ) collection_name = 'objects' resource_name = 'article' filtering = { 'id': ALL, } ordering = ALL excludes = ( 'pages_urls', 'authors', 'url', ) # These are specific to 1flow functionnals. authentication = SessionAndApiKeyAuthentications()
class ClientLandUseDefinitionResource(DynamicResource): """ This is an abstract resource class. A client specific resource subclass is created by dynamic_resource_class """ label = CharField('label', readonly=True) class Meta(DynamicResource.Meta): abstract = True always_return_data = False resource_name = 'client_land_use_definition' # querysets are not allowed for abstract classes. So use a special property # to associate the model _model = ClientLandUseDefinition def create_subclass(self, params, **kwargs): land_use_definition_fixture_class = resolve_fixture_class( "built_form", "land_use_definition", ClientLandUseDefinition, settings.CLIENT) return get_dynamic_resource_class( self.__class__, land_use_definition_fixture_class) def resolve_config_entity(self, params): """ :param params.config_entity: The id of the config_entity :return: The subclassed ConfigEntity instanced based on the param value """ return ConfigEntity.objects.filter(id=int(params['config_entity__id'])).all().select_subclasses()[0]
class UserResource(ModelResource): username = CharField() class Meta: cache = SimpleCache() queryset = User.objects.all() serializer = api.Serializer()
class PolicyResource(ModelResource): Insurer = ForeignKey(InsurerResource, "insurer", full=True) customer = ForeignKey(CustomerResource, "customer", full=True) policy_type = CharField(attribute="policy_type__name", null=True) class Meta: queryset = Policy.objects.all().annotate() include_resource_uri = False
class PersonTestResource(MongoResource): name = CharField(attribute='name') class Meta: object_class = PersonTest queryset = PersonTest.objects.all() allowed_methods = ['get', 'post', 'put', 'delete'] authorization = Authorization() authentication = Authentication()
class NonSiteLocationNameResource(ModelResource): loc_type = CharField() parent_id = IntegerField() text = CharField() class Meta: fields = ['pk'] limit = 0 resource_name = 'location-names' allowed_methods = ['get'] queryset = Location.objects.exclude(loc_type__code='adm6') def dehydrate(self, bundle): bundle.data['text'] = bundle.obj.name bundle.data['loc_type'] = bundle.obj.loc_type.name.lower() if bundle.obj.parent: bundle.data['parent_id'] = bundle.obj.parent.pk else: bundle.data['parent_id'] = None return bundle
class LocalComputerResource(ModelResource): name = CharField(attribute="name", null=True) class Meta: queryset = LocalComputer.objects.all() authorization = Authorization() authentication = Authentication() resource_name = 'local_computer' always_return_data = True serializer = PrettyJSONSerializer() filtering = {'name': ALL_WITH_RELATIONS}
class ExportJobResource(ModelResource): query = ToOneField('dds.api.QueryResource', attribute='query') requested = DateTimeField('requested', readonly=True, default=now) begin = DateTimeField('begin', readonly=True, null=True, blank=True) end = DateTimeField('end', readonly=True, null=True, blank=True) download_link = CharField('get_indirect_link', readonly=True, blank=True) filename = CharField('export_filename', readonly=True, blank=True, null=True) class Meta: queryset = ExportJob.objects.all() authentication = SessionAuthentication() authorization = OwnedOnlyAuthorization() def apply_authorization_limits(self, request, object_list): return object_list.filter(query__account=request.user.account) def obj_create(self, bundle, **kwargs): result = super(ExportJobResource, self).obj_create(bundle, **kwargs) if result.obj.query.account != bundle.request.user.account: raise Unauthorized("Can't attach to a query that is not yours") return result def obj_get_list(self, bundle, **kwargs): return [ f for f in super(ExportJobResource, self).obj_get_list( bundle, **kwargs) if f.query.account == bundle.request.user.account ] def obj_get(self, bundle, **kwargs): result = super(ExportJobResource, self).obj_get(bundle, **kwargs) if result.query.account != bundle.request.user.account: raise Unauthorized("Forbidden") return result
class QueryResource(ModelResource): sample = CharField(attribute='sample', readonly=True, null=True, help_text="sample of the data returned") num_records = IntegerField(attribute='num_records', readonly=True, help_text="number of records matched") sort_by = ToOneField(CensusFieldResource, attribute='sort_by', help_text="field to sort results by") queryfilter_set = ToManyField('dds.api.QueryFilterResource', attribute='queryfilter_set', blank=True, null=True, full=True) export_jobs = ToManyField(ExportJobResource, attribute='exportjob_set', help_text="jobs run with this query", full=True, blank=True, null=True) class Meta: queryset = Query.objects.all() authentication = SessionAuthentication() authorization = OwnedOnlyAuthorization() def obj_create(self, bundle, **kwargs): return super(QueryResource, self).obj_create(bundle, account=bundle.request.user.account, **kwargs) def obj_get_list(self, bundle, **kwargs): return [ f for f in super(QueryResource, self).obj_get_list(bundle, **kwargs) if f.account == bundle.request.user.account ] def obj_get(self, bundle, **kwargs): result = super(QueryResource, self).obj_get(bundle, **kwargs) if result.account != bundle.request.user.account: raise Unauthorized("Forbidden") return result def apply_authorization_limits(self, request, object_list): return object_list.filter(account=request.user.account)
class RegistrationTokenResource(CustomModelResource): """ Server registration tokens. To add a server via HTTPS registration, acquire one of these first. POSTs may be passed 'expiry' and 'credits' PATCHs may only be passed 'cancelled' """ profile = ToOneField( ServerProfileResource, "profile", null=False, help_text= "Server profile to be used when setting up servers using this token", ) register_command = CharField( help_text= "Command line to run on a storage server to register it using this token" ) def dehydrate_register_command(self, bundle): server_profile = ServerProfileResource().get_via_uri( bundle.data["profile"], bundle.request) return "curl -k %sagent/setup/%s/%s | python" % ( settings.SERVER_HTTP_URL, bundle.obj.secret, "?profile_name=%s" % server_profile.name, ) class Meta: object_class = RegistrationToken authentication = AnonymousAuthentication() authorization = TokenAuthorization() serializer = DateSerializer() list_allowed_methods = ["get", "post"] detail_allowed_methods = ["patch", "get"] fields = [ "id", "secret", "expiry", "credits", "cancelled", "profile", "register_command" ] resource_name = "registration_token" queryset = RegistrationToken.objects.filter( cancelled=False, expiry__gt=IMLDateTime.utcnow(), credits__gt=0) validation = RegistrationTokenValidation() always_return_data = True
class ExperimentResource(ModelResource): local_computer_id = IntegerField(attribute="local_computer_id") name = CharField(attribute="name", null=True) class Meta: queryset = Experiment.objects.all() authorization = Authorization() authentication = Authentication() resource_name = 'experiment' filtering = { 'local_computer_id': ALL_WITH_RELATIONS, 'name': ALL_WITH_RELATIONS, } always_return_data = True serializer = PrettyJSONSerializer()
class DocumentResource(ModelResource): type = ToOneField(DocTypeNameResource, 'type', null=True) stream = ToOneField(StreamNameResource, 'stream', null=True) group = ToOneField(GroupResource, 'group', null=True) intended_std_level = ToOneField(IntendedStdLevelNameResource, 'intended_std_level', null=True) std_level = ToOneField(StdLevelNameResource, 'std_level', null=True) ad = ToOneField(PersonResource, 'ad', null=True) shepherd = ToOneField(EmailResource, 'shepherd', null=True) states = ToManyField(StateResource, 'states', null=True) tags = ToManyField(DocTagNameResource, 'tags', null=True) rfc = CharField(attribute='rfc_number', null=True) submissions = ToManyField('ietf.submit.resources.SubmissionResource', 'submission_set', null=True) class Meta: cache = SimpleCache() queryset = Document.objects.all() serializer = api.Serializer() #resource_name = 'document' filtering = { "time": ALL, "title": ALL, "abstract": ALL, "rev": ALL, "pages": ALL, "order": ALL, "expires": ALL, "notify": ALL, "external_url": ALL, "note": ALL, "internal_comments": ALL, "name": ALL, "type": ALL_WITH_RELATIONS, "stream": ALL_WITH_RELATIONS, "group": ALL_WITH_RELATIONS, "intended_std_level": ALL_WITH_RELATIONS, "std_level": ALL_WITH_RELATIONS, "ad": ALL_WITH_RELATIONS, "shepherd": ALL_WITH_RELATIONS, "states": ALL_WITH_RELATIONS, "tags": ALL_WITH_RELATIONS, }
class RegistrationTokenResource(CustomModelResource): """ Server registration tokens. To add a server via HTTPS registration, acquire one of these first. POSTs may be passed 'expiry' and 'credits' PATCHs may only be passed 'cancelled' """ profile = ToOneField( ServerProfileResource, 'profile', null=False, help_text= "Server profile to be used when setting up servers using this token") register_command = CharField( help_text= "Command line to run on a storage server to register it using this token" ) def dehydrate_register_command(self, bundle): server_profile = ServerProfileResource().get_via_uri( bundle.data['profile']) return 'curl -k %sagent/setup/%s/%s | python' % ( settings.SERVER_HTTP_URL, bundle.obj.secret, '?profile_name=%s' % server_profile.name) class Meta: object_class = RegistrationToken authentication = AnonymousAuthentication() authorization = TokenAuthorization() list_allowed_methods = ['get', 'post'] detail_allowed_methods = ['patch', 'get'] fields = [ 'id', 'secret', 'expiry', 'credits', 'cancelled', 'profile', 'register_command' ] resource_name = 'registration_token' queryset = RegistrationToken.objects.filter( cancelled=False, expiry__gt=IMLDateTime.utcnow(), credits__gt=0) validation = RegistrationTokenValidation() always_return_data = True
class AirSpacesResource(AbstractAirSpacesResource): geometry = GeometryField(attribute="geom") properties = DictField(attribute="get_properties") # this default to a feature. Beware when returning multiple objects. type = CharField(default="Feature") class Meta: queryset = AirSpaces.objects.all() resource_name = 'airspaces' serializer = GeoJSONSerializer() allowed_methods = ['get'] # these are wrapped by the 'properties' attribute above. excludes = [ 'name', 'start_date', 'stop_date', 'clazz', 'ext_info', 'geom', 'ext_info', 'ceil_alti', 'ceil_alti_m', 'ceil_fl', 'ceil_ref', 'ceil_f_sfc', 'ceil_unl', 'flr_alti', 'flr_alti_m', 'flr_fl', 'flr_ref', 'flr_f_sfc', 'flr_unl' ]
class SignalResource(ModelResource): local_computer_id = IntegerField(attribute="local_computer_id") system_id = IntegerField(attribute="system_id", null=True) name = CharField(attribute="name", null=True) experiment_id = IntegerField(attribute="experiment_id", null=True) class Meta: queryset = Signal.objects.all() authorization = Authorization() authentication = Authentication() resource_name = 'signal' always_return_data = True filtering = { 'local_computer_id': ALL_WITH_RELATIONS, 'name': ALL_WITH_RELATIONS, 'experiment_id': ALL_WITH_RELATIONS } serializer = PrettyJSONSerializer()
class GroupResource(ModelResource): state = ToOneField(GroupStateNameResource, 'state', null=True) type = ToOneField(GroupTypeNameResource, 'type', null=True) parent = ToOneField('ietf.group.resources.GroupResource', 'parent', null=True) ad = ToOneField(PersonResource, 'ad', null=True) charter = ToOneField('ietf.doc.resources.DocumentResource', 'charter', null=True) unused_states = ToManyField('ietf.doc.resources.StateResource', 'unused_states', null=True) unused_tags = ToManyField(DocTagNameResource, 'unused_tags', null=True) description = CharField(attribute='get_description') class Meta: cache = SimpleCache() queryset = Group.objects.all() serializer = api.Serializer() #resource_name = 'group' filtering = { "id": ALL, "time": ALL, "name": ALL, "description": ALL, "list_email": ALL, "list_subscribe": ALL, "list_archive": ALL, "comments": ALL, "acronym": ALL, "state": ALL_WITH_RELATIONS, "type": ALL_WITH_RELATIONS, "parent": ALL_WITH_RELATIONS, "ad": ALL_WITH_RELATIONS, "charter": ALL_WITH_RELATIONS, "unused_states": ALL_WITH_RELATIONS, "unused_tags": ALL_WITH_RELATIONS, }
class VersionResource(Resource): identifier = CharField(attribute='identifier') class Meta: resource_name = 'version' allowed_methods = ['get'] object_class = Version include_resource_uri = False def detail_uri_kwargs(self, bundle_or_obj): kwargs = {} if isinstance(bundle_or_obj, Bundle): kwargs['pk'] = bundle_or_obj.obj.identifier else: kwargs['pk'] = bundle_or_obj['identifier'] return kwargs def get_object_list(self, bundle, **kwargs): return [Version(identifier=settings.VERSION)] def obj_get_list(self, bundle, **kwargs): return self.get_object_list(bundle, **kwargs)
class PackageResource(ChromaModelResource): """ Represents a particular version of a package. Includes which servers have this package installed, and on which servers this package is available. Filter by ``host`` to obtain a report including only packages which are installed on or available to a particular host. """ class Meta: queryset = PackageVersion.objects.select_related( 'packageinstallation').select_related( 'packageavailability').select_related('package') resource_name = 'package' fields = [ 'name', 'epoch', 'version', 'release', 'arch', 'installed_hosts', 'available_hosts' ] authentication = AnonymousAuthentication() authorization = DjangoAuthorization() ordering = ['name'] list_allowed_methods = ['get'] detail_allowed_methods = [] filtering = {'host': ['exact']} name = CharField(help_text="Name of the package, for example \"lustre\"") # epoch = IntegerField() # version = CharField() # release = CharField() # arch = CharField() installed_hosts = ToManyField( HostResource, attribute=lambda bundle: ManagedHost.objects.filter( packageinstallation__package_version=bundle.obj), null=True, help_text="List of URIs of servers on which this package is installed") available_hosts = ToManyField( HostResource, attribute=lambda bundle: ManagedHost.objects.filter( packageavailability__package_version=bundle.obj), null=True, help_text="List of URIs of servers on which this package is available") def apply_filters(self, request, applicable_filters): if 'host' in request.GET: host = ManagedHost.objects.get(pk=request.GET['host']) return PackageVersion.objects.filter( Q(packageinstallation__host=host) | Q(packageavailability__host=host)) else: return PackageVersion.objects.all() def dehydrate_name(self, bundle): return bundle.obj.package.name def dehydrate_epoch(self, bundle): return bundle.obj.epoch def dehydrate_arch(self, bundle): return bundle.obj.arch def dehydrate_version(self, bundle): return bundle.obj.version def dehydrate_release(self, bundle): return bundle.obj.release
class CreativeResource(ProtectedModelResource): class Meta: resource_name = 'creative' allowed_methods = ('get', 'post', 'get', 'put', 'delete') always_return_data = True filtering = { 'destination': ( 'exact', 'startswith', ), } queryset = Creative.objects_visible.all() authorization = Auth('owner') fields = ('name', 'width', 'height', 'api_data', 'destination') validation = CreativeValidation() id = IntegerField('id', readonly=True) size = ListField('size', readonly=True) type = CharField(readonly=True) status = CharField('appnexus_status', readonly=True) api_data = CharField('api_data') vast_url = CharField('vast_url', readonly=True, null=True) to_audit = BooleanField('to_audit', readonly=True, null=True) fb_title = CharField('title', null=True) fb_body = CharField('body', null=True) fb_message = CharField('message', null=True) fb_domain = CharField('domain', null=True) fb_brand_page = IntegerField('brand_id', null=True) def prepend_urls(self): return [ url(r"^{0}/audit/(?P<creative_id>[\d]+)$".format( self._meta.resource_name, ), self.wrap_view('manual_audit'), name="creative_manual_audit"), ] def manual_audit(self, request, creative_id, **kwargs): """ Manual audit api view. :param request: request object :param int creative_id: creative which we want to send to audit Returns detail response. """ creative = Creative.objects.get(id=creative_id) creative.to_audit = True creative.save() return self.get_detail(request, pk=creative_id) def dehydrate_destination(self, bundle): return bundle.obj.get_destination_display() def dehydrate(self, bundle): creative = bundle.obj # get type based on class name bundle.data['type'] = creative.type bundle.data['status'] = creative.state.status bundle.data['is_auditable'] = creative.is_auditable if creative.is_facebook_destination(verify_is_newsfeed=True): bundle.data[ 'fb_brand_page_access'] = creative.brand.appnexus_access_status if creative.type == 'Video': bundle.data['liverail_status'] = creative.liverail_status else: bundle.data['liverail_status'] = '' # If facebook creative was added to strategy, # Add information about strategy and campaign if creative.is_facebook_destination(): # For facebook creatives there is only one advert advert = creative.advert_set.filter( is_deleted=False, strategy__is_deleted=False, strategy__campaign__is_deleted=False).first() if advert: strategy = advert.strategy campaign = strategy.campaign bundle.data['strategy'] = strategy.name bundle.data['campaign'] = campaign.name return bundle def hydrate_destination(self, bundle): bundle.data['destination'] = DESTINATION[bundle.data['destination']] return bundle def hydrate_fb_brand_page(self, bundle): """ Clear creative brand page if it is not facebook newsfeed. """ if bundle.data['destination'] != 'facebook_newsfeed': bundle.data['fb_brand_page'] = None return bundle def hydrate(self, bundle): # A bug in Tastypie: on update, hydrate is called 2 times, # once with obj.id == None and method == 'PUT' # We should create an object only if method is POST if not bundle.obj.id and bundle.request.method == 'POST': bundle.obj = creative_factory(bundle.data['type'], owner=bundle.request.user.account) return bundle
class UploadedLayerResource(ModelResource): """ API for accessing UploadedData. """ geonode_layer = DictField(attribute='layer_data', readonly=True, null=True) configuration_options = DictField(attribute='configuration_options', null=True) fields = ListField(attribute='fields') status = CharField(attribute='status', readonly=True, null=True) class Meta: queryset = UploadLayer.objects.all() resource_name = 'data-layers' allowed_methods = ['get'] filtering = {'id': ALL} authentication = SessionAuthentication() def get_object_list(self, request): """ Filters the list view by the current user. """ return super( UploadedLayerResource, self).get_object_list(request).filter(upload__user=request.user.id) def import_layer(self, request, **kwargs): """ Imports a layer """ self.method_check(request, allowed=['post']) b = Bundle() b.request = request try: obj = self.obj_get(b, pk=kwargs.get('pk')) except UploadLayer.DoesNotExist: raise ImmediateHttpResponse(response=http.HttpNotFound()) configuration_options = request.POST.get('configurationOptions') if 'application/json' in request.META.get('CONTENT_TYPE', ''): configuration_options = json.loads(request.body) if isinstance(configuration_options, dict): obj.configuration_options = configuration_options obj.save() configuration_options = [configuration_options] if not configuration_options: raise ImmediateHttpResponse( response=http.HttpBadRequest('Configuration options missing.')) uploaded_file = obj.upload.uploadfile_set.first() import_result = import_object.delay( uploaded_file.id, configuration_options=configuration_options) # query the db again for this object since it may have been updated during the import obj = self.obj_get(b, pk=kwargs.get('pk')) obj.task_id = import_result.id obj.save() return self.create_response(request, {'task': obj.task_id}) def prepend_urls(self): return [ url(r"^(?P<resource_name>{0})/(?P<pk>\w[\w/-]*)/configure{1}$". format(self._meta.resource_name, trailing_slash()), self.wrap_view('import_layer'), name="importer_configure"), ]
class UploadedLayerResource(ModelResource): """ API for accessing UploadedData. """ geonode_layer = DictField(attribute='layer_data', readonly=True, null=True) configuration_options = DictField(attribute='configuration_options', null=True) fields = ListField(attribute='fields') status = CharField(attribute='status', readonly=True, null=True) file_type = CharField(attribute='file_type', readonly=True) file_name = CharField(attribute='file_name', readonly=True) layer_name = CharField(attribute='layer_name', readonly=True) class Meta: queryset = UploadLayer.objects.all() resource_name = 'data-layers' allowed_methods = ['get'] filtering = {'id': ALL} authentication = SessionAuthentication() def get_object_list(self, request): """ Filters the list view by the current user. """ return super(UploadedLayerResource, self).get_object_list(request).filter(upload__user=request.user.id) def clean_configuration_options(self, request, obj, configuration_options): return configuration_options def import_layer(self, request, pk=None, **kwargs): """Imports a layer """ self.method_check(request, allowed=['post']) bundle = Bundle(request=request) try: obj = self.obj_get(bundle, pk=pk) except UploadLayer.DoesNotExist: raise ImmediateHttpResponse(response=http.HttpNotFound()) configuration_options = request.POST.get('configurationOptions') if 'application/json' in request.META.get('CONTENT_TYPE', ''): configuration_options = json.loads(request.body) if isinstance(configuration_options, list) and len(configuration_options) == 1: configuration_options = configuration_options[0] if isinstance(configuration_options, dict): self.clean_configuration_options(request, obj, configuration_options) obj.configuration_options = configuration_options obj.save() if not configuration_options: raise ImmediateHttpResponse(response=http.HttpBadRequest('Configuration options missing.')) uploaded_file = obj.upload_file configuration_options.update({'upload_layer_id': pk}) import_result = import_object.delay(uploaded_file.id, configuration_options=configuration_options) task_id = getattr(import_result, 'id', None) # The task id will be useless if no backend is configured or a non-persistent backend is used. return self.create_response(request, {'task': task_id}) def prepend_urls(self): return [url(r"^(?P<resource_name>{0})/(?P<pk>\w[\w/-]*)/configure{1}$".format(self._meta.resource_name, trailing_slash()), self.wrap_view('import_layer'), name="importer_configure"), ]