How to use the geonode.base.models.ResourceBase function in GeoNode

To help you get started, we’ve selected a few GeoNode examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github MapStory / mapstory / mapstory / mapstories / models.py View on Github external
import geonode
import json
import uuid

from django import core, db
from django.db.models import signals
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
# Redefining Map Model and adding additional fields


class MapStory(geonode.base.models.ResourceBase):

    @property
    def chapters(self):
        return self.chapter_list.order_by('chapter_index')

    @property
    def get_chapter_info(self):
        chapter_list = []
        for chapter in self.chapters:

            storypins = chapter.storypin_set.all()
            storypin_list = []
            for storypin in storypins:
                storypin_dict = {
                    'title': storypin.title,
                    'content': storypin.content,
github GeoNode / geonode / geonode / base / management / commands / migrate_baseurl.py View on Github external
sld_url=Func(
                        F('sld_url'),Value(source_address),Value(target_address),function='replace'))
                print("Updated %s Styles" % _cnt)

                _cnt = Link.objects.filter(url__icontains=source_address).update(
                    url=Func(
                        F('url'),Value(source_address),Value(target_address),function='replace'))
                print("Updated %s Links" % _cnt)

                _cnt = ResourceBase.objects.filter(thumbnail_url__icontains=source_address).update(
                    thumbnail_url=Func(
                        F('thumbnail_url'),Value(source_address),Value(target_address),function='replace'))
                _cnt += ResourceBase.objects.filter(csw_anytext__icontains=source_address).update(
                    csw_anytext=Func(
                        F('csw_anytext'), Value(source_address), Value(target_address), function='replace'))
                _cnt += ResourceBase.objects.filter(metadata_xml__icontains=source_address).update(
                    metadata_xml=Func(
                        F('metadata_xml'), Value(source_address), Value(target_address), function='replace'))
                print("Updated %s ResourceBases" % _cnt)
            finally:
                # Reactivate GeoNode Signals
                print("Reactivating GeoNode Signals...")
                resignals()
                print("...done!")
github GeoNode / geonode / geonode / base / models.py View on Github external
class Link(models.Model):
    """Auxiliary model for storing links for resources.

       This helps avoiding the need for runtime lookups
       to the OWS server or the CSW Catalogue.

       There are four types of links:
        * original: For uploaded files (Shapefiles or GeoTIFFs)
        * data: For WFS and WCS links that allow access to raw data
        * image: For WMS and TMS links
        * metadata: For CSW links
        * OGC:WMS: for WMS service links
        * OGC:WFS: for WFS service links
        * OGC:WCS: for WCS service links
    """
    resource = models.ForeignKey(ResourceBase, blank=True, null=True)
    extension = models.CharField(
        max_length=255,
        help_text=_('For example "kml"'))
    link_type = models.CharField(
        max_length=255, choices=[
            (x, x) for x in LINK_TYPES])
    name = models.CharField(max_length=255, help_text=_(
        'For example "View in Google Earth"'))
    mime = models.CharField(max_length=255,
                            help_text=_('For example "text/xml"'))
    url = models.TextField(max_length=1000)

    objects = LinkManager()

    def __unicode__(self):
        return u"{0} link".format(self.link_type)
github MapStory / mapstory / mapstory / api / resourcebase_api.py View on Github external
class Meta(CommonMetaApi):
        queryset = ResourceBase.objects.polymorphic_queryset() \
            .distinct().order_by('-date')
        if settings.RESOURCE_PUBLISHING:
            queryset = queryset.filter(is_published=True)
        resource_name = 'base'
        excludes = ['csw_anytext', 'metadata_xml']


class FeaturedResourceBaseResource(CommonModelApi):

    """Only the featured resourcebases"""

    class Meta(CommonMetaApi):
        queryset = ResourceBase.objects.filter(featured=True).order_by('-date')
        if settings.RESOURCE_PUBLISHING:
            queryset = queryset.filter(is_published=True)
        resource_name = 'featured'


class MapStoryResource(CommonModelApi):
    """MapStory API"""

    chapters = fields.ListField(attribute='get_chapter_info')

    def prepend_urls(self):
        return [
            url(r"^(?P%s)/slug/(?P[\w\d_.-]+)/$" % self._meta.resource_name, self.wrap_view(
                'dispatch_detail'), name="api_dispatch_detail"),
        ]
github GeoNode / geonode / geonode / layers / models.py View on Github external
if user == self.owner or user.is_superuser:
            return
        if not do_local:
            from geonode.messaging import producer
            producer.viewing_layer(str(user), str(self.owner), self.id)

        else:
            Layer.objects.filter(id=self.id)\
                         .update(popular_count=models.F('popular_count') + 1)


class UploadSession(models.Model):

    """Helper class to keep track of uploads.
    """
    resource = models.ForeignKey(ResourceBase, blank=True, null=True)
    date = models.DateTimeField(auto_now=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    processed = models.BooleanField(default=False)
    error = models.TextField(blank=True, null=True)
    traceback = models.TextField(blank=True, null=True)
    context = models.TextField(blank=True, null=True)

    def successful(self):
        return self.processed and self.errors is None

    def __unicode__(self):
        try:
            _s = '[Upload session-id: {}] - {}'.format(self.id, self.resource.title)
        except BaseException:
            _s = '[Upload session-id: {}]'.format(self.id)
        return u"{0}".format(_s)
github GeoNode / geonode / geonode / services / models.py View on Github external
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from geonode.base.models import ResourceBase
from geonode.people.enumerations import ROLE_VALUES
try:
    from urllib.parse import urljoin
except ImportError:
    # Python 2 compatibility
    from urlparse import urljoin

from . import enumerations

logger = logging.getLogger("geonode.services")


class Service(ResourceBase):
    """Service Class to represent remote Geo Web Services"""

    type = models.CharField(
        max_length=10,
        choices=enumerations.SERVICE_TYPES
    )
    method = models.CharField(
        max_length=1,
        choices=(
            (enumerations.LOCAL, _('Local')),
            (enumerations.CASCADED, _('Cascaded')),
            (enumerations.HARVESTED, _('Harvested')),
            (enumerations.INDEXED, _('Indexed')),
            (enumerations.LIVE, _('Live')),
            (enumerations.OPENGEOPORTAL, _('OpenGeoPortal'))
        )
github cartologic / cartoview / cartoview / cartoview_api / rest.py View on Github external
request).exclude(
            id__in=__inactive_apps_instances)

        return active_app_instances


class AllResourcesResource(ModelResource):
    type = fields.CharField(null=False, blank=False)
    app = fields.DictField(null=True, blank=False)
    urls = fields.DictField(null=False, blank=False)
    owner = fields.ToOneField(OwnersResource, 'owner', full=True)
    thumbnail_url = fields.CharField(null=True, blank=True)

    class Meta:
        resource_name = 'all_resources'
        queryset = ResourceBase.objects.distinct()
        fields = ['id', 'title', 'abstract',
                  'type', 'featured', 'owner__username', 'app', 'owner',
                  'urls', 'thumbnail_url']
        filtering = {
            'id': ALL,
            'title': ALL,
            'abstract': ALL,
            'featured': ALL,
            'owner': ALL_WITH_RELATIONS
        }
        authorization = GeoNodeAuthorization()
        authentication = MultiAuthentication(
            SessionAuthentication(), GeonodeApiKeyAuthentication())

    def build_filters(self, filters=None):
        if filters is None:
github GeoNode / geonode / geonode / layers / utils.py View on Github external
valid_x = True
            valid_y = True

        image = None

        if valid_x and valid_y:
            Link.objects.get_or_create(resource=instance.get_self_resource(),
                                       url=thumbnail_remote_url,
                                       defaults=dict(
                                           extension='png',
                                           name="Remote Thumbnail",
                                           mime='image/png',
                                           link_type='image',
            )
            )
            ResourceBase.objects.filter(id=instance.id) \
                .update(thumbnail_url=thumbnail_remote_url)

            # Download thumbnail and save it locally.
            if not ogc_client:
                ogc_client = http_client

            if ogc_client:
                if check_ogc_backend(geoserver.BACKEND_PACKAGE):
                    if image is None:
                        request_body = {
                            'width': width,
                            'height': height
                        }
                        if instance.bbox and \
                        (not thumbnail_create_url or 'bbox' not in thumbnail_create_url):
                            instance_bbox = instance.bbox[0:4]
github GeoNode / geonode / geonode / search / models.py View on Github external
def filter_by_period(model, q, start, end, user=None):
    '''modify the query to filter the given model for dates between start and end
    start, end - iso str ('-5000-01-01T12:00:00Z')
    '''

    parse = lambda v: datetime.strptime(v, iso_fmt)  
    if issubclass(model, ResourceBase) and not user:
        if start:
            q = q.filter(date__gte = parse(start))
        if end:    
            q = q.filter(date__lte = parse(end))
    else:
        # @todo handle map and/or users - either directly if implemented or ...
        # this will effectively short-circuit the query at this point
        q = q.none()
    return q
github MapStory / mapstory / mapstory / search / elasticsearch_backend.py View on Github external
def remove(self, obj_or_string, commit=True):
        doc_id = get_identifier(obj_or_string)

        # django-haystack default to using namespaced ids for objects like layers.layer.83 but the GeoNode SearchIndexes
        # override the default ids with ResourceBase ids.
        if isinstance(obj_or_string, ResourceBase):
            doc_id = getattr(obj_or_string, 'id')

        if not self.setup_complete:
            try:
                self.setup()
            except elasticsearch.TransportError as e:
                if not self.silently_fail:
                    raise

                self.log.error(
                    "Failed to remove document '%s' from Elasticsearch: %s", doc_id, e)
                return

        try:
            self.conn.delete(index=self.index_name,
                             doc_type='modelresult', id=doc_id, ignore=404)