hash
stringlengths
64
64
content
stringlengths
0
1.51M
8539e555af85440f87e6536e3644f608a8710d5886277c7279968f47baa9591d
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("sites", "0001_initial"), ] operations = [ migrations.CreateModel( name="FlatPage", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ( "url", models.CharField(max_length=100, verbose_name="URL", db_index=True), ), ("title", models.CharField(max_length=200, verbose_name="title")), ("content", models.TextField(verbose_name="content", blank=True)), ( "enable_comments", models.BooleanField(default=False, verbose_name="enable comments"), ), ( "template_name", models.CharField( help_text=( "Example: “flatpages/contact_page.html”. If this isn’t " "provided, the system will use “flatpages/default.html”." ), max_length=70, verbose_name="template name", blank=True, ), ), ( "registration_required", models.BooleanField( default=False, help_text=( "If this is checked, only logged-in users will be able to " "view the page." ), verbose_name="registration required", ), ), ( "sites", models.ManyToManyField(to="sites.Site", verbose_name="sites"), ), ], options={ "ordering": ["url"], "db_table": "django_flatpage", "verbose_name": "flat page", "verbose_name_plural": "flat pages", }, bases=(models.Model,), ), ]
407facbb3b283c8312ae0c8747d3bcb8e7667c8901bffc372ccfa119f42f9d4f
from django import template from django.conf import settings from django.contrib.flatpages.models import FlatPage from django.contrib.sites.shortcuts import get_current_site register = template.Library() class FlatpageNode(template.Node): def __init__(self, context_name, starts_with=None, user=None): self.context_name = context_name if starts_with: self.starts_with = template.Variable(starts_with) else: self.starts_with = None if user: self.user = template.Variable(user) else: self.user = None def render(self, context): if "request" in context: site_pk = get_current_site(context["request"]).pk else: site_pk = settings.SITE_ID flatpages = FlatPage.objects.filter(sites__id=site_pk) # If a prefix was specified, add a filter if self.starts_with: flatpages = flatpages.filter( url__startswith=self.starts_with.resolve(context) ) # If the provided user is not authenticated, or no user # was provided, filter the list to only public flatpages. if self.user: user = self.user.resolve(context) if not user.is_authenticated: flatpages = flatpages.filter(registration_required=False) else: flatpages = flatpages.filter(registration_required=False) context[self.context_name] = flatpages return "" @register.tag def get_flatpages(parser, token): """ Retrieve all flatpage objects available for the current site and visible to the specific user (or visible to all users if no user is specified). Populate the template context with them in a variable whose name is defined by the ``as`` clause. An optional ``for`` clause controls the user whose permissions are used in determining which flatpages are visible. An optional argument, ``starts_with``, limits the returned flatpages to those beginning with a particular base URL. This argument can be a variable or a string, as it resolves from the template context. Syntax:: {% get_flatpages ['url_starts_with'] [for user] as context_name %} Example usage:: {% get_flatpages as flatpages %} {% get_flatpages for someuser as flatpages %} {% get_flatpages '/about/' as about_pages %} {% get_flatpages prefix as about_pages %} {% get_flatpages '/about/' for someuser as about_pages %} """ bits = token.split_contents() syntax_message = ( "%(tag_name)s expects a syntax of %(tag_name)s " "['url_starts_with'] [for user] as context_name" % {"tag_name": bits[0]} ) # Must have at 3-6 bits in the tag if 3 <= len(bits) <= 6: # If there's an even number of bits, there's no prefix if len(bits) % 2 == 0: prefix = bits[1] else: prefix = None # The very last bit must be the context name if bits[-2] != "as": raise template.TemplateSyntaxError(syntax_message) context_name = bits[-1] # If there are 5 or 6 bits, there is a user defined if len(bits) >= 5: if bits[-4] != "for": raise template.TemplateSyntaxError(syntax_message) user = bits[-3] else: user = None return FlatpageNode(context_name, starts_with=prefix, user=user) else: raise template.TemplateSyntaxError(syntax_message)
3b2b927a1e87c5cb9145ee9d0ab24343cbc69c096b9e03bf8de7372cbdfc2a0d
import django.contrib.sites.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("sites", "0001_initial"), ] operations = [ migrations.AlterField( model_name="site", name="domain", field=models.CharField( max_length=100, unique=True, validators=[django.contrib.sites.models._simple_domain_name_validator], verbose_name="domain name", ), ), ]
792bb96a247c14f1254ef21b2deb9241972539ad13225b53ed7683ae825e8ce8
import django.contrib.sites.models from django.contrib.sites.models import _simple_domain_name_validator from django.db import migrations, models class Migration(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( name="Site", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ( "domain", models.CharField( max_length=100, verbose_name="domain name", validators=[_simple_domain_name_validator], ), ), ("name", models.CharField(max_length=50, verbose_name="display name")), ], options={ "ordering": ["domain"], "db_table": "django_site", "verbose_name": "site", "verbose_name_plural": "sites", }, bases=(models.Model,), managers=[ ("objects", django.contrib.sites.models.SiteManager()), ], ), ]
ebe34a74f28223ed9e267424b291ed2d5e29c052f1b7c082d2844fcc28da6ba9
import django.contrib.contenttypes.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( name="ContentType", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("name", models.CharField(max_length=100)), ("app_label", models.CharField(max_length=100)), ( "model", models.CharField( max_length=100, verbose_name="python model class name" ), ), ], options={ "ordering": ("name",), "db_table": "django_content_type", "verbose_name": "content type", "verbose_name_plural": "content types", }, bases=(models.Model,), managers=[ ("objects", django.contrib.contenttypes.models.ContentTypeManager()), ], ), migrations.AlterUniqueTogether( name="contenttype", unique_together={("app_label", "model")}, ), ]
2f60c6035c7e6523f84ebeddf63ab5cac24ebd1ee75a1ccc800935345a58c465
from django.db import migrations, models def add_legacy_name(apps, schema_editor): ContentType = apps.get_model("contenttypes", "ContentType") for ct in ContentType.objects.all(): try: ct.name = apps.get_model(ct.app_label, ct.model)._meta.object_name except LookupError: ct.name = ct.model ct.save() class Migration(migrations.Migration): dependencies = [ ("contenttypes", "0001_initial"), ] operations = [ migrations.AlterModelOptions( name="contenttype", options={ "verbose_name": "content type", "verbose_name_plural": "content types", }, ), migrations.AlterField( model_name="contenttype", name="name", field=models.CharField(max_length=100, null=True), ), migrations.RunPython( migrations.RunPython.noop, add_legacy_name, hints={"model_name": "contenttype"}, ), migrations.RemoveField( model_name="contenttype", name="name", ), ]
6551d5240622fe30885f1594652931ab42031027ba6ef6c5b166b2aea6eeb5f7
from django.apps import apps as global_apps from django.db import DEFAULT_DB_ALIAS, IntegrityError, migrations, router, transaction class RenameContentType(migrations.RunPython): def __init__(self, app_label, old_model, new_model): self.app_label = app_label self.old_model = old_model self.new_model = new_model super().__init__(self.rename_forward, self.rename_backward) def _rename(self, apps, schema_editor, old_model, new_model): ContentType = apps.get_model("contenttypes", "ContentType") db = schema_editor.connection.alias if not router.allow_migrate_model(db, ContentType): return try: content_type = ContentType.objects.db_manager(db).get_by_natural_key( self.app_label, old_model ) except ContentType.DoesNotExist: pass else: content_type.model = new_model try: with transaction.atomic(using=db): content_type.save(using=db, update_fields={"model"}) except IntegrityError: # Gracefully fallback if a stale content type causes a # conflict as remove_stale_contenttypes will take care of # asking the user what should be done next. content_type.model = old_model else: # Clear the cache as the `get_by_natural_key()` call will cache # the renamed ContentType instance by its old model name. ContentType.objects.clear_cache() def rename_forward(self, apps, schema_editor): self._rename(apps, schema_editor, self.old_model, self.new_model) def rename_backward(self, apps, schema_editor): self._rename(apps, schema_editor, self.new_model, self.old_model) def inject_rename_contenttypes_operations( plan=None, apps=global_apps, using=DEFAULT_DB_ALIAS, **kwargs ): """ Insert a `RenameContentType` operation after every planned `RenameModel` operation. """ if plan is None: return # Determine whether or not the ContentType model is available. try: ContentType = apps.get_model("contenttypes", "ContentType") except LookupError: available = False else: if not router.allow_migrate_model(using, ContentType): return available = True for migration, backward in plan: if (migration.app_label, migration.name) == ("contenttypes", "0001_initial"): # There's no point in going forward if the initial contenttypes # migration is unapplied as the ContentType model will be # unavailable from this point. if backward: break else: available = True continue # The ContentType model is not available yet. if not available: continue inserts = [] for index, operation in enumerate(migration.operations): if isinstance(operation, migrations.RenameModel): operation = RenameContentType( migration.app_label, operation.old_name_lower, operation.new_name_lower, ) inserts.append((index + 1, operation)) for inserted, (index, operation) in enumerate(inserts): migration.operations.insert(inserted + index, operation) def get_contenttypes_and_models(app_config, using, ContentType): if not router.allow_migrate_model(using, ContentType): return None, None ContentType.objects.clear_cache() content_types = { ct.model: ct for ct in ContentType.objects.using(using).filter(app_label=app_config.label) } app_models = {model._meta.model_name: model for model in app_config.get_models()} return content_types, app_models def create_contenttypes( app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, apps=global_apps, **kwargs, ): """ Create content types for models in the given app. """ if not app_config.models_module: return app_label = app_config.label try: app_config = apps.get_app_config(app_label) ContentType = apps.get_model("contenttypes", "ContentType") except LookupError: return content_types, app_models = get_contenttypes_and_models( app_config, using, ContentType ) if not app_models: return cts = [ ContentType( app_label=app_label, model=model_name, ) for (model_name, model) in app_models.items() if model_name not in content_types ] ContentType.objects.using(using).bulk_create(cts) if verbosity >= 2: for ct in cts: print("Adding content type '%s | %s'" % (ct.app_label, ct.model))
ae535338315ee6bce82f5e9a8f023d2a673d089bef934a3a17e9bb54c0ee78c1
import itertools from django.apps import apps from django.contrib.contenttypes.models import ContentType from django.core.management import BaseCommand from django.db import DEFAULT_DB_ALIAS, router from django.db.models.deletion import Collector class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( "--noinput", "--no-input", action="store_false", dest="interactive", help="Tells Django to NOT prompt the user for input of any kind.", ) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, help='Nominates the database to use. Defaults to the "default" database.', ) parser.add_argument( "--include-stale-apps", action="store_true", default=False, help=( "Deletes stale content types including ones from previously " "installed apps that have been removed from INSTALLED_APPS." ), ) def handle(self, **options): db = options["database"] include_stale_apps = options["include_stale_apps"] interactive = options["interactive"] verbosity = options["verbosity"] if not router.allow_migrate_model(db, ContentType): return ContentType.objects.clear_cache() apps_content_types = itertools.groupby( ContentType.objects.using(db).order_by("app_label", "model"), lambda obj: obj.app_label, ) for app_label, content_types in apps_content_types: if not include_stale_apps and app_label not in apps.app_configs: continue to_remove = [ct for ct in content_types if ct.model_class() is None] # Confirm that the content type is stale before deletion. using = router.db_for_write(ContentType) if to_remove: if interactive: ct_info = [] for ct in to_remove: ct_info.append( " - Content type for %s.%s" % (ct.app_label, ct.model) ) collector = NoFastDeleteCollector(using=using, origin=ct) collector.collect([ct]) for obj_type, objs in collector.data.items(): if objs != {ct}: ct_info.append( " - %s %s object(s)" % ( len(objs), obj_type._meta.label, ) ) content_type_display = "\n".join(ct_info) self.stdout.write( """Some content types in your database are stale and can be deleted. Any objects that depend on these content types will also be deleted. The content types and dependent objects that would be deleted are: %s This list doesn't include any cascade deletions to data outside of Django's models (uncommon). Are you sure you want to delete these content types? If you're unsure, answer 'no'.""" % content_type_display ) ok_to_delete = input("Type 'yes' to continue, or 'no' to cancel: ") else: ok_to_delete = "yes" if ok_to_delete == "yes": for ct in to_remove: if verbosity >= 2: self.stdout.write( "Deleting stale content type '%s | %s'" % (ct.app_label, ct.model) ) ct.delete() else: if verbosity >= 2: self.stdout.write("Stale content types remain.") class NoFastDeleteCollector(Collector): def can_fast_delete(self, *args, **kwargs): """ Always load related objects to display them when showing confirmation. """ return False
e2d733560349c6633968486b0f0fc47ea38178fcecc6e26695c87094c1475ab5
import django.contrib.sessions.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( name="Session", fields=[ ( "session_key", models.CharField( max_length=40, serialize=False, verbose_name="session key", primary_key=True, ), ), ("session_data", models.TextField(verbose_name="session data")), ( "expire_date", models.DateTimeField(verbose_name="expire date", db_index=True), ), ], options={ "abstract": False, "db_table": "django_session", "verbose_name": "session", "verbose_name_plural": "sessions", }, managers=[ ("objects", django.contrib.sessions.models.SessionManager()), ], ), ]
d3a4a01c93b2e3909e2fc588e22b3d826c9f57f08227033a892a052ea6844e91
import datetime import logging import os import shutil import tempfile from django.conf import settings from django.contrib.sessions.backends.base import ( VALID_KEY_CHARS, CreateError, SessionBase, UpdateError, ) from django.contrib.sessions.exceptions import InvalidSessionKey from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation from django.utils import timezone class SessionStore(SessionBase): """ Implement a file based session store. """ def __init__(self, session_key=None): self.storage_path = self._get_storage_path() self.file_prefix = settings.SESSION_COOKIE_NAME super().__init__(session_key) @classmethod def _get_storage_path(cls): try: return cls._storage_path except AttributeError: storage_path = ( getattr(settings, "SESSION_FILE_PATH", None) or tempfile.gettempdir() ) # Make sure the storage path is valid. if not os.path.isdir(storage_path): raise ImproperlyConfigured( "The session storage path %r doesn't exist. Please set your" " SESSION_FILE_PATH setting to an existing directory in which" " Django can store session data." % storage_path ) cls._storage_path = storage_path return storage_path def _key_to_file(self, session_key=None): """ Get the file associated with this session key. """ if session_key is None: session_key = self._get_or_create_session_key() # Make sure we're not vulnerable to directory traversal. Session keys # should always be md5s, so they should never contain directory # components. if not set(session_key).issubset(VALID_KEY_CHARS): raise InvalidSessionKey("Invalid characters in session key") return os.path.join(self.storage_path, self.file_prefix + session_key) def _last_modification(self): """ Return the modification time of the file storing the session's content. """ modification = os.stat(self._key_to_file()).st_mtime tz = timezone.utc if settings.USE_TZ else None return datetime.datetime.fromtimestamp(modification, tz=tz) def _expiry_date(self, session_data): """ Return the expiry time of the file storing the session's content. """ return session_data.get("_session_expiry") or ( self._last_modification() + datetime.timedelta(seconds=self.get_session_cookie_age()) ) def load(self): session_data = {} try: with open(self._key_to_file(), encoding="ascii") as session_file: file_data = session_file.read() # Don't fail if there is no data in the session file. # We may have opened the empty placeholder file. if file_data: try: session_data = self.decode(file_data) except (EOFError, SuspiciousOperation) as e: if isinstance(e, SuspiciousOperation): logger = logging.getLogger( "django.security.%s" % e.__class__.__name__ ) logger.warning(str(e)) self.create() # Remove expired sessions. expiry_age = self.get_expiry_age(expiry=self._expiry_date(session_data)) if expiry_age <= 0: session_data = {} self.delete() self.create() except (OSError, SuspiciousOperation): self._session_key = None return session_data def create(self): while True: self._session_key = self._get_new_session_key() try: self.save(must_create=True) except CreateError: continue self.modified = True return def save(self, must_create=False): if self.session_key is None: return self.create() # Get the session data now, before we start messing # with the file it is stored within. session_data = self._get_session(no_load=must_create) session_file_name = self._key_to_file() try: # Make sure the file exists. If it does not already exist, an # empty placeholder file is created. flags = os.O_WRONLY | getattr(os, "O_BINARY", 0) if must_create: flags |= os.O_EXCL | os.O_CREAT fd = os.open(session_file_name, flags) os.close(fd) except FileNotFoundError: if not must_create: raise UpdateError except FileExistsError: if must_create: raise CreateError # Write the session file without interfering with other threads # or processes. By writing to an atomically generated temporary # file and then using the atomic os.rename() to make the complete # file visible, we avoid having to lock the session file, while # still maintaining its integrity. # # Note: Locking the session file was explored, but rejected in part # because in order to be atomic and cross-platform, it required a # long-lived lock file for each session, doubling the number of # files in the session storage directory at any given time. This # rename solution is cleaner and avoids any additional overhead # when reading the session data, which is the more common case # unless SESSION_SAVE_EVERY_REQUEST = True. # # See ticket #8616. dir, prefix = os.path.split(session_file_name) try: output_file_fd, output_file_name = tempfile.mkstemp( dir=dir, prefix=prefix + "_out_" ) renamed = False try: try: os.write(output_file_fd, self.encode(session_data).encode()) finally: os.close(output_file_fd) # This will atomically rename the file (os.rename) if the OS # supports it. Otherwise this will result in a shutil.copy2 # and os.unlink (for example on Windows). See #9084. shutil.move(output_file_name, session_file_name) renamed = True finally: if not renamed: os.unlink(output_file_name) except (EOFError, OSError): pass def exists(self, session_key): return os.path.exists(self._key_to_file(session_key)) def delete(self, session_key=None): if session_key is None: if self.session_key is None: return session_key = self.session_key try: os.unlink(self._key_to_file(session_key)) except OSError: pass def clean(self): pass @classmethod def clear_expired(cls): storage_path = cls._get_storage_path() file_prefix = settings.SESSION_COOKIE_NAME for session_file in os.listdir(storage_path): if not session_file.startswith(file_prefix): continue session_key = session_file[len(file_prefix) :] session = cls(session_key) # When an expired session is loaded, its file is removed, and a # new file is immediately created. Prevent this by disabling # the create() method. session.create = lambda: None session.load()
a84619366c96935a416ee5c65db4ec2ed4365edfc78284402f14d09b9e592f2d
import logging from django.contrib.sessions.backends.base import CreateError, SessionBase, UpdateError from django.core.exceptions import SuspiciousOperation from django.db import DatabaseError, IntegrityError, router, transaction from django.utils import timezone from django.utils.functional import cached_property class SessionStore(SessionBase): """ Implement database session store. """ def __init__(self, session_key=None): super().__init__(session_key) @classmethod def get_model_class(cls): # Avoids a circular import and allows importing SessionStore when # django.contrib.sessions is not in INSTALLED_APPS. from django.contrib.sessions.models import Session return Session @cached_property def model(self): return self.get_model_class() def _get_session_from_db(self): try: return self.model.objects.get( session_key=self.session_key, expire_date__gt=timezone.now() ) except (self.model.DoesNotExist, SuspiciousOperation) as e: if isinstance(e, SuspiciousOperation): logger = logging.getLogger("django.security.%s" % e.__class__.__name__) logger.warning(str(e)) self._session_key = None def load(self): s = self._get_session_from_db() return self.decode(s.session_data) if s else {} def exists(self, session_key): return self.model.objects.filter(session_key=session_key).exists() def create(self): while True: self._session_key = self._get_new_session_key() try: # Save immediately to ensure we have a unique entry in the # database. self.save(must_create=True) except CreateError: # Key wasn't unique. Try again. continue self.modified = True return def create_model_instance(self, data): """ Return a new instance of the session model object, which represents the current session state. Intended to be used for saving the session data to the database. """ return self.model( session_key=self._get_or_create_session_key(), session_data=self.encode(data), expire_date=self.get_expiry_date(), ) def save(self, must_create=False): """ Save the current session data to the database. If 'must_create' is True, raise a database error if the saving operation doesn't create a new entry (as opposed to possibly updating an existing entry). """ if self.session_key is None: return self.create() data = self._get_session(no_load=must_create) obj = self.create_model_instance(data) using = router.db_for_write(self.model, instance=obj) try: with transaction.atomic(using=using): obj.save( force_insert=must_create, force_update=not must_create, using=using ) except IntegrityError: if must_create: raise CreateError raise except DatabaseError: if not must_create: raise UpdateError raise def delete(self, session_key=None): if session_key is None: if self.session_key is None: return session_key = self.session_key try: self.model.objects.get(session_key=session_key).delete() except self.model.DoesNotExist: pass @classmethod def clear_expired(cls): cls.get_model_class().objects.filter(expire_date__lt=timezone.now()).delete()
c66f51b34648f0444fe9c67e37829d7d5c30dda5a25c2f0572073141635daeac
import logging import string from datetime import datetime, timedelta from django.conf import settings from django.core import signing from django.utils import timezone from django.utils.crypto import get_random_string from django.utils.module_loading import import_string # session_key should not be case sensitive because some backends can store it # on case insensitive file systems. VALID_KEY_CHARS = string.ascii_lowercase + string.digits class CreateError(Exception): """ Used internally as a consistent exception type to catch from save (see the docstring for SessionBase.save() for details). """ pass class UpdateError(Exception): """ Occurs if Django tries to update a session that was deleted. """ pass class SessionBase: """ Base class for all Session classes. """ TEST_COOKIE_NAME = "testcookie" TEST_COOKIE_VALUE = "worked" __not_given = object() def __init__(self, session_key=None): self._session_key = session_key self.accessed = False self.modified = False self.serializer = import_string(settings.SESSION_SERIALIZER) def __contains__(self, key): return key in self._session def __getitem__(self, key): return self._session[key] def __setitem__(self, key, value): self._session[key] = value self.modified = True def __delitem__(self, key): del self._session[key] self.modified = True @property def key_salt(self): return "django.contrib.sessions." + self.__class__.__qualname__ def get(self, key, default=None): return self._session.get(key, default) def pop(self, key, default=__not_given): self.modified = self.modified or key in self._session args = () if default is self.__not_given else (default,) return self._session.pop(key, *args) def setdefault(self, key, value): if key in self._session: return self._session[key] else: self.modified = True self._session[key] = value return value def set_test_cookie(self): self[self.TEST_COOKIE_NAME] = self.TEST_COOKIE_VALUE def test_cookie_worked(self): return self.get(self.TEST_COOKIE_NAME) == self.TEST_COOKIE_VALUE def delete_test_cookie(self): del self[self.TEST_COOKIE_NAME] def encode(self, session_dict): "Return the given session dictionary serialized and encoded as a string." return signing.dumps( session_dict, salt=self.key_salt, serializer=self.serializer, compress=True, ) def decode(self, session_data): try: return signing.loads( session_data, salt=self.key_salt, serializer=self.serializer ) except signing.BadSignature: logger = logging.getLogger("django.security.SuspiciousSession") logger.warning("Session data corrupted") except Exception: # ValueError, unpickling exceptions. If any of these happen, just # return an empty dictionary (an empty session). pass return {} def update(self, dict_): self._session.update(dict_) self.modified = True def has_key(self, key): return key in self._session def keys(self): return self._session.keys() def values(self): return self._session.values() def items(self): return self._session.items() def clear(self): # To avoid unnecessary persistent storage accesses, we set up the # internals directly (loading data wastes time, since we are going to # set it to an empty dict anyway). self._session_cache = {} self.accessed = True self.modified = True def is_empty(self): "Return True when there is no session_key and the session is empty." try: return not self._session_key and not self._session_cache except AttributeError: return True def _get_new_session_key(self): "Return session key that isn't being used." while True: session_key = get_random_string(32, VALID_KEY_CHARS) if not self.exists(session_key): return session_key def _get_or_create_session_key(self): if self._session_key is None: self._session_key = self._get_new_session_key() return self._session_key def _validate_session_key(self, key): """ Key must be truthy and at least 8 characters long. 8 characters is an arbitrary lower bound for some minimal key security. """ return key and len(key) >= 8 def _get_session_key(self): return self.__session_key def _set_session_key(self, value): """ Validate session key on assignment. Invalid values will set to None. """ if self._validate_session_key(value): self.__session_key = value else: self.__session_key = None session_key = property(_get_session_key) _session_key = property(_get_session_key, _set_session_key) def _get_session(self, no_load=False): """ Lazily load session from storage (unless "no_load" is True, when only an empty dict is stored) and store it in the current instance. """ self.accessed = True try: return self._session_cache except AttributeError: if self.session_key is None or no_load: self._session_cache = {} else: self._session_cache = self.load() return self._session_cache _session = property(_get_session) def get_session_cookie_age(self): return settings.SESSION_COOKIE_AGE def get_expiry_age(self, **kwargs): """Get the number of seconds until the session expires. Optionally, this function accepts `modification` and `expiry` keyword arguments specifying the modification and expiry of the session. """ try: modification = kwargs["modification"] except KeyError: modification = timezone.now() # Make the difference between "expiry=None passed in kwargs" and # "expiry not passed in kwargs", in order to guarantee not to trigger # self.load() when expiry is provided. try: expiry = kwargs["expiry"] except KeyError: expiry = self.get("_session_expiry") if not expiry: # Checks both None and 0 cases return self.get_session_cookie_age() if not isinstance(expiry, (datetime, str)): return expiry if isinstance(expiry, str): expiry = datetime.fromisoformat(expiry) delta = expiry - modification return delta.days * 86400 + delta.seconds def get_expiry_date(self, **kwargs): """Get session the expiry date (as a datetime object). Optionally, this function accepts `modification` and `expiry` keyword arguments specifying the modification and expiry of the session. """ try: modification = kwargs["modification"] except KeyError: modification = timezone.now() # Same comment as in get_expiry_age try: expiry = kwargs["expiry"] except KeyError: expiry = self.get("_session_expiry") if isinstance(expiry, datetime): return expiry elif isinstance(expiry, str): return datetime.fromisoformat(expiry) expiry = expiry or self.get_session_cookie_age() return modification + timedelta(seconds=expiry) def set_expiry(self, value): """ Set a custom expiration for the session. ``value`` can be an integer, a Python ``datetime`` or ``timedelta`` object or ``None``. If ``value`` is an integer, the session will expire after that many seconds of inactivity. If set to ``0`` then the session will expire on browser close. If ``value`` is a ``datetime`` or ``timedelta`` object, the session will expire at that specific future time. If ``value`` is ``None``, the session uses the global session expiry policy. """ if value is None: # Remove any custom expiration for this session. try: del self["_session_expiry"] except KeyError: pass return if isinstance(value, timedelta): value = timezone.now() + value if isinstance(value, datetime): value = value.isoformat() self["_session_expiry"] = value def get_expire_at_browser_close(self): """ Return ``True`` if the session is set to expire when the browser closes, and ``False`` if there's an expiry date. Use ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry date/age, if there is one. """ if (expiry := self.get("_session_expiry")) is None: return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE return expiry == 0 def flush(self): """ Remove the current session data from the database and regenerate the key. """ self.clear() self.delete() self._session_key = None def cycle_key(self): """ Create a new session key, while retaining the current session data. """ data = self._session key = self.session_key self.create() self._session_cache = data if key: self.delete(key) # Methods that child classes must implement. def exists(self, session_key): """ Return True if the given session_key already exists. """ raise NotImplementedError( "subclasses of SessionBase must provide an exists() method" ) def create(self): """ Create a new session instance. Guaranteed to create a new object with a unique key and will have saved the result once (with empty data) before the method returns. """ raise NotImplementedError( "subclasses of SessionBase must provide a create() method" ) def save(self, must_create=False): """ Save the session data. If 'must_create' is True, create a new session object (or raise CreateError). Otherwise, only update an existing object and don't create one (raise UpdateError if needed). """ raise NotImplementedError( "subclasses of SessionBase must provide a save() method" ) def delete(self, session_key=None): """ Delete the session data under this key. If the key is None, use the current session key value. """ raise NotImplementedError( "subclasses of SessionBase must provide a delete() method" ) def load(self): """ Load the session data and return a dictionary. """ raise NotImplementedError( "subclasses of SessionBase must provide a load() method" ) @classmethod def clear_expired(cls): """ Remove expired sessions from the session store. If this operation isn't possible on a given backend, it should raise NotImplementedError. If it isn't necessary, because the backend has a built-in expiration mechanism, it should be a no-op. """ raise NotImplementedError("This backend does not support clear_expired().")
91e460cb90b2bee7e2128e00f75ce738a6d7e943b3cc7da1cdac39d54ccaff46
from django.contrib.sessions.backends.base import SessionBase from django.core import signing class SessionStore(SessionBase): def load(self): """ Load the data from the key itself instead of fetching from some external data store. Opposite of _get_session_key(), raise BadSignature if signature fails. """ try: return signing.loads( self.session_key, serializer=self.serializer, # This doesn't handle non-default expiry dates, see #19201 max_age=self.get_session_cookie_age(), salt="django.contrib.sessions.backends.signed_cookies", ) except Exception: # BadSignature, ValueError, or unpickling exceptions. If any of # these happen, reset the session. self.create() return {} def create(self): """ To create a new key, set the modified flag so that the cookie is set on the client for the current request. """ self.modified = True def save(self, must_create=False): """ To save, get the session key as a securely signed string and then set the modified flag so that the cookie is set on the client for the current request. """ self._session_key = self._get_session_key() self.modified = True def exists(self, session_key=None): """ This method makes sense when you're talking to a shared resource, but it doesn't matter when you're storing the information in the client's cookie. """ return False def delete(self, session_key=None): """ To delete, clear the session key and the underlying data structure and set the modified flag so that the cookie is set on the client for the current request. """ self._session_key = "" self._session_cache = {} self.modified = True def cycle_key(self): """ Keep the same data but with a new key. Call save() and it will automatically save a cookie with a new key at the end of the request. """ self.save() def _get_session_key(self): """ Instead of generating a random string, generate a secure url-safe base64-encoded string of data as our session key. """ return signing.dumps( self._session, compress=True, salt="django.contrib.sessions.backends.signed_cookies", serializer=self.serializer, ) @classmethod def clear_expired(cls): pass
a713e563d925387d0d0a1b7c399ac741ec3f52432b42528cb4828c2d822fd832
""" Cached, database-backed sessions. """ from django.conf import settings from django.contrib.sessions.backends.db import SessionStore as DBStore from django.core.cache import caches KEY_PREFIX = "django.contrib.sessions.cached_db" class SessionStore(DBStore): """ Implement cached, database backed sessions. """ cache_key_prefix = KEY_PREFIX def __init__(self, session_key=None): self._cache = caches[settings.SESSION_CACHE_ALIAS] super().__init__(session_key) @property def cache_key(self): return self.cache_key_prefix + self._get_or_create_session_key() def load(self): try: data = self._cache.get(self.cache_key) except Exception: # Some backends (e.g. memcache) raise an exception on invalid # cache keys. If this happens, reset the session. See #17810. data = None if data is None: s = self._get_session_from_db() if s: data = self.decode(s.session_data) self._cache.set( self.cache_key, data, self.get_expiry_age(expiry=s.expire_date) ) else: data = {} return data def exists(self, session_key): return ( session_key and (self.cache_key_prefix + session_key) in self._cache or super().exists(session_key) ) def save(self, must_create=False): super().save(must_create) self._cache.set(self.cache_key, self._session, self.get_expiry_age()) def delete(self, session_key=None): super().delete(session_key) if session_key is None: if self.session_key is None: return session_key = self.session_key self._cache.delete(self.cache_key_prefix + session_key) def flush(self): """ Remove the current session data from the database and regenerate the key. """ self.clear() self.delete(self.session_key) self._session_key = None
0f3e253a2ac4237652aef3969c07df429c80e774ee3e6dcc995d6ef23913fa12
from django.conf import settings from django.contrib.sessions.backends.base import CreateError, SessionBase, UpdateError from django.core.cache import caches KEY_PREFIX = "django.contrib.sessions.cache" class SessionStore(SessionBase): """ A cache-based session store. """ cache_key_prefix = KEY_PREFIX def __init__(self, session_key=None): self._cache = caches[settings.SESSION_CACHE_ALIAS] super().__init__(session_key) @property def cache_key(self): return self.cache_key_prefix + self._get_or_create_session_key() def load(self): try: session_data = self._cache.get(self.cache_key) except Exception: # Some backends (e.g. memcache) raise an exception on invalid # cache keys. If this happens, reset the session. See #17810. session_data = None if session_data is not None: return session_data self._session_key = None return {} def create(self): # Because a cache can fail silently (e.g. memcache), we don't know if # we are failing to create a new session because of a key collision or # because the cache is missing. So we try for a (large) number of times # and then raise an exception. That's the risk you shoulder if using # cache backing. for i in range(10000): self._session_key = self._get_new_session_key() try: self.save(must_create=True) except CreateError: continue self.modified = True return raise RuntimeError( "Unable to create a new session key. " "It is likely that the cache is unavailable." ) def save(self, must_create=False): if self.session_key is None: return self.create() if must_create: func = self._cache.add elif self._cache.get(self.cache_key) is not None: func = self._cache.set else: raise UpdateError result = func( self.cache_key, self._get_session(no_load=must_create), self.get_expiry_age(), ) if must_create and not result: raise CreateError def exists(self, session_key): return ( bool(session_key) and (self.cache_key_prefix + session_key) in self._cache ) def delete(self, session_key=None): if session_key is None: if self.session_key is None: return session_key = self.session_key self._cache.delete(self.cache_key_prefix + session_key) @classmethod def clear_expired(cls): pass
0949ff28a56bc06836666983716a2c05cd1016e269f211e978d442725a159355
from django.apps import apps from django.contrib.gis.db.models import GeometryField from django.contrib.sitemaps import Sitemap from django.db import models from django.urls import reverse class KMLSitemap(Sitemap): """ A minimal hook to produce KML sitemaps. """ geo_format = "kml" def __init__(self, locations=None): # If no locations specified, then we try to build for # every model in installed applications. self.locations = self._build_kml_sources(locations) def _build_kml_sources(self, sources): """ Go through the given sources and return a 3-tuple of the application label, module name, and field name of every GeometryField encountered in the sources. If no sources are provided, then all models. """ kml_sources = [] if sources is None: sources = apps.get_models() for source in sources: if isinstance(source, models.base.ModelBase): for field in source._meta.fields: if isinstance(field, GeometryField): kml_sources.append( ( source._meta.app_label, source._meta.model_name, field.name, ) ) elif isinstance(source, (list, tuple)): if len(source) != 3: raise ValueError( "Must specify a 3-tuple of (app_label, module_name, " "field_name)." ) kml_sources.append(source) else: raise TypeError("KML Sources must be a model or a 3-tuple.") return kml_sources def get_urls(self, page=1, site=None, protocol=None): """ This method is overridden so the appropriate `geo_format` attribute is placed on each URL element. """ urls = Sitemap.get_urls(self, page=page, site=site, protocol=protocol) for url in urls: url["geo_format"] = self.geo_format return urls def items(self): return self.locations def location(self, obj): return reverse( "django.contrib.gis.sitemaps.views.%s" % self.geo_format, kwargs={ "label": obj[0], "model": obj[1], "field_name": obj[2], }, ) class KMZSitemap(KMLSitemap): geo_format = "kmz"
4e38f4e7ba263957280b915bf084c461584b9b41dc563ad9d4c6f3fed2a80f50
# Geo-enabled Sitemap classes. from django.contrib.gis.sitemaps.kml import KMLSitemap, KMZSitemap __all__ = ["KMLSitemap", "KMZSitemap"]
0055756b2fa815fb450be22ccf378acf72401b31344ce087f29375730b60ef22
from django.apps import apps from django.contrib.gis.db.models import GeometryField from django.contrib.gis.db.models.functions import AsKML, Transform from django.contrib.gis.shortcuts import render_to_kml, render_to_kmz from django.core.exceptions import FieldDoesNotExist from django.db import DEFAULT_DB_ALIAS, connections from django.http import Http404 def kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB_ALIAS): """ This view generates KML for the given app label, model, and field name. The field name must be that of a geographic field. """ placemarks = [] try: klass = apps.get_model(label, model) except LookupError: raise Http404( 'You must supply a valid app label and module name. Got "%s.%s"' % (label, model) ) if field_name: try: field = klass._meta.get_field(field_name) if not isinstance(field, GeometryField): raise FieldDoesNotExist except FieldDoesNotExist: raise Http404("Invalid geometry field.") connection = connections[using] if connection.features.has_AsKML_function: # Database will take care of transformation. placemarks = klass._default_manager.using(using).annotate(kml=AsKML(field_name)) else: # If the database offers no KML method, we use the `kml` # attribute of the lazy geometry instead. placemarks = [] if connection.features.has_Transform_function: qs = klass._default_manager.using(using).annotate( **{"%s_4326" % field_name: Transform(field_name, 4326)} ) field_name += "_4326" else: qs = klass._default_manager.using(using).all() for mod in qs: mod.kml = getattr(mod, field_name).kml placemarks.append(mod) # Getting the render function and rendering to the correct. if compress: render = render_to_kmz else: render = render_to_kml return render("gis/kml/placemarks.kml", {"places": placemarks}) def kmz(request, label, model, field_name=None, using=DEFAULT_DB_ALIAS): """ Return KMZ for the given app label, model, and field name. """ return kml(request, label, model, field_name, compress=True, using=using)
a26d2b3cf0704a6bcde3f059a4492fa59a93e384b46fb4422692c04b69c8f7ea
""" This module contains useful utilities for GeoDjango. """ from django.contrib.gis.utils.ogrinfo import ogrinfo # NOQA from django.contrib.gis.utils.ogrinspect import mapping, ogrinspect # NOQA from django.contrib.gis.utils.srs import add_srs_entry # NOQA from django.core.exceptions import ImproperlyConfigured try: # LayerMapping requires DJANGO_SETTINGS_MODULE to be set, # and ImproperlyConfigured is raised if that's not the case. from django.contrib.gis.utils.layermapping import ( # NOQA LayerMapError, LayerMapping, ) except ImproperlyConfigured: pass
ea6dca691ccba19b50d0e4aba5191a1484178bd60e5d39107187aa61bd12d27c
""" This module includes some utility functions for inspecting the layout of a GDAL data source -- the functionality is analogous to the output produced by the `ogrinfo` utility. """ from django.contrib.gis.gdal import DataSource from django.contrib.gis.gdal.geometries import GEO_CLASSES def ogrinfo(data_source, num_features=10): """ Walk the available layers in the supplied `data_source`, displaying the fields for the first `num_features` features. """ # Checking the parameters. if isinstance(data_source, str): data_source = DataSource(data_source) elif isinstance(data_source, DataSource): pass else: raise Exception( "Data source parameter must be a string or a DataSource object." ) for i, layer in enumerate(data_source): print("data source : %s" % data_source.name) print("==== layer %s" % i) print(" shape type: %s" % GEO_CLASSES[layer.geom_type.num].__name__) print(" # features: %s" % len(layer)) print(" srs: %s" % layer.srs) extent_tup = layer.extent.tuple print(" extent: %s - %s" % (extent_tup[0:2], extent_tup[2:4])) print("Displaying the first %s features ====" % num_features) width = max(*map(len, layer.fields)) fmt = " %%%ss: %%s" % width for j, feature in enumerate(layer[:num_features]): print("=== Feature %s" % j) for fld_name in layer.fields: type_name = feature[fld_name].type_name output = fmt % (fld_name, type_name) val = feature.get(fld_name) if val: if isinstance(val, str): val_fmt = ' ("%s")' else: val_fmt = " (%s)" output += val_fmt % val else: output += " (None)" print(output)
9f129dd5cb9f8db3fceae25cb1a35bd5cde7f4803ebb2e25b508cb1a03e30751
""" This module is for inspecting OGR data sources and generating either models for GeoDjango and/or mapping dictionaries for use with the `LayerMapping` utility. """ from django.contrib.gis.gdal import DataSource from django.contrib.gis.gdal.field import ( OFTDate, OFTDateTime, OFTInteger, OFTInteger64, OFTReal, OFTString, OFTTime, ) def mapping(data_source, geom_name="geom", layer_key=0, multi_geom=False): """ Given a DataSource, generate a dictionary that may be used for invoking the LayerMapping utility. Keyword Arguments: `geom_name` => The name of the geometry field to use for the model. `layer_key` => The key for specifying which layer in the DataSource to use; defaults to 0 (the first layer). May be an integer index or a string identifier for the layer. `multi_geom` => Boolean (default: False) - specify as multigeometry. """ if isinstance(data_source, str): # Instantiating the DataSource from the string. data_source = DataSource(data_source) elif isinstance(data_source, DataSource): pass else: raise TypeError( "Data source parameter must be a string or a DataSource object." ) # Creating the dictionary. _mapping = {} # Generating the field name for each field in the layer. for field in data_source[layer_key].fields: mfield = field.lower() if mfield[-1:] == "_": mfield += "field" _mapping[mfield] = field gtype = data_source[layer_key].geom_type if multi_geom: gtype.to_multi() _mapping[geom_name] = str(gtype).upper() return _mapping def ogrinspect(*args, **kwargs): """ Given a data source (either a string or a DataSource object) and a string model name this function will generate a GeoDjango model. Usage: >>> from django.contrib.gis.utils import ogrinspect >>> ogrinspect('/path/to/shapefile.shp','NewModel') ...will print model definition to stout or put this in a Python script and use to redirect the output to a new model like: $ python generate_model.py > myapp/models.py # generate_model.py from django.contrib.gis.utils import ogrinspect shp_file = 'data/mapping_hacks/world_borders.shp' model_name = 'WorldBorders' print(ogrinspect(shp_file, model_name, multi_geom=True, srid=4326, geom_name='shapes', blank=True)) Required Arguments `datasource` => string or DataSource object to file pointer `model name` => string of name of new model class to create Optional Keyword Arguments `geom_name` => For specifying the model name for the Geometry Field. Otherwise will default to `geom` `layer_key` => The key for specifying which layer in the DataSource to use; defaults to 0 (the first layer). May be an integer index or a string identifier for the layer. `srid` => The SRID to use for the Geometry Field. If it can be determined, the SRID of the datasource is used. `multi_geom` => Boolean (default: False) - specify as multigeometry. `name_field` => String - specifies a field name to return for the __str__() method (which will be generated if specified). `imports` => Boolean (default: True) - set to False to omit the `from django.contrib.gis.db import models` code from the autogenerated models thus avoiding duplicated imports when building more than one model by batching ogrinspect() `decimal` => Boolean or sequence (default: False). When set to True all generated model fields corresponding to the `OFTReal` type will be `DecimalField` instead of `FloatField`. A sequence of specific field names to generate as `DecimalField` may also be used. `blank` => Boolean or sequence (default: False). When set to True all generated model fields will have `blank=True`. If the user wants to give specific fields to have blank, then a list/tuple of OGR field names may be used. `null` => Boolean (default: False) - When set to True all generated model fields will have `null=True`. If the user wants to specify give specific fields to have null, then a list/tuple of OGR field names may be used. Note: Call the _ogrinspect() helper to do the heavy lifting. """ return "\n".join(_ogrinspect(*args, **kwargs)) def _ogrinspect( data_source, model_name, geom_name="geom", layer_key=0, srid=None, multi_geom=False, name_field=None, imports=True, decimal=False, blank=False, null=False, ): """ Helper routine for `ogrinspect` that generates GeoDjango models corresponding to the given data source. See the `ogrinspect` docstring for more details. """ # Getting the DataSource if isinstance(data_source, str): data_source = DataSource(data_source) elif isinstance(data_source, DataSource): pass else: raise TypeError( "Data source parameter must be a string or a DataSource object." ) # Getting the layer corresponding to the layer key and getting # a string listing of all OGR fields in the Layer. layer = data_source[layer_key] ogr_fields = layer.fields # Creating lists from the `null`, `blank`, and `decimal` # keyword arguments. def process_kwarg(kwarg): if isinstance(kwarg, (list, tuple)): return [s.lower() for s in kwarg] elif kwarg: return [s.lower() for s in ogr_fields] else: return [] null_fields = process_kwarg(null) blank_fields = process_kwarg(blank) decimal_fields = process_kwarg(decimal) # Gets the `null` and `blank` keywords for the given field name. def get_kwargs_str(field_name): kwlist = [] if field_name.lower() in null_fields: kwlist.append("null=True") if field_name.lower() in blank_fields: kwlist.append("blank=True") if kwlist: return ", " + ", ".join(kwlist) else: return "" # For those wishing to disable the imports. if imports: yield "# This is an auto-generated Django model module created by ogrinspect." yield "from django.contrib.gis.db import models" yield "" yield "" yield "class %s(models.Model):" % model_name for field_name, width, precision, field_type in zip( ogr_fields, layer.field_widths, layer.field_precisions, layer.field_types ): # The model field name. mfield = field_name.lower() if mfield[-1:] == "_": mfield += "field" # Getting the keyword args string. kwargs_str = get_kwargs_str(field_name) if field_type is OFTReal: # By default OFTReals are mapped to `FloatField`, however, they # may also be mapped to `DecimalField` if specified in the # `decimal` keyword. if field_name.lower() in decimal_fields: yield ( " %s = models.DecimalField(max_digits=%d, decimal_places=%d%s)" ) % ( mfield, width, precision, kwargs_str, ) else: yield " %s = models.FloatField(%s)" % (mfield, kwargs_str[2:]) elif field_type is OFTInteger: yield " %s = models.IntegerField(%s)" % (mfield, kwargs_str[2:]) elif field_type is OFTInteger64: yield " %s = models.BigIntegerField(%s)" % (mfield, kwargs_str[2:]) elif field_type is OFTString: yield " %s = models.CharField(max_length=%s%s)" % ( mfield, width, kwargs_str, ) elif field_type is OFTDate: yield " %s = models.DateField(%s)" % (mfield, kwargs_str[2:]) elif field_type is OFTDateTime: yield " %s = models.DateTimeField(%s)" % (mfield, kwargs_str[2:]) elif field_type is OFTTime: yield " %s = models.TimeField(%s)" % (mfield, kwargs_str[2:]) else: raise TypeError("Unknown field type %s in %s" % (field_type, mfield)) # TODO: Autodetection of multigeometry types (see #7218). gtype = layer.geom_type if multi_geom: gtype.to_multi() geom_field = gtype.django # Setting up the SRID keyword string. if srid is None: if layer.srs is None: srid_str = "srid=-1" else: srid = layer.srs.srid if srid is None: srid_str = "srid=-1" elif srid == 4326: # WGS84 is already the default. srid_str = "" else: srid_str = "srid=%s" % srid else: srid_str = "srid=%s" % srid yield " %s = models.%s(%s)" % (geom_name, geom_field, srid_str) if name_field: yield "" yield " def __str__(self): return self.%s" % name_field
85243eb01bea0f4432dffc619ce4d85daea9b890dcee9db4c67f4ba47406b1ec
# LayerMapping -- A Django Model/OGR Layer Mapping Utility """ The LayerMapping class provides a way to map the contents of OGR vector files (e.g. SHP files) to Geographic-enabled Django models. For more information, please consult the GeoDjango documentation: https://docs.djangoproject.com/en/dev/ref/contrib/gis/layermapping/ """ import sys from decimal import Decimal from decimal import InvalidOperation as DecimalInvalidOperation from pathlib import Path from django.contrib.gis.db.models import GeometryField from django.contrib.gis.gdal import ( CoordTransform, DataSource, GDALException, OGRGeometry, OGRGeomType, SpatialReference, ) from django.contrib.gis.gdal.field import ( OFTDate, OFTDateTime, OFTInteger, OFTInteger64, OFTReal, OFTString, OFTTime, ) from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist from django.db import connections, models, router, transaction from django.utils.encoding import force_str # LayerMapping exceptions. class LayerMapError(Exception): pass class InvalidString(LayerMapError): pass class InvalidDecimal(LayerMapError): pass class InvalidInteger(LayerMapError): pass class MissingForeignKey(LayerMapError): pass class LayerMapping: "A class that maps OGR Layers to GeoDjango Models." # Acceptable 'base' types for a multi-geometry type. MULTI_TYPES = { 1: OGRGeomType("MultiPoint"), 2: OGRGeomType("MultiLineString"), 3: OGRGeomType("MultiPolygon"), OGRGeomType("Point25D").num: OGRGeomType("MultiPoint25D"), OGRGeomType("LineString25D").num: OGRGeomType("MultiLineString25D"), OGRGeomType("Polygon25D").num: OGRGeomType("MultiPolygon25D"), } # Acceptable Django field types and corresponding acceptable OGR # counterparts. FIELD_TYPES = { models.AutoField: OFTInteger, models.BigAutoField: OFTInteger64, models.SmallAutoField: OFTInteger, models.BooleanField: (OFTInteger, OFTReal, OFTString), models.IntegerField: (OFTInteger, OFTReal, OFTString), models.FloatField: (OFTInteger, OFTReal), models.DateField: OFTDate, models.DateTimeField: OFTDateTime, models.EmailField: OFTString, models.TimeField: OFTTime, models.DecimalField: (OFTInteger, OFTReal), models.CharField: OFTString, models.SlugField: OFTString, models.TextField: OFTString, models.URLField: OFTString, models.UUIDField: OFTString, models.BigIntegerField: (OFTInteger, OFTReal, OFTString), models.SmallIntegerField: (OFTInteger, OFTReal, OFTString), models.PositiveBigIntegerField: (OFTInteger, OFTReal, OFTString), models.PositiveIntegerField: (OFTInteger, OFTReal, OFTString), models.PositiveSmallIntegerField: (OFTInteger, OFTReal, OFTString), } def __init__( self, model, data, mapping, layer=0, source_srs=None, encoding="utf-8", transaction_mode="commit_on_success", transform=True, unique=None, using=None, ): """ A LayerMapping object is initialized using the given Model (not an instance), a DataSource (or string path to an OGR-supported data file), and a mapping dictionary. See the module level docstring for more details and keyword argument usage. """ # Getting the DataSource and the associated Layer. if isinstance(data, (str, Path)): self.ds = DataSource(data, encoding=encoding) else: self.ds = data self.layer = self.ds[layer] self.using = using if using is not None else router.db_for_write(model) connection = connections[self.using] self.spatial_backend = connection.ops # Setting the mapping & model attributes. self.mapping = mapping self.model = model # Checking the layer -- initialization of the object will fail if # things don't check out before hand. self.check_layer() # Getting the geometry column associated with the model (an # exception will be raised if there is no geometry column). if connection.features.supports_transform: self.geo_field = self.geometry_field() else: transform = False # Checking the source spatial reference system, and getting # the coordinate transformation object (unless the `transform` # keyword is set to False) if transform: self.source_srs = self.check_srs(source_srs) self.transform = self.coord_transform() else: self.transform = transform # Setting the encoding for OFTString fields, if specified. if encoding: # Making sure the encoding exists, if not a LookupError # exception will be thrown. from codecs import lookup lookup(encoding) self.encoding = encoding else: self.encoding = None if unique: self.check_unique(unique) transaction_mode = "autocommit" # Has to be set to autocommit. self.unique = unique else: self.unique = None # Setting the transaction decorator with the function in the # transaction modes dictionary. self.transaction_mode = transaction_mode if transaction_mode == "autocommit": self.transaction_decorator = None elif transaction_mode == "commit_on_success": self.transaction_decorator = transaction.atomic else: raise LayerMapError("Unrecognized transaction mode: %s" % transaction_mode) # #### Checking routines used during initialization #### def check_fid_range(self, fid_range): "Check the `fid_range` keyword." if fid_range: if isinstance(fid_range, (tuple, list)): return slice(*fid_range) elif isinstance(fid_range, slice): return fid_range else: raise TypeError else: return None def check_layer(self): """ Check the Layer metadata and ensure that it's compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer. """ # The geometry field of the model is set here. # TODO: Support more than one geometry field / model. However, this # depends on the GDAL Driver in use. self.geom_field = False self.fields = {} # Getting lists of the field names and the field types available in # the OGR Layer. ogr_fields = self.layer.fields ogr_field_types = self.layer.field_types # Function for determining if the OGR mapping field is in the Layer. def check_ogr_fld(ogr_map_fld): try: idx = ogr_fields.index(ogr_map_fld) except ValueError: raise LayerMapError( 'Given mapping OGR field "%s" not found in OGR Layer.' % ogr_map_fld ) return idx # No need to increment through each feature in the model, simply check # the Layer metadata against what was given in the mapping dictionary. for field_name, ogr_name in self.mapping.items(): # Ensuring that a corresponding field exists in the model # for the given field name in the mapping. try: model_field = self.model._meta.get_field(field_name) except FieldDoesNotExist: raise LayerMapError( 'Given mapping field "%s" not in given Model fields.' % field_name ) # Getting the string name for the Django field class (e.g., 'PointField'). fld_name = model_field.__class__.__name__ if isinstance(model_field, GeometryField): if self.geom_field: raise LayerMapError( "LayerMapping does not support more than one GeometryField per " "model." ) # Getting the coordinate dimension of the geometry field. coord_dim = model_field.dim try: if coord_dim == 3: gtype = OGRGeomType(ogr_name + "25D") else: gtype = OGRGeomType(ogr_name) except GDALException: raise LayerMapError( 'Invalid mapping for GeometryField "%s".' % field_name ) # Making sure that the OGR Layer's Geometry is compatible. ltype = self.layer.geom_type if not ( ltype.name.startswith(gtype.name) or self.make_multi(ltype, model_field) ): raise LayerMapError( "Invalid mapping geometry; model has %s%s, " "layer geometry type is %s." % (fld_name, "(dim=3)" if coord_dim == 3 else "", ltype) ) # Setting the `geom_field` attribute w/the name of the model field # that is a Geometry. Also setting the coordinate dimension # attribute. self.geom_field = field_name self.coord_dim = coord_dim fields_val = model_field elif isinstance(model_field, models.ForeignKey): if isinstance(ogr_name, dict): # Is every given related model mapping field in the Layer? rel_model = model_field.remote_field.model for rel_name, ogr_field in ogr_name.items(): idx = check_ogr_fld(ogr_field) try: rel_model._meta.get_field(rel_name) except FieldDoesNotExist: raise LayerMapError( 'ForeignKey mapping field "%s" not in %s fields.' % (rel_name, rel_model.__class__.__name__) ) fields_val = rel_model else: raise TypeError("ForeignKey mapping must be of dictionary type.") else: # Is the model field type supported by LayerMapping? if model_field.__class__ not in self.FIELD_TYPES: raise LayerMapError( 'Django field type "%s" has no OGR mapping (yet).' % fld_name ) # Is the OGR field in the Layer? idx = check_ogr_fld(ogr_name) ogr_field = ogr_field_types[idx] # Can the OGR field type be mapped to the Django field type? if not issubclass(ogr_field, self.FIELD_TYPES[model_field.__class__]): raise LayerMapError( 'OGR field "%s" (of type %s) cannot be mapped to Django %s.' % (ogr_field, ogr_field.__name__, fld_name) ) fields_val = model_field self.fields[field_name] = fields_val def check_srs(self, source_srs): "Check the compatibility of the given spatial reference object." if isinstance(source_srs, SpatialReference): sr = source_srs elif isinstance(source_srs, self.spatial_backend.spatial_ref_sys()): sr = source_srs.srs elif isinstance(source_srs, (int, str)): sr = SpatialReference(source_srs) else: # Otherwise just pulling the SpatialReference from the layer sr = self.layer.srs if not sr: raise LayerMapError("No source reference system defined.") else: return sr def check_unique(self, unique): "Check the `unique` keyword parameter -- may be a sequence or string." if isinstance(unique, (list, tuple)): # List of fields to determine uniqueness with for attr in unique: if attr not in self.mapping: raise ValueError elif isinstance(unique, str): # Only a single field passed in. if unique not in self.mapping: raise ValueError else: raise TypeError( "Unique keyword argument must be set with a tuple, list, or string." ) # Keyword argument retrieval routines #### def feature_kwargs(self, feat): """ Given an OGR Feature, return a dictionary of keyword arguments for constructing the mapped model. """ # The keyword arguments for model construction. kwargs = {} # Incrementing through each model field and OGR field in the # dictionary mapping. for field_name, ogr_name in self.mapping.items(): model_field = self.fields[field_name] if isinstance(model_field, GeometryField): # Verify OGR geometry. try: val = self.verify_geom(feat.geom, model_field) except GDALException: raise LayerMapError("Could not retrieve geometry from feature.") elif isinstance(model_field, models.base.ModelBase): # The related _model_, not a field was passed in -- indicating # another mapping for the related Model. val = self.verify_fk(feat, model_field, ogr_name) else: # Otherwise, verify OGR Field type. val = self.verify_ogr_field(feat[ogr_name], model_field) # Setting the keyword arguments for the field name with the # value obtained above. kwargs[field_name] = val return kwargs def unique_kwargs(self, kwargs): """ Given the feature keyword arguments (from `feature_kwargs`), construct and return the uniqueness keyword arguments -- a subset of the feature kwargs. """ if isinstance(self.unique, str): return {self.unique: kwargs[self.unique]} else: return {fld: kwargs[fld] for fld in self.unique} # #### Verification routines used in constructing model keyword arguments. #### def verify_ogr_field(self, ogr_field, model_field): """ Verify if the OGR Field contents are acceptable to the model field. If they are, return the verified value, otherwise raise an exception. """ if isinstance(ogr_field, OFTString) and isinstance( model_field, (models.CharField, models.TextField) ): if self.encoding and ogr_field.value is not None: # The encoding for OGR data sources may be specified here # (e.g., 'cp437' for Census Bureau boundary files). val = force_str(ogr_field.value, self.encoding) else: val = ogr_field.value if ( model_field.max_length and val is not None and len(val) > model_field.max_length ): raise InvalidString( "%s model field maximum string length is %s, given %s characters." % (model_field.name, model_field.max_length, len(val)) ) elif isinstance(ogr_field, OFTReal) and isinstance( model_field, models.DecimalField ): try: # Creating an instance of the Decimal value to use. d = Decimal(str(ogr_field.value)) except DecimalInvalidOperation: raise InvalidDecimal( "Could not construct decimal from: %s" % ogr_field.value ) # Getting the decimal value as a tuple. dtup = d.as_tuple() digits = dtup[1] d_idx = dtup[2] # index where the decimal is # Maximum amount of precision, or digits to the left of the decimal. max_prec = model_field.max_digits - model_field.decimal_places # Getting the digits to the left of the decimal place for the # given decimal. if d_idx < 0: n_prec = len(digits[:d_idx]) else: n_prec = len(digits) + d_idx # If we have more than the maximum digits allowed, then throw an # InvalidDecimal exception. if n_prec > max_prec: raise InvalidDecimal( "A DecimalField with max_digits %d, decimal_places %d must " "round to an absolute value less than 10^%d." % (model_field.max_digits, model_field.decimal_places, max_prec) ) val = d elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance( model_field, models.IntegerField ): # Attempt to convert any OFTReal and OFTString value to an OFTInteger. try: val = int(ogr_field.value) except ValueError: raise InvalidInteger( "Could not construct integer from: %s" % ogr_field.value ) else: val = ogr_field.value return val def verify_fk(self, feat, rel_model, rel_mapping): """ Given an OGR Feature, the related model and its dictionary mapping, retrieve the related model for the ForeignKey mapping. """ # TODO: It is expensive to retrieve a model for every record -- # explore if an efficient mechanism exists for caching related # ForeignKey models. # Constructing and verifying the related model keyword arguments. fk_kwargs = {} for field_name, ogr_name in rel_mapping.items(): fk_kwargs[field_name] = self.verify_ogr_field( feat[ogr_name], rel_model._meta.get_field(field_name) ) # Attempting to retrieve and return the related model. try: return rel_model.objects.using(self.using).get(**fk_kwargs) except ObjectDoesNotExist: raise MissingForeignKey( "No ForeignKey %s model found with keyword arguments: %s" % (rel_model.__name__, fk_kwargs) ) def verify_geom(self, geom, model_field): """ Verify the geometry -- construct and return a GeometryCollection if necessary (for example if the model field is MultiPolygonField while the mapped shapefile only contains Polygons). """ # Downgrade a 3D geom to a 2D one, if necessary. if self.coord_dim != geom.coord_dim: geom.coord_dim = self.coord_dim if self.make_multi(geom.geom_type, model_field): # Constructing a multi-geometry type to contain the single geometry multi_type = self.MULTI_TYPES[geom.geom_type.num] g = OGRGeometry(multi_type) g.add(geom) else: g = geom # Transforming the geometry with our Coordinate Transformation object, # but only if the class variable `transform` is set w/a CoordTransform # object. if self.transform: g.transform(self.transform) # Returning the WKT of the geometry. return g.wkt # #### Other model methods #### def coord_transform(self): "Return the coordinate transformation object." SpatialRefSys = self.spatial_backend.spatial_ref_sys() try: # Getting the target spatial reference system target_srs = ( SpatialRefSys.objects.using(self.using) .get(srid=self.geo_field.srid) .srs ) # Creating the CoordTransform object return CoordTransform(self.source_srs, target_srs) except Exception as exc: raise LayerMapError( "Could not translate between the data source and model geometry." ) from exc def geometry_field(self): "Return the GeometryField instance associated with the geographic column." # Use `get_field()` on the model's options so that we # get the correct field instance if there's model inheritance. opts = self.model._meta return opts.get_field(self.geom_field) def make_multi(self, geom_type, model_field): """ Given the OGRGeomType for a geometry and its associated GeometryField, determine whether the geometry should be turned into a GeometryCollection. """ return ( geom_type.num in self.MULTI_TYPES and model_field.__class__.__name__ == "Multi%s" % geom_type.django ) def save( self, verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False, ): """ Save the contents from the OGR DataSource Layer into the database according to the mapping dictionary given at initialization. Keyword Parameters: verbose: If set, information will be printed subsequent to each model save executed on the database. fid_range: May be set with a slice or tuple of (begin, end) feature ID's to map from the data source. In other words, this keyword enables the user to selectively import a subset range of features in the geographic data source. step: If set with an integer, transactions will occur at every step interval. For example, if step=1000, a commit would occur after the 1,000th feature, the 2,000th feature etc. progress: When this keyword is set, status information will be printed giving the number of features processed and successfully saved. By default, progress information will pe printed every 1000 features processed, however, this default may be overridden by setting this keyword with an integer for the desired interval. stream: Status information will be written to this file handle. Defaults to using `sys.stdout`, but any object with a `write` method is supported. silent: By default, non-fatal error notifications are printed to stdout, but this keyword may be set to disable these notifications. strict: Execution of the model mapping will cease upon the first error encountered. The default behavior is to attempt to continue. """ # Getting the default Feature ID range. default_range = self.check_fid_range(fid_range) # Setting the progress interval, if requested. if progress: if progress is True or not isinstance(progress, int): progress_interval = 1000 else: progress_interval = progress def _save(feat_range=default_range, num_feat=0, num_saved=0): if feat_range: layer_iter = self.layer[feat_range] else: layer_iter = self.layer for feat in layer_iter: num_feat += 1 # Getting the keyword arguments try: kwargs = self.feature_kwargs(feat) except LayerMapError as msg: # Something borked the validation if strict: raise elif not silent: stream.write( "Ignoring Feature ID %s because: %s\n" % (feat.fid, msg) ) else: # Constructing the model using the keyword args is_update = False if self.unique: # If we want unique models on a particular field, handle the # geometry appropriately. try: # Getting the keyword arguments and retrieving # the unique model. u_kwargs = self.unique_kwargs(kwargs) m = self.model.objects.using(self.using).get(**u_kwargs) is_update = True # Getting the geometry (in OGR form), creating # one from the kwargs WKT, adding in additional # geometries, and update the attribute with the # just-updated geometry WKT. geom_value = getattr(m, self.geom_field) if geom_value is None: geom = OGRGeometry(kwargs[self.geom_field]) else: geom = geom_value.ogr new = OGRGeometry(kwargs[self.geom_field]) for g in new: geom.add(g) setattr(m, self.geom_field, geom.wkt) except ObjectDoesNotExist: # No unique model exists yet, create. m = self.model(**kwargs) else: m = self.model(**kwargs) try: # Attempting to save. m.save(using=self.using) num_saved += 1 if verbose: stream.write( "%s: %s\n" % ("Updated" if is_update else "Saved", m) ) except Exception as msg: if strict: # Bailing out if the `strict` keyword is set. if not silent: stream.write( "Failed to save the feature (id: %s) into the " "model with the keyword arguments:\n" % feat.fid ) stream.write("%s\n" % kwargs) raise elif not silent: stream.write( "Failed to save %s:\n %s\nContinuing\n" % (kwargs, msg) ) # Printing progress information, if requested. if progress and num_feat % progress_interval == 0: stream.write( "Processed %d features, saved %d ...\n" % (num_feat, num_saved) ) # Only used for status output purposes -- incremental saving uses the # values returned here. return num_saved, num_feat if self.transaction_decorator is not None: _save = self.transaction_decorator(_save) nfeat = self.layer.num_feat if step and isinstance(step, int) and step < nfeat: # Incremental saving is requested at the given interval (step) if default_range: raise LayerMapError( "The `step` keyword may not be used in conjunction with the " "`fid_range` keyword." ) beg, num_feat, num_saved = (0, 0, 0) indices = range(step, nfeat, step) n_i = len(indices) for i, end in enumerate(indices): # Constructing the slice to use for this step; the last slice is # special (e.g, [100:] instead of [90:100]). if i + 1 == n_i: step_slice = slice(beg, None) else: step_slice = slice(beg, end) try: num_feat, num_saved = _save(step_slice, num_feat, num_saved) beg = end except Exception: # Deliberately catch everything stream.write( "%s\nFailed to save slice: %s\n" % ("=-" * 20, step_slice) ) raise else: # Otherwise, just calling the previously defined _save() function. _save()
517b1bc56d1c4337673ca3b477d1392b61cf75e91d69be4d68b65634e52afb39
from django.contrib.gis.gdal import SpatialReference from django.db import DEFAULT_DB_ALIAS, connections def add_srs_entry( srs, auth_name="EPSG", auth_srid=None, ref_sys_name=None, database=None ): """ Take a GDAL SpatialReference system and add its information to the `spatial_ref_sys` table of the spatial backend. Doing this enables database-level spatial transformations for the backend. Thus, this utility is useful for adding spatial reference systems not included by default with the backend: >>> from django.contrib.gis.utils import add_srs_entry >>> add_srs_entry(3857) Keyword Arguments: auth_name: This keyword may be customized with the value of the `auth_name` field. Defaults to 'EPSG'. auth_srid: This keyword may be customized with the value of the `auth_srid` field. Defaults to the SRID determined by GDAL. ref_sys_name: For SpatiaLite users only, sets the value of the `ref_sys_name` field. Defaults to the name determined by GDAL. database: The name of the database connection to use; the default is the value of `django.db.DEFAULT_DB_ALIAS` (at the time of this writing, its value is 'default'). """ database = database or DEFAULT_DB_ALIAS connection = connections[database] if not hasattr(connection.ops, "spatial_version"): raise Exception("The `add_srs_entry` utility only works with spatial backends.") if not connection.features.supports_add_srs_entry: raise Exception("This utility does not support your database backend.") SpatialRefSys = connection.ops.spatial_ref_sys() # If argument is not a `SpatialReference` instance, use it as parameter # to construct a `SpatialReference` instance. if not isinstance(srs, SpatialReference): srs = SpatialReference(srs) if srs.srid is None: raise Exception( "Spatial reference requires an SRID to be " "compatible with the spatial backend." ) # Initializing the keyword arguments dictionary for both PostGIS # and SpatiaLite. kwargs = { "srid": srs.srid, "auth_name": auth_name, "auth_srid": auth_srid or srs.srid, "proj4text": srs.proj4, } # Backend-specific fields for the SpatialRefSys model. srs_field_names = {f.name for f in SpatialRefSys._meta.get_fields()} if "srtext" in srs_field_names: kwargs["srtext"] = srs.wkt if "ref_sys_name" in srs_field_names: # SpatiaLite specific kwargs["ref_sys_name"] = ref_sys_name or srs.name # Creating the spatial_ref_sys model. try: # Try getting via SRID only, because using all kwargs may # differ from exact wkt/proj in database. SpatialRefSys.objects.using(database).get(srid=srs.srid) except SpatialRefSys.DoesNotExist: SpatialRefSys.objects.using(database).create(**kwargs)
618f48a05bcb22679a80b32aa2e1de63adaa29fa34a97977005421eb7fbf120a
""" This module houses the GeoIP2 object, a wrapper for the MaxMind GeoIP2(R) Python API (https://geoip2.readthedocs.io/). This is an alternative to the Python GeoIP2 interface provided by MaxMind. GeoIP(R) is a registered trademark of MaxMind, Inc. For IP-based geolocation, this module requires the GeoLite2 Country and City datasets, in binary format (CSV will not work!). The datasets may be downloaded from MaxMind at https://dev.maxmind.com/geoip/geoip2/geolite2/. Grab GeoLite2-Country.mmdb.gz and GeoLite2-City.mmdb.gz, and unzip them in the directory corresponding to settings.GEOIP_PATH. """ __all__ = ["HAS_GEOIP2"] try: import geoip2 # NOQA except ImportError: HAS_GEOIP2 = False else: from .base import GeoIP2, GeoIP2Exception HAS_GEOIP2 = True __all__ += ["GeoIP2", "GeoIP2Exception"]
5f25f8424964d39882db8e5a36d2b3116da80b7c2ea2d8a947614b0cbb52f4ed
import socket import geoip2.database from django.conf import settings from django.contrib.gis.geos import Point from django.core.exceptions import ValidationError from django.core.validators import validate_ipv46_address from django.utils._os import to_path from .resources import City, Country # Creating the settings dictionary with any settings, if needed. GEOIP_SETTINGS = { "GEOIP_PATH": getattr(settings, "GEOIP_PATH", None), "GEOIP_CITY": getattr(settings, "GEOIP_CITY", "GeoLite2-City.mmdb"), "GEOIP_COUNTRY": getattr(settings, "GEOIP_COUNTRY", "GeoLite2-Country.mmdb"), } class GeoIP2Exception(Exception): pass class GeoIP2: # The flags for GeoIP memory caching. # Try MODE_MMAP_EXT, MODE_MMAP, MODE_FILE in that order. MODE_AUTO = 0 # Use the C extension with memory map. MODE_MMAP_EXT = 1 # Read from memory map. Pure Python. MODE_MMAP = 2 # Read database as standard file. Pure Python. MODE_FILE = 4 # Load database into memory. Pure Python. MODE_MEMORY = 8 cache_options = frozenset( (MODE_AUTO, MODE_MMAP_EXT, MODE_MMAP, MODE_FILE, MODE_MEMORY) ) # Paths to the city & country binary databases. _city_file = "" _country_file = "" # Initially, pointers to GeoIP file references are NULL. _city = None _country = None def __init__(self, path=None, cache=0, country=None, city=None): """ Initialize the GeoIP object. No parameters are required to use default settings. Keyword arguments may be passed in to customize the locations of the GeoIP datasets. * path: Base directory to where GeoIP data is located or the full path to where the city or country data files (*.mmdb) are located. Assumes that both the city and country data sets are located in this directory; overrides the GEOIP_PATH setting. * cache: The cache settings when opening up the GeoIP datasets. May be an integer in (0, 1, 2, 4, 8) corresponding to the MODE_AUTO, MODE_MMAP_EXT, MODE_MMAP, MODE_FILE, and MODE_MEMORY, `GeoIPOptions` C API settings, respectively. Defaults to 0, meaning MODE_AUTO. * country: The name of the GeoIP country data file. Defaults to 'GeoLite2-Country.mmdb'; overrides the GEOIP_COUNTRY setting. * city: The name of the GeoIP city data file. Defaults to 'GeoLite2-City.mmdb'; overrides the GEOIP_CITY setting. """ # Checking the given cache option. if cache not in self.cache_options: raise GeoIP2Exception("Invalid GeoIP caching option: %s" % cache) # Getting the GeoIP data path. path = path or GEOIP_SETTINGS["GEOIP_PATH"] if not path: raise GeoIP2Exception( "GeoIP path must be provided via parameter or the GEOIP_PATH setting." ) path = to_path(path) if path.is_dir(): # Constructing the GeoIP database filenames using the settings # dictionary. If the database files for the GeoLite country # and/or city datasets exist, then try to open them. country_db = path / (country or GEOIP_SETTINGS["GEOIP_COUNTRY"]) if country_db.is_file(): self._country = geoip2.database.Reader(str(country_db), mode=cache) self._country_file = country_db city_db = path / (city or GEOIP_SETTINGS["GEOIP_CITY"]) if city_db.is_file(): self._city = geoip2.database.Reader(str(city_db), mode=cache) self._city_file = city_db if not self._reader: raise GeoIP2Exception("Could not load a database from %s." % path) elif path.is_file(): # Otherwise, some detective work will be needed to figure out # whether the given database path is for the GeoIP country or city # databases. reader = geoip2.database.Reader(str(path), mode=cache) db_type = reader.metadata().database_type if db_type.endswith("City"): # GeoLite City database detected. self._city = reader self._city_file = path elif db_type.endswith("Country"): # GeoIP Country database detected. self._country = reader self._country_file = path else: raise GeoIP2Exception( "Unable to recognize database edition: %s" % db_type ) else: raise GeoIP2Exception("GeoIP path must be a valid file or directory.") @property def _reader(self): return self._country or self._city @property def _country_or_city(self): if self._country: return self._country.country else: return self._city.city def __del__(self): # Cleanup any GeoIP file handles lying around. if self._reader: self._reader.close() def __repr__(self): meta = self._reader.metadata() version = "[v%s.%s]" % ( meta.binary_format_major_version, meta.binary_format_minor_version, ) return ( '<%(cls)s %(version)s _country_file="%(country)s", _city_file="%(city)s">' % { "cls": self.__class__.__name__, "version": version, "country": self._country_file, "city": self._city_file, } ) def _check_query(self, query, city=False, city_or_country=False): "Check the query and database availability." # Making sure a string was passed in for the query. if not isinstance(query, str): raise TypeError( "GeoIP query must be a string, not type %s" % type(query).__name__ ) # Extra checks for the existence of country and city databases. if city_or_country and not (self._country or self._city): raise GeoIP2Exception("Invalid GeoIP country and city data files.") elif city and not self._city: raise GeoIP2Exception("Invalid GeoIP city data file: %s" % self._city_file) # Return the query string back to the caller. GeoIP2 only takes IP addresses. try: validate_ipv46_address(query) except ValidationError: query = socket.gethostbyname(query) return query def city(self, query): """ Return a dictionary of city information for the given IP address or Fully Qualified Domain Name (FQDN). Some information in the dictionary may be undefined (None). """ enc_query = self._check_query(query, city=True) return City(self._city.city(enc_query)) def country_code(self, query): "Return the country code for the given IP Address or FQDN." return self.country(query)["country_code"] def country_name(self, query): "Return the country name for the given IP Address or FQDN." return self.country(query)["country_name"] def country(self, query): """ Return a dictionary with the country code and name when given an IP address or a Fully Qualified Domain Name (FQDN). For example, both '24.124.1.80' and 'djangoproject.com' are valid parameters. """ # Returning the country code and name enc_query = self._check_query(query, city_or_country=True) return Country(self._country_or_city(enc_query)) # #### Coordinate retrieval routines #### def coords(self, query, ordering=("longitude", "latitude")): cdict = self.city(query) if cdict is None: return None else: return tuple(cdict[o] for o in ordering) def lon_lat(self, query): "Return a tuple of the (longitude, latitude) for the given query." return self.coords(query) def lat_lon(self, query): "Return a tuple of the (latitude, longitude) for the given query." return self.coords(query, ("latitude", "longitude")) def geos(self, query): "Return a GEOS Point object for the given query." ll = self.lon_lat(query) if ll: return Point(ll, srid=4326) else: return None # #### GeoIP Database Information Routines #### @property def info(self): "Return information about the GeoIP library and databases in use." meta = self._reader.metadata() return "GeoIP Library:\n\t%s.%s\n" % ( meta.binary_format_major_version, meta.binary_format_minor_version, ) @classmethod def open(cls, full_path, cache): return GeoIP2(full_path, cache)
2f3cfe3a4ebbed406631941d1ec3efd7ea8f05e27c6dce0729393bfd4ce66342
def City(response): return { "city": response.city.name, "continent_code": response.continent.code, "continent_name": response.continent.name, "country_code": response.country.iso_code, "country_name": response.country.name, "dma_code": response.location.metro_code, "is_in_european_union": response.country.is_in_european_union, "latitude": response.location.latitude, "longitude": response.location.longitude, "postal_code": response.postal.code, "region": response.subdivisions[0].iso_code if response.subdivisions else None, "time_zone": response.location.time_zone, } def Country(response): return { "country_code": response.country.iso_code, "country_name": response.country.name, }
67289dfd8959cc751c31891f197d467b098f3c335cd278bb1f25ca0d3788923a
from django.forms import * # NOQA from .fields import ( # NOQA GeometryCollectionField, GeometryField, LineStringField, MultiLineStringField, MultiPointField, MultiPolygonField, PointField, PolygonField, ) from .widgets import BaseGeometryWidget, OpenLayersWidget, OSMWidget # NOQA
258b179df825543b6d5b151ba5de867289625c3c1851e9d507635f09f428ea2c
import logging from django.conf import settings from django.contrib.gis import gdal from django.contrib.gis.geometry import json_regex from django.contrib.gis.geos import GEOSException, GEOSGeometry from django.forms.widgets import Widget from django.utils import translation logger = logging.getLogger("django.contrib.gis") class BaseGeometryWidget(Widget): """ The base class for rich geometry widgets. Render a map using the WKT of the geometry. """ geom_type = "GEOMETRY" map_srid = 4326 map_width = 600 map_height = 400 display_raw = False supports_3d = False template_name = "" # set on subclasses def __init__(self, attrs=None): self.attrs = {} for key in ("geom_type", "map_srid", "map_width", "map_height", "display_raw"): self.attrs[key] = getattr(self, key) if attrs: self.attrs.update(attrs) def serialize(self, value): return value.wkt if value else "" def deserialize(self, value): try: return GEOSGeometry(value) except (GEOSException, ValueError, TypeError) as err: logger.error("Error creating geometry from value '%s' (%s)", value, err) return None def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) # If a string reaches here (via a validation error on another # field) then just reconstruct the Geometry. if value and isinstance(value, str): value = self.deserialize(value) if value: # Check that srid of value and map match if value.srid and value.srid != self.map_srid: try: ogr = value.ogr ogr.transform(self.map_srid) value = ogr except gdal.GDALException as err: logger.error( "Error transforming geometry from srid '%s' to srid '%s' (%s)", value.srid, self.map_srid, err, ) geom_type = gdal.OGRGeomType(self.attrs["geom_type"]).name context.update( self.build_attrs( self.attrs, { "name": name, "module": "geodjango_%s" % name.replace("-", "_"), # JS-safe "serialized": self.serialize(value), "geom_type": "Geometry" if geom_type == "Unknown" else geom_type, "STATIC_URL": settings.STATIC_URL, "LANGUAGE_BIDI": translation.get_language_bidi(), **(attrs or {}), }, ) ) return context class OpenLayersWidget(BaseGeometryWidget): template_name = "gis/openlayers.html" map_srid = 3857 class Media: css = { "all": ( "https://cdnjs.cloudflare.com/ajax/libs/ol3/4.6.5/ol.css", "gis/css/ol3.css", ) } js = ( "https://cdnjs.cloudflare.com/ajax/libs/ol3/4.6.5/ol.js", "gis/js/OLMapWidget.js", ) def serialize(self, value): return value.json if value else "" def deserialize(self, value): geom = super().deserialize(value) # GeoJSON assumes WGS84 (4326). Use the map's SRID instead. if geom and json_regex.match(value) and self.map_srid != 4326: geom.srid = self.map_srid return geom class OSMWidget(OpenLayersWidget): """ An OpenLayers/OpenStreetMap-based widget. """ template_name = "gis/openlayers-osm.html" default_lon = 5 default_lat = 47 default_zoom = 12 def __init__(self, attrs=None): super().__init__() for key in ("default_lon", "default_lat", "default_zoom"): self.attrs[key] = getattr(self, key) if attrs: self.attrs.update(attrs)
16b65a6565c551d58ad5012ef3095d6b7bba12da9a5478d0458ad228abbae8f0
from django import forms from django.contrib.gis.gdal import GDALException from django.contrib.gis.geos import GEOSException, GEOSGeometry from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from .widgets import OpenLayersWidget class GeometryField(forms.Field): """ This is the basic form field for a Geometry. Any textual input that is accepted by GEOSGeometry is accepted by this form. By default, this includes WKT, HEXEWKB, WKB (in a buffer), and GeoJSON. """ widget = OpenLayersWidget geom_type = "GEOMETRY" default_error_messages = { "required": _("No geometry value provided."), "invalid_geom": _("Invalid geometry value."), "invalid_geom_type": _("Invalid geometry type."), "transform_error": _( "An error occurred when transforming the geometry " "to the SRID of the geometry form field." ), } def __init__(self, *, srid=None, geom_type=None, **kwargs): self.srid = srid if geom_type is not None: self.geom_type = geom_type super().__init__(**kwargs) self.widget.attrs["geom_type"] = self.geom_type def to_python(self, value): """Transform the value to a Geometry object.""" if value in self.empty_values: return None if not isinstance(value, GEOSGeometry): if hasattr(self.widget, "deserialize"): try: value = self.widget.deserialize(value) except GDALException: value = None else: try: value = GEOSGeometry(value) except (GEOSException, ValueError, TypeError): value = None if value is None: raise ValidationError( self.error_messages["invalid_geom"], code="invalid_geom" ) # Try to set the srid if not value.srid: try: value.srid = self.widget.map_srid except AttributeError: if self.srid: value.srid = self.srid return value def clean(self, value): """ Validate that the input value can be converted to a Geometry object and return it. Raise a ValidationError if the value cannot be instantiated as a Geometry. """ geom = super().clean(value) if geom is None: return geom # Ensuring that the geometry is of the correct type (indicated # using the OGC string label). if ( str(geom.geom_type).upper() != self.geom_type and self.geom_type != "GEOMETRY" ): raise ValidationError( self.error_messages["invalid_geom_type"], code="invalid_geom_type" ) # Transforming the geometry if the SRID was set. if self.srid and self.srid != -1 and self.srid != geom.srid: try: geom.transform(self.srid) except GEOSException: raise ValidationError( self.error_messages["transform_error"], code="transform_error" ) return geom def has_changed(self, initial, data): """Compare geographic value of data with its initial value.""" try: data = self.to_python(data) initial = self.to_python(initial) except ValidationError: return True # Only do a geographic comparison if both values are available if initial and data: data.transform(initial.srid) # If the initial value was not added by the browser, the geometry # provided may be slightly different, the first time it is saved. # The comparison is done with a very low tolerance. return not initial.equals_exact(data, tolerance=0.000001) else: # Check for change of state of existence return bool(initial) != bool(data) class GeometryCollectionField(GeometryField): geom_type = "GEOMETRYCOLLECTION" class PointField(GeometryField): geom_type = "POINT" class MultiPointField(GeometryField): geom_type = "MULTIPOINT" class LineStringField(GeometryField): geom_type = "LINESTRING" class MultiLineStringField(GeometryField): geom_type = "MULTILINESTRING" class PolygonField(GeometryField): geom_type = "POLYGON" class MultiPolygonField(GeometryField): geom_type = "MULTIPOLYGON"
5ee12537e4b39dbbbc42f1ab52ad350c1ac7d32357a6f37da34cbc7689d46f68
import json from django.contrib.gis.gdal import CoordTransform, SpatialReference from django.core.serializers.base import SerializerDoesNotExist from django.core.serializers.json import Serializer as JSONSerializer class Serializer(JSONSerializer): """ Convert a queryset to GeoJSON, http://geojson.org/ """ def _init_options(self): super()._init_options() self.geometry_field = self.json_kwargs.pop("geometry_field", None) self.srid = self.json_kwargs.pop("srid", 4326) if ( self.selected_fields is not None and self.geometry_field is not None and self.geometry_field not in self.selected_fields ): self.selected_fields = [*self.selected_fields, self.geometry_field] def start_serialization(self): self._init_options() self._cts = {} # cache of CoordTransform's self.stream.write( '{"type": "FeatureCollection", ' '"crs": {"type": "name", "properties": {"name": "EPSG:%d"}},' ' "features": [' % self.srid ) def end_serialization(self): self.stream.write("]}") def start_object(self, obj): super().start_object(obj) self._geometry = None if self.geometry_field is None: # Find the first declared geometry field for field in obj._meta.fields: if hasattr(field, "geom_type"): self.geometry_field = field.name break def get_dump_object(self, obj): data = { "type": "Feature", "properties": self._current, } if ( self.selected_fields is None or "pk" in self.selected_fields ) and "pk" not in data["properties"]: data["properties"]["pk"] = obj._meta.pk.value_to_string(obj) if self._geometry: if self._geometry.srid != self.srid: # If needed, transform the geometry in the srid of the global # geojson srid. if self._geometry.srid not in self._cts: srs = SpatialReference(self.srid) self._cts[self._geometry.srid] = CoordTransform( self._geometry.srs, srs ) self._geometry.transform(self._cts[self._geometry.srid]) data["geometry"] = json.loads(self._geometry.geojson) else: data["geometry"] = None return data def handle_field(self, obj, field): if field.name == self.geometry_field: self._geometry = field.value_from_object(obj) else: super().handle_field(obj, field) class Deserializer: def __init__(self, *args, **kwargs): raise SerializerDoesNotExist("geojson is a serialization-only serializer")
efc4bc6791fad4f0894b5ffe08225b88900e3f5d97f885a8efd3f009fca25572
""" DataSource is a wrapper for the OGR Data Source object, which provides an interface for reading vector geometry data from many different file formats (including ESRI shapefiles). When instantiating a DataSource object, use the filename of a GDAL-supported data source. For example, a SHP file or a TIGER/Line file from the government. The ds_driver keyword is used internally when a ctypes pointer is passed in directly. Example: ds = DataSource('/home/foo/bar.shp') for layer in ds: for feature in layer: # Getting the geometry for the feature. g = feature.geom # Getting the 'description' field for the feature. desc = feature['description'] # We can also increment through all of the fields # attached to this feature. for field in feature: # Get the name of the field (e.g. 'description') nm = field.name # Get the type (integer) of the field, e.g. 0 => OFTInteger t = field.type # Returns the value the field; OFTIntegers return ints, # OFTReal returns floats, all else returns string. val = field.value """ from ctypes import byref from pathlib import Path from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.driver import Driver from django.contrib.gis.gdal.error import GDALException from django.contrib.gis.gdal.layer import Layer from django.contrib.gis.gdal.prototypes import ds as capi from django.utils.encoding import force_bytes, force_str # For more information, see the OGR C API documentation: # https://gdal.org/api/vector_c_api.html # # The OGR_DS_* routines are relevant here. class DataSource(GDALBase): "Wraps an OGR Data Source object." destructor = capi.destroy_ds def __init__(self, ds_input, ds_driver=False, write=False, encoding="utf-8"): # The write flag. if write: self._write = 1 else: self._write = 0 # See also https://gdal.org/development/rfc/rfc23_ogr_unicode.html self.encoding = encoding Driver.ensure_registered() if isinstance(ds_input, (str, Path)): # The data source driver is a void pointer. ds_driver = Driver.ptr_type() try: # OGROpen will auto-detect the data source type. ds = capi.open_ds(force_bytes(ds_input), self._write, byref(ds_driver)) except GDALException: # Making the error message more clear rather than something # like "Invalid pointer returned from OGROpen". raise GDALException('Could not open the datasource at "%s"' % ds_input) elif isinstance(ds_input, self.ptr_type) and isinstance( ds_driver, Driver.ptr_type ): ds = ds_input else: raise GDALException("Invalid data source input type: %s" % type(ds_input)) if ds: self.ptr = ds self.driver = Driver(ds_driver) else: # Raise an exception if the returned pointer is NULL raise GDALException('Invalid data source file "%s"' % ds_input) def __getitem__(self, index): "Allows use of the index [] operator to get a layer at the index." if isinstance(index, str): try: layer = capi.get_layer_by_name(self.ptr, force_bytes(index)) except GDALException: raise IndexError("Invalid OGR layer name given: %s." % index) elif isinstance(index, int): if 0 <= index < self.layer_count: layer = capi.get_layer(self._ptr, index) else: raise IndexError( "Index out of range when accessing layers in a datasource: %s." % index ) else: raise TypeError("Invalid index type: %s" % type(index)) return Layer(layer, self) def __len__(self): "Return the number of layers within the data source." return self.layer_count def __str__(self): "Return OGR GetName and Driver for the Data Source." return "%s (%s)" % (self.name, self.driver) @property def layer_count(self): "Return the number of layers in the data source." return capi.get_layer_count(self._ptr) @property def name(self): "Return the name of the data source." name = capi.get_ds_name(self._ptr) return force_str(name, self.encoding, strings_only=True)
543ff0e46ca675a289c20056d5cab65e3b65dc45570af261dba2c894a816fcf3
from django.contrib.gis.gdal.error import GDALException class OGRGeomType: "Encapsulate OGR Geometry Types." wkb25bit = -2147483648 # Dictionary of acceptable OGRwkbGeometryType s and their string names. _types = { 0: "Unknown", 1: "Point", 2: "LineString", 3: "Polygon", 4: "MultiPoint", 5: "MultiLineString", 6: "MultiPolygon", 7: "GeometryCollection", 100: "None", 101: "LinearRing", 102: "PointZ", 1 + wkb25bit: "Point25D", 2 + wkb25bit: "LineString25D", 3 + wkb25bit: "Polygon25D", 4 + wkb25bit: "MultiPoint25D", 5 + wkb25bit: "MultiLineString25D", 6 + wkb25bit: "MultiPolygon25D", 7 + wkb25bit: "GeometryCollection25D", } # Reverse type dictionary, keyed by lowercase of the name. _str_types = {v.lower(): k for k, v in _types.items()} def __init__(self, type_input): "Figure out the correct OGR Type based upon the input." if isinstance(type_input, OGRGeomType): num = type_input.num elif isinstance(type_input, str): type_input = type_input.lower() if type_input == "geometry": type_input = "unknown" num = self._str_types.get(type_input) if num is None: raise GDALException('Invalid OGR String Type "%s"' % type_input) elif isinstance(type_input, int): if type_input not in self._types: raise GDALException("Invalid OGR Integer Type: %d" % type_input) num = type_input else: raise TypeError("Invalid OGR input type given.") # Setting the OGR geometry type number. self.num = num def __str__(self): "Return the value of the name property." return self.name def __eq__(self, other): """ Do an equivalence test on the OGR type with the given other OGRGeomType, the short-hand string, or the integer. """ if isinstance(other, OGRGeomType): return self.num == other.num elif isinstance(other, str): return self.name.lower() == other.lower() elif isinstance(other, int): return self.num == other else: return False @property def name(self): "Return a short-hand string form of the OGR Geometry type." return self._types[self.num] @property def django(self): "Return the Django GeometryField for this OGR Type." s = self.name.replace("25D", "") if s in ("LinearRing", "None"): return None elif s == "Unknown": s = "Geometry" elif s == "PointZ": s = "Point" return s + "Field" def to_multi(self): """ Transform Point, LineString, Polygon, and their 25D equivalents to their Multi... counterpart. """ if self.name.startswith(("Point", "LineString", "Polygon")): self.num += 3
b585eaa070f4918f0b58dd5255c69b8f5e647de5f2d964d05bdcca21e47cfa24
""" The OGRGeometry is a wrapper for using the OGR Geometry class (see https://gdal.org/api/ogrgeometry_cpp.html#_CPPv411OGRGeometry). OGRGeometry may be instantiated when reading geometries from OGR Data Sources (e.g. SHP files), or when given OGC WKT (a string). While the 'full' API is not present yet, the API is "pythonic" unlike the traditional and "next-generation" OGR Python bindings. One major advantage OGR Geometries have over their GEOS counterparts is support for spatial reference systems and their transformation. Example: >>> from django.contrib.gis.gdal import OGRGeometry, OGRGeomType, SpatialReference >>> wkt1, wkt2 = 'POINT(-90 30)', 'POLYGON((0 0, 5 0, 5 5, 0 5)' >>> pnt = OGRGeometry(wkt1) >>> print(pnt) POINT (-90 30) >>> mpnt = OGRGeometry(OGRGeomType('MultiPoint'), SpatialReference('WGS84')) >>> mpnt.add(wkt1) >>> mpnt.add(wkt1) >>> print(mpnt) MULTIPOINT (-90 30,-90 30) >>> print(mpnt.srs.name) WGS 84 >>> print(mpnt.srs.proj) +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs >>> mpnt.transform(SpatialReference('NAD27')) >>> print(mpnt.proj) +proj=longlat +ellps=clrk66 +datum=NAD27 +no_defs >>> print(mpnt) MULTIPOINT (-89.99993037860248 29.99979788655764,-89.99993037860248 29.99979788655764) The OGRGeomType class is to make it easy to specify an OGR geometry type: >>> from django.contrib.gis.gdal import OGRGeomType >>> gt1 = OGRGeomType(3) # Using an integer for the type >>> gt2 = OGRGeomType('Polygon') # Using a string >>> gt3 = OGRGeomType('POLYGON') # It's case-insensitive >>> print(gt1 == 3, gt1 == 'Polygon') # Equivalence works w/non-OGRGeomType objects True True """ import sys from binascii import b2a_hex from ctypes import byref, c_char_p, c_double, c_ubyte, c_void_p, string_at from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope from django.contrib.gis.gdal.error import GDALException, SRSException from django.contrib.gis.gdal.geomtype import OGRGeomType from django.contrib.gis.gdal.prototypes import geom as capi from django.contrib.gis.gdal.prototypes import srs as srs_api from django.contrib.gis.gdal.srs import CoordTransform, SpatialReference from django.contrib.gis.geometry import hex_regex, json_regex, wkt_regex from django.utils.encoding import force_bytes # For more information, see the OGR C API source code: # https://gdal.org/api/vector_c_api.html # # The OGR_G_* routines are relevant here. class OGRGeometry(GDALBase): """Encapsulate an OGR geometry.""" destructor = capi.destroy_geom def __init__(self, geom_input, srs=None): """Initialize Geometry on either WKT or an OGR pointer as input.""" str_instance = isinstance(geom_input, str) # If HEX, unpack input to a binary buffer. if str_instance and hex_regex.match(geom_input): geom_input = memoryview(bytes.fromhex(geom_input)) str_instance = False # Constructing the geometry, if str_instance: wkt_m = wkt_regex.match(geom_input) json_m = json_regex.match(geom_input) if wkt_m: if wkt_m["srid"]: # If there's EWKT, set the SRS w/value of the SRID. srs = int(wkt_m["srid"]) if wkt_m["type"].upper() == "LINEARRING": # OGR_G_CreateFromWkt doesn't work with LINEARRING WKT. # See https://trac.osgeo.org/gdal/ticket/1992. g = capi.create_geom(OGRGeomType(wkt_m["type"]).num) capi.import_wkt(g, byref(c_char_p(wkt_m["wkt"].encode()))) else: g = capi.from_wkt( byref(c_char_p(wkt_m["wkt"].encode())), None, byref(c_void_p()) ) elif json_m: g = self._from_json(geom_input.encode()) else: # Seeing if the input is a valid short-hand string # (e.g., 'Point', 'POLYGON'). OGRGeomType(geom_input) g = capi.create_geom(OGRGeomType(geom_input).num) elif isinstance(geom_input, memoryview): # WKB was passed in g = self._from_wkb(geom_input) elif isinstance(geom_input, OGRGeomType): # OGRGeomType was passed in, an empty geometry will be created. g = capi.create_geom(geom_input.num) elif isinstance(geom_input, self.ptr_type): # OGR pointer (c_void_p) was the input. g = geom_input else: raise GDALException( "Invalid input type for OGR Geometry construction: %s" % type(geom_input) ) # Now checking the Geometry pointer before finishing initialization # by setting the pointer for the object. if not g: raise GDALException( "Cannot create OGR Geometry from input: %s" % geom_input ) self.ptr = g # Assigning the SpatialReference object to the geometry, if valid. if srs: self.srs = srs # Setting the class depending upon the OGR Geometry Type self.__class__ = GEO_CLASSES[self.geom_type.num] # Pickle routines def __getstate__(self): srs = self.srs if srs: srs = srs.wkt else: srs = None return bytes(self.wkb), srs def __setstate__(self, state): wkb, srs = state ptr = capi.from_wkb(wkb, None, byref(c_void_p()), len(wkb)) if not ptr: raise GDALException("Invalid OGRGeometry loaded from pickled state.") self.ptr = ptr self.srs = srs @classmethod def _from_wkb(cls, geom_input): return capi.from_wkb( bytes(geom_input), None, byref(c_void_p()), len(geom_input) ) @staticmethod def _from_json(geom_input): return capi.from_json(geom_input) @classmethod def from_bbox(cls, bbox): "Construct a Polygon from a bounding box (4-tuple)." x0, y0, x1, y1 = bbox return OGRGeometry( "POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))" % (x0, y0, x0, y1, x1, y1, x1, y0, x0, y0) ) @staticmethod def from_json(geom_input): return OGRGeometry(OGRGeometry._from_json(force_bytes(geom_input))) @classmethod def from_gml(cls, gml_string): return cls(capi.from_gml(force_bytes(gml_string))) # ### Geometry set-like operations ### # g = g1 | g2 def __or__(self, other): "Return the union of the two geometries." return self.union(other) # g = g1 & g2 def __and__(self, other): "Return the intersection of this Geometry and the other." return self.intersection(other) # g = g1 - g2 def __sub__(self, other): "Return the difference this Geometry and the other." return self.difference(other) # g = g1 ^ g2 def __xor__(self, other): "Return the symmetric difference of this Geometry and the other." return self.sym_difference(other) def __eq__(self, other): "Is this Geometry equal to the other?" return isinstance(other, OGRGeometry) and self.equals(other) def __str__(self): "WKT is used for the string representation." return self.wkt # #### Geometry Properties #### @property def dimension(self): "Return 0 for points, 1 for lines, and 2 for surfaces." return capi.get_dims(self.ptr) def _get_coord_dim(self): "Return the coordinate dimension of the Geometry." return capi.get_coord_dim(self.ptr) def _set_coord_dim(self, dim): "Set the coordinate dimension of this Geometry." if dim not in (2, 3): raise ValueError("Geometry dimension must be either 2 or 3") capi.set_coord_dim(self.ptr, dim) coord_dim = property(_get_coord_dim, _set_coord_dim) @property def geom_count(self): "Return the number of elements in this Geometry." return capi.get_geom_count(self.ptr) @property def point_count(self): "Return the number of Points in this Geometry." return capi.get_point_count(self.ptr) @property def num_points(self): "Alias for `point_count` (same name method in GEOS API.)" return self.point_count @property def num_coords(self): "Alias for `point_count`." return self.point_count @property def geom_type(self): "Return the Type for this Geometry." return OGRGeomType(capi.get_geom_type(self.ptr)) @property def geom_name(self): "Return the Name of this Geometry." return capi.get_geom_name(self.ptr) @property def area(self): "Return the area for a LinearRing, Polygon, or MultiPolygon; 0 otherwise." return capi.get_area(self.ptr) @property def envelope(self): "Return the envelope for this Geometry." # TODO: Fix Envelope() for Point geometries. return Envelope(capi.get_envelope(self.ptr, byref(OGREnvelope()))) @property def empty(self): return capi.is_empty(self.ptr) @property def extent(self): "Return the envelope as a 4-tuple, instead of as an Envelope object." return self.envelope.tuple # #### SpatialReference-related Properties #### # The SRS property def _get_srs(self): "Return the Spatial Reference for this Geometry." try: srs_ptr = capi.get_geom_srs(self.ptr) return SpatialReference(srs_api.clone_srs(srs_ptr)) except SRSException: return None def _set_srs(self, srs): "Set the SpatialReference for this geometry." # Do not have to clone the `SpatialReference` object pointer because # when it is assigned to this `OGRGeometry` it's internal OGR # reference count is incremented, and will likewise be released # (decremented) when this geometry's destructor is called. if isinstance(srs, SpatialReference): srs_ptr = srs.ptr elif isinstance(srs, (int, str)): sr = SpatialReference(srs) srs_ptr = sr.ptr elif srs is None: srs_ptr = None else: raise TypeError( "Cannot assign spatial reference with object of type: %s" % type(srs) ) capi.assign_srs(self.ptr, srs_ptr) srs = property(_get_srs, _set_srs) # The SRID property def _get_srid(self): srs = self.srs if srs: return srs.srid return None def _set_srid(self, srid): if isinstance(srid, int) or srid is None: self.srs = srid else: raise TypeError("SRID must be set with an integer.") srid = property(_get_srid, _set_srid) # #### Output Methods #### def _geos_ptr(self): from django.contrib.gis.geos import GEOSGeometry return GEOSGeometry._from_wkb(self.wkb) @property def geos(self): "Return a GEOSGeometry object from this OGRGeometry." from django.contrib.gis.geos import GEOSGeometry return GEOSGeometry(self._geos_ptr(), self.srid) @property def gml(self): "Return the GML representation of the Geometry." return capi.to_gml(self.ptr) @property def hex(self): "Return the hexadecimal representation of the WKB (a string)." return b2a_hex(self.wkb).upper() @property def json(self): """ Return the GeoJSON representation of this Geometry. """ return capi.to_json(self.ptr) geojson = json @property def kml(self): "Return the KML representation of the Geometry." return capi.to_kml(self.ptr, None) @property def wkb_size(self): "Return the size of the WKB buffer." return capi.get_wkbsize(self.ptr) @property def wkb(self): "Return the WKB representation of the Geometry." if sys.byteorder == "little": byteorder = 1 # wkbNDR (from ogr_core.h) else: byteorder = 0 # wkbXDR sz = self.wkb_size # Creating the unsigned character buffer, and passing it in by reference. buf = (c_ubyte * sz)() capi.to_wkb(self.ptr, byteorder, byref(buf)) # Returning a buffer of the string at the pointer. return memoryview(string_at(buf, sz)) @property def wkt(self): "Return the WKT representation of the Geometry." return capi.to_wkt(self.ptr, byref(c_char_p())) @property def ewkt(self): "Return the EWKT representation of the Geometry." srs = self.srs if srs and srs.srid: return "SRID=%s;%s" % (srs.srid, self.wkt) else: return self.wkt # #### Geometry Methods #### def clone(self): "Clone this OGR Geometry." return OGRGeometry(capi.clone_geom(self.ptr), self.srs) def close_rings(self): """ If there are any rings within this geometry that have not been closed, this routine will do so by adding the starting point at the end. """ # Closing the open rings. capi.geom_close_rings(self.ptr) def transform(self, coord_trans, clone=False): """ Transform this geometry to a different spatial reference system. May take a CoordTransform object, a SpatialReference object, string WKT or PROJ, and/or an integer SRID. By default, return nothing and transform the geometry in-place. However, if the `clone` keyword is set, return a transformed clone of this geometry. """ if clone: klone = self.clone() klone.transform(coord_trans) return klone # Depending on the input type, use the appropriate OGR routine # to perform the transformation. if isinstance(coord_trans, CoordTransform): capi.geom_transform(self.ptr, coord_trans.ptr) elif isinstance(coord_trans, SpatialReference): capi.geom_transform_to(self.ptr, coord_trans.ptr) elif isinstance(coord_trans, (int, str)): sr = SpatialReference(coord_trans) capi.geom_transform_to(self.ptr, sr.ptr) else: raise TypeError( "Transform only accepts CoordTransform, " "SpatialReference, string, and integer objects." ) # #### Topology Methods #### def _topology(self, func, other): """A generalized function for topology operations, takes a GDAL function and the other geometry to perform the operation on.""" if not isinstance(other, OGRGeometry): raise TypeError( "Must use another OGRGeometry object for topology operations!" ) # Returning the output of the given function with the other geometry's # pointer. return func(self.ptr, other.ptr) def intersects(self, other): "Return True if this geometry intersects with the other." return self._topology(capi.ogr_intersects, other) def equals(self, other): "Return True if this geometry is equivalent to the other." return self._topology(capi.ogr_equals, other) def disjoint(self, other): "Return True if this geometry and the other are spatially disjoint." return self._topology(capi.ogr_disjoint, other) def touches(self, other): "Return True if this geometry touches the other." return self._topology(capi.ogr_touches, other) def crosses(self, other): "Return True if this geometry crosses the other." return self._topology(capi.ogr_crosses, other) def within(self, other): "Return True if this geometry is within the other." return self._topology(capi.ogr_within, other) def contains(self, other): "Return True if this geometry contains the other." return self._topology(capi.ogr_contains, other) def overlaps(self, other): "Return True if this geometry overlaps the other." return self._topology(capi.ogr_overlaps, other) # #### Geometry-generation Methods #### def _geomgen(self, gen_func, other=None): "A helper routine for the OGR routines that generate geometries." if isinstance(other, OGRGeometry): return OGRGeometry(gen_func(self.ptr, other.ptr), self.srs) else: return OGRGeometry(gen_func(self.ptr), self.srs) @property def boundary(self): "Return the boundary of this geometry." return self._geomgen(capi.get_boundary) @property def convex_hull(self): """ Return the smallest convex Polygon that contains all the points in this Geometry. """ return self._geomgen(capi.geom_convex_hull) def difference(self, other): """ Return a new geometry consisting of the region which is the difference of this geometry and the other. """ return self._geomgen(capi.geom_diff, other) def intersection(self, other): """ Return a new geometry consisting of the region of intersection of this geometry and the other. """ return self._geomgen(capi.geom_intersection, other) def sym_difference(self, other): """ Return a new geometry which is the symmetric difference of this geometry and the other. """ return self._geomgen(capi.geom_sym_diff, other) def union(self, other): """ Return a new geometry consisting of the region which is the union of this geometry and the other. """ return self._geomgen(capi.geom_union, other) # The subclasses for OGR Geometry. class Point(OGRGeometry): def _geos_ptr(self): from django.contrib.gis import geos return geos.Point._create_empty() if self.empty else super()._geos_ptr() @classmethod def _create_empty(cls): return capi.create_geom(OGRGeomType("point").num) @property def x(self): "Return the X coordinate for this Point." return capi.getx(self.ptr, 0) @property def y(self): "Return the Y coordinate for this Point." return capi.gety(self.ptr, 0) @property def z(self): "Return the Z coordinate for this Point." if self.coord_dim == 3: return capi.getz(self.ptr, 0) @property def tuple(self): "Return the tuple of this point." if self.coord_dim == 2: return (self.x, self.y) elif self.coord_dim == 3: return (self.x, self.y, self.z) coords = tuple class LineString(OGRGeometry): def __getitem__(self, index): "Return the Point at the given index." if 0 <= index < self.point_count: x, y, z = c_double(), c_double(), c_double() capi.get_point(self.ptr, index, byref(x), byref(y), byref(z)) dim = self.coord_dim if dim == 1: return (x.value,) elif dim == 2: return (x.value, y.value) elif dim == 3: return (x.value, y.value, z.value) else: raise IndexError( "Index out of range when accessing points of a line string: %s." % index ) def __len__(self): "Return the number of points in the LineString." return self.point_count @property def tuple(self): "Return the tuple representation of this LineString." return tuple(self[i] for i in range(len(self))) coords = tuple def _listarr(self, func): """ Internal routine that returns a sequence (list) corresponding with the given function. """ return [func(self.ptr, i) for i in range(len(self))] @property def x(self): "Return the X coordinates in a list." return self._listarr(capi.getx) @property def y(self): "Return the Y coordinates in a list." return self._listarr(capi.gety) @property def z(self): "Return the Z coordinates in a list." if self.coord_dim == 3: return self._listarr(capi.getz) # LinearRings are used in Polygons. class LinearRing(LineString): pass class Polygon(OGRGeometry): def __len__(self): "Return the number of interior rings in this Polygon." return self.geom_count def __getitem__(self, index): "Get the ring at the specified index." if 0 <= index < self.geom_count: return OGRGeometry( capi.clone_geom(capi.get_geom_ref(self.ptr, index)), self.srs ) else: raise IndexError( "Index out of range when accessing rings of a polygon: %s." % index ) # Polygon Properties @property def shell(self): "Return the shell of this Polygon." return self[0] # First ring is the shell exterior_ring = shell @property def tuple(self): "Return a tuple of LinearRing coordinate tuples." return tuple(self[i].tuple for i in range(self.geom_count)) coords = tuple @property def point_count(self): "Return the number of Points in this Polygon." # Summing up the number of points in each ring of the Polygon. return sum(self[i].point_count for i in range(self.geom_count)) @property def centroid(self): "Return the centroid (a Point) of this Polygon." # The centroid is a Point, create a geometry for this. p = OGRGeometry(OGRGeomType("Point")) capi.get_centroid(self.ptr, p.ptr) return p # Geometry Collection base class. class GeometryCollection(OGRGeometry): "The Geometry Collection class." def __getitem__(self, index): "Get the Geometry at the specified index." if 0 <= index < self.geom_count: return OGRGeometry( capi.clone_geom(capi.get_geom_ref(self.ptr, index)), self.srs ) else: raise IndexError( "Index out of range when accessing geometry in a collection: %s." % index ) def __len__(self): "Return the number of geometries in this Geometry Collection." return self.geom_count def add(self, geom): "Add the geometry to this Geometry Collection." if isinstance(geom, OGRGeometry): if isinstance(geom, self.__class__): for g in geom: capi.add_geom(self.ptr, g.ptr) else: capi.add_geom(self.ptr, geom.ptr) elif isinstance(geom, str): tmp = OGRGeometry(geom) capi.add_geom(self.ptr, tmp.ptr) else: raise GDALException("Must add an OGRGeometry.") @property def point_count(self): "Return the number of Points in this Geometry Collection." # Summing up the number of points in each geometry in this collection return sum(self[i].point_count for i in range(self.geom_count)) @property def tuple(self): "Return a tuple representation of this Geometry Collection." return tuple(self[i].tuple for i in range(self.geom_count)) coords = tuple # Multiple Geometry types. class MultiPoint(GeometryCollection): pass class MultiLineString(GeometryCollection): pass class MultiPolygon(GeometryCollection): pass # Class mapping dictionary (using the OGRwkbGeometryType as the key) GEO_CLASSES = { 1: Point, 2: LineString, 3: Polygon, 4: MultiPoint, 5: MultiLineString, 6: MultiPolygon, 7: GeometryCollection, 101: LinearRing, 1 + OGRGeomType.wkb25bit: Point, 2 + OGRGeomType.wkb25bit: LineString, 3 + OGRGeomType.wkb25bit: Polygon, 4 + OGRGeomType.wkb25bit: MultiPoint, 5 + OGRGeomType.wkb25bit: MultiLineString, 6 + OGRGeomType.wkb25bit: MultiPolygon, 7 + OGRGeomType.wkb25bit: GeometryCollection, }
9b97118ffaaf0f78db2c38cc9348200f15bf8627de67e09bb51b4765422c4624
""" This module houses ctypes interfaces for GDAL objects. The following GDAL objects are supported: CoordTransform: Used for coordinate transformations from one spatial reference system to another. Driver: Wraps an OGR data source driver. DataSource: Wrapper for the OGR data source object, supports OGR-supported data sources. Envelope: A ctypes structure for bounding boxes (GDAL library not required). OGRGeometry: Object for accessing OGR Geometry functionality. OGRGeomType: A class for representing the different OGR Geometry types (GDAL library not required). SpatialReference: Represents OSR Spatial Reference objects. The GDAL library will be imported from the system path using the default library name for the current OS. The default library path may be overridden by setting `GDAL_LIBRARY_PATH` in your settings with the path to the GDAL C library on your system. """ from django.contrib.gis.gdal.datasource import DataSource from django.contrib.gis.gdal.driver import Driver from django.contrib.gis.gdal.envelope import Envelope from django.contrib.gis.gdal.error import GDALException, SRSException, check_err from django.contrib.gis.gdal.geometries import OGRGeometry from django.contrib.gis.gdal.geomtype import OGRGeomType from django.contrib.gis.gdal.libgdal import ( GDAL_VERSION, gdal_full_version, gdal_version, ) from django.contrib.gis.gdal.raster.source import GDALRaster from django.contrib.gis.gdal.srs import AxisOrder, CoordTransform, SpatialReference __all__ = ( "AxisOrder", "Driver", "DataSource", "CoordTransform", "Envelope", "GDALException", "GDALRaster", "GDAL_VERSION", "OGRGeometry", "OGRGeomType", "SpatialReference", "SRSException", "check_err", "gdal_version", "gdal_full_version", )
10a13e2288f92fbf6fa3ddce8b1cff244e132196c34d1cb46151af647f88d73e
from ctypes import byref, c_int from datetime import date, datetime, time from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.error import GDALException from django.contrib.gis.gdal.prototypes import ds as capi from django.utils.encoding import force_str # For more information, see the OGR C API source code: # https://gdal.org/api/vector_c_api.html # # The OGR_Fld_* routines are relevant here. class Field(GDALBase): """ Wrap an OGR Field. Needs to be instantiated from a Feature object. """ def __init__(self, feat, index): """ Initialize on the feature object and the integer index of the field within the feature. """ # Setting the feature pointer and index. self._feat = feat self._index = index # Getting the pointer for this field. fld_ptr = capi.get_feat_field_defn(feat.ptr, index) if not fld_ptr: raise GDALException("Cannot create OGR Field, invalid pointer given.") self.ptr = fld_ptr # Setting the class depending upon the OGR Field Type (OFT) self.__class__ = OGRFieldTypes[self.type] def __str__(self): "Return the string representation of the Field." return str(self.value).strip() # #### Field Methods #### def as_double(self): "Retrieve the Field's value as a double (float)." return ( capi.get_field_as_double(self._feat.ptr, self._index) if self.is_set else None ) def as_int(self, is_64=False): "Retrieve the Field's value as an integer." if is_64: return ( capi.get_field_as_integer64(self._feat.ptr, self._index) if self.is_set else None ) else: return ( capi.get_field_as_integer(self._feat.ptr, self._index) if self.is_set else None ) def as_string(self): "Retrieve the Field's value as a string." if not self.is_set: return None string = capi.get_field_as_string(self._feat.ptr, self._index) return force_str(string, encoding=self._feat.encoding, strings_only=True) def as_datetime(self): "Retrieve the Field's value as a tuple of date & time components." if not self.is_set: return None yy, mm, dd, hh, mn, ss, tz = [c_int() for i in range(7)] status = capi.get_field_as_datetime( self._feat.ptr, self._index, byref(yy), byref(mm), byref(dd), byref(hh), byref(mn), byref(ss), byref(tz), ) if status: return (yy, mm, dd, hh, mn, ss, tz) else: raise GDALException( "Unable to retrieve date & time information from the field." ) # #### Field Properties #### @property def is_set(self): "Return True if the value of this field isn't null, False otherwise." return capi.is_field_set(self._feat.ptr, self._index) @property def name(self): "Return the name of this Field." name = capi.get_field_name(self.ptr) return force_str(name, encoding=self._feat.encoding, strings_only=True) @property def precision(self): "Return the precision of this Field." return capi.get_field_precision(self.ptr) @property def type(self): "Return the OGR type of this Field." return capi.get_field_type(self.ptr) @property def type_name(self): "Return the OGR field type name for this Field." return capi.get_field_type_name(self.type) @property def value(self): "Return the value of this Field." # Default is to get the field as a string. return self.as_string() @property def width(self): "Return the width of this Field." return capi.get_field_width(self.ptr) # ### The Field sub-classes for each OGR Field type. ### class OFTInteger(Field): _bit64 = False @property def value(self): "Return an integer contained in this field." return self.as_int(self._bit64) @property def type(self): """ GDAL uses OFTReals to represent OFTIntegers in created shapefiles -- forcing the type here since the underlying field type may actually be OFTReal. """ return 0 class OFTReal(Field): @property def value(self): "Return a float contained in this field." return self.as_double() # String & Binary fields, just subclasses class OFTString(Field): pass class OFTWideString(Field): pass class OFTBinary(Field): pass # OFTDate, OFTTime, OFTDateTime fields. class OFTDate(Field): @property def value(self): "Return a Python `date` object for the OFTDate field." try: yy, mm, dd, hh, mn, ss, tz = self.as_datetime() return date(yy.value, mm.value, dd.value) except (TypeError, ValueError, GDALException): return None class OFTDateTime(Field): @property def value(self): "Return a Python `datetime` object for this OFTDateTime field." # TODO: Adapt timezone information. # See https://lists.osgeo.org/pipermail/gdal-dev/2006-February/007990.html # The `tz` variable has values of: 0=unknown, 1=localtime (ambiguous), # 100=GMT, 104=GMT+1, 80=GMT-5, etc. try: yy, mm, dd, hh, mn, ss, tz = self.as_datetime() return datetime(yy.value, mm.value, dd.value, hh.value, mn.value, ss.value) except (TypeError, ValueError, GDALException): return None class OFTTime(Field): @property def value(self): "Return a Python `time` object for this OFTTime field." try: yy, mm, dd, hh, mn, ss, tz = self.as_datetime() return time(hh.value, mn.value, ss.value) except (ValueError, GDALException): return None class OFTInteger64(OFTInteger): _bit64 = True # List fields are also just subclasses class OFTIntegerList(Field): pass class OFTRealList(Field): pass class OFTStringList(Field): pass class OFTWideStringList(Field): pass class OFTInteger64List(Field): pass # Class mapping dictionary for OFT Types and reverse mapping. OGRFieldTypes = { 0: OFTInteger, 1: OFTIntegerList, 2: OFTReal, 3: OFTRealList, 4: OFTString, 5: OFTStringList, 6: OFTWideString, 7: OFTWideStringList, 8: OFTBinary, 9: OFTDate, 10: OFTTime, 11: OFTDateTime, 12: OFTInteger64, 13: OFTInteger64List, } ROGRFieldTypes = {cls: num for num, cls in OGRFieldTypes.items()}
1cf5a80998f0cec52785ced098a87e041311a890a38f4ed170523abe36dd9e9e
from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.error import GDALException from django.contrib.gis.gdal.field import Field from django.contrib.gis.gdal.geometries import OGRGeometry, OGRGeomType from django.contrib.gis.gdal.prototypes import ds as capi from django.contrib.gis.gdal.prototypes import geom as geom_api from django.utils.encoding import force_bytes, force_str # For more information, see the OGR C API source code: # https://gdal.org/api/vector_c_api.html # # The OGR_F_* routines are relevant here. class Feature(GDALBase): """ This class that wraps an OGR Feature, needs to be instantiated from a Layer object. """ destructor = capi.destroy_feature def __init__(self, feat, layer): """ Initialize Feature from a pointer and its Layer object. """ if not feat: raise GDALException("Cannot create OGR Feature, invalid pointer given.") self.ptr = feat self._layer = layer def __getitem__(self, index): """ Get the Field object at the specified index, which may be either an integer or the Field's string label. Note that the Field object is not the field's _value_ -- use the `get` method instead to retrieve the value (e.g. an integer) instead of a Field instance. """ if isinstance(index, str): i = self.index(index) elif 0 <= index < self.num_fields: i = index else: raise IndexError( "Index out of range when accessing field in a feature: %s." % index ) return Field(self, i) def __len__(self): "Return the count of fields in this feature." return self.num_fields def __str__(self): "The string name of the feature." return "Feature FID %d in Layer<%s>" % (self.fid, self.layer_name) def __eq__(self, other): "Do equivalence testing on the features." return bool(capi.feature_equal(self.ptr, other._ptr)) # #### Feature Properties #### @property def encoding(self): return self._layer._ds.encoding @property def fid(self): "Return the feature identifier." return capi.get_fid(self.ptr) @property def layer_name(self): "Return the name of the layer for the feature." name = capi.get_feat_name(self._layer._ldefn) return force_str(name, self.encoding, strings_only=True) @property def num_fields(self): "Return the number of fields in the Feature." return capi.get_feat_field_count(self.ptr) @property def fields(self): "Return a list of fields in the Feature." return [ force_str( capi.get_field_name(capi.get_field_defn(self._layer._ldefn, i)), self.encoding, strings_only=True, ) for i in range(self.num_fields) ] @property def geom(self): "Return the OGR Geometry for this Feature." # Retrieving the geometry pointer for the feature. geom_ptr = capi.get_feat_geom_ref(self.ptr) return OGRGeometry(geom_api.clone_geom(geom_ptr)) @property def geom_type(self): "Return the OGR Geometry Type for this Feature." return OGRGeomType(capi.get_fd_geom_type(self._layer._ldefn)) # #### Feature Methods #### def get(self, field): """ Return the value of the field, instead of an instance of the Field object. May take a string of the field name or a Field object as parameters. """ field_name = getattr(field, "name", field) return self[field_name].value def index(self, field_name): "Return the index of the given field name." i = capi.get_field_index(self.ptr, force_bytes(field_name)) if i < 0: raise IndexError("Invalid OFT field name given: %s." % field_name) return i
56df948acf73efce94184ded0fb7e3887f3fd0fe474933bcd67e1f69de25ea4c
""" This module houses the GDAL & SRS Exception objects, and the check_err() routine which checks the status code returned by GDAL/OGR methods. """ # #### GDAL & SRS Exceptions #### class GDALException(Exception): pass class SRSException(Exception): pass # #### GDAL/OGR error checking codes and routine #### # OGR Error Codes OGRERR_DICT = { 1: (GDALException, "Not enough data."), 2: (GDALException, "Not enough memory."), 3: (GDALException, "Unsupported geometry type."), 4: (GDALException, "Unsupported operation."), 5: (GDALException, "Corrupt data."), 6: (GDALException, "OGR failure."), 7: (SRSException, "Unsupported SRS."), 8: (GDALException, "Invalid handle."), } # CPL Error Codes # https://gdal.org/api/cpl.html#cpl-error-h CPLERR_DICT = { 1: (GDALException, "AppDefined"), 2: (GDALException, "OutOfMemory"), 3: (GDALException, "FileIO"), 4: (GDALException, "OpenFailed"), 5: (GDALException, "IllegalArg"), 6: (GDALException, "NotSupported"), 7: (GDALException, "AssertionFailed"), 8: (GDALException, "NoWriteAccess"), 9: (GDALException, "UserInterrupt"), 10: (GDALException, "ObjectNull"), } ERR_NONE = 0 def check_err(code, cpl=False): """ Check the given CPL/OGRERR and raise an exception where appropriate. """ err_dict = CPLERR_DICT if cpl else OGRERR_DICT if code == ERR_NONE: return elif code in err_dict: e, msg = err_dict[code] raise e(msg) else: raise GDALException('Unknown error code: "%s"' % code)
023dd09f7dd05a30d8af05f58ded8064e9a891f7f3b3eb38903f7a1cbd5e6ac4
""" The GDAL/OGR library uses an Envelope structure to hold the bounding box information for a geometry. The envelope (bounding box) contains two pairs of coordinates, one for the lower left coordinate and one for the upper right coordinate: +----------o Upper right; (max_x, max_y) | | | | | | Lower left (min_x, min_y) o----------+ """ from ctypes import Structure, c_double from django.contrib.gis.gdal.error import GDALException # The OGR definition of an Envelope is a C structure containing four doubles. # See the 'ogr_core.h' source file for more information: # https://gdal.org/doxygen/ogr__core_8h_source.html class OGREnvelope(Structure): "Represent the OGREnvelope C Structure." _fields_ = [ ("MinX", c_double), ("MaxX", c_double), ("MinY", c_double), ("MaxY", c_double), ] class Envelope: """ The Envelope object is a C structure that contains the minimum and maximum X, Y coordinates for a rectangle bounding box. The naming of the variables is compatible with the OGR Envelope structure. """ def __init__(self, *args): """ The initialization function may take an OGREnvelope structure, 4-element tuple or list, or 4 individual arguments. """ if len(args) == 1: if isinstance(args[0], OGREnvelope): # OGREnvelope (a ctypes Structure) was passed in. self._envelope = args[0] elif isinstance(args[0], (tuple, list)): # A tuple was passed in. if len(args[0]) != 4: raise GDALException( "Incorrect number of tuple elements (%d)." % len(args[0]) ) else: self._from_sequence(args[0]) else: raise TypeError("Incorrect type of argument: %s" % type(args[0])) elif len(args) == 4: # Individual parameters passed in. # Thanks to ww for the help self._from_sequence([float(a) for a in args]) else: raise GDALException("Incorrect number (%d) of arguments." % len(args)) # Checking the x,y coordinates if self.min_x > self.max_x: raise GDALException("Envelope minimum X > maximum X.") if self.min_y > self.max_y: raise GDALException("Envelope minimum Y > maximum Y.") def __eq__(self, other): """ Return True if the envelopes are equivalent; can compare against other Envelopes and 4-tuples. """ if isinstance(other, Envelope): return ( (self.min_x == other.min_x) and (self.min_y == other.min_y) and (self.max_x == other.max_x) and (self.max_y == other.max_y) ) elif isinstance(other, tuple) and len(other) == 4: return ( (self.min_x == other[0]) and (self.min_y == other[1]) and (self.max_x == other[2]) and (self.max_y == other[3]) ) else: raise GDALException("Equivalence testing only works with other Envelopes.") def __str__(self): "Return a string representation of the tuple." return str(self.tuple) def _from_sequence(self, seq): "Initialize the C OGR Envelope structure from the given sequence." self._envelope = OGREnvelope() self._envelope.MinX = seq[0] self._envelope.MinY = seq[1] self._envelope.MaxX = seq[2] self._envelope.MaxY = seq[3] def expand_to_include(self, *args): """ Modify the envelope to expand to include the boundaries of the passed-in 2-tuple (a point), 4-tuple (an extent) or envelope. """ # We provide a number of different signatures for this method, # and the logic here is all about converting them into a # 4-tuple single parameter which does the actual work of # expanding the envelope. if len(args) == 1: if isinstance(args[0], Envelope): return self.expand_to_include(args[0].tuple) elif hasattr(args[0], "x") and hasattr(args[0], "y"): return self.expand_to_include( args[0].x, args[0].y, args[0].x, args[0].y ) elif isinstance(args[0], (tuple, list)): # A tuple was passed in. if len(args[0]) == 2: return self.expand_to_include( (args[0][0], args[0][1], args[0][0], args[0][1]) ) elif len(args[0]) == 4: (minx, miny, maxx, maxy) = args[0] if minx < self._envelope.MinX: self._envelope.MinX = minx if miny < self._envelope.MinY: self._envelope.MinY = miny if maxx > self._envelope.MaxX: self._envelope.MaxX = maxx if maxy > self._envelope.MaxY: self._envelope.MaxY = maxy else: raise GDALException( "Incorrect number of tuple elements (%d)." % len(args[0]) ) else: raise TypeError("Incorrect type of argument: %s" % type(args[0])) elif len(args) == 2: # An x and an y parameter were passed in return self.expand_to_include((args[0], args[1], args[0], args[1])) elif len(args) == 4: # Individual parameters passed in. return self.expand_to_include(args) else: raise GDALException("Incorrect number (%d) of arguments." % len(args[0])) @property def min_x(self): "Return the value of the minimum X coordinate." return self._envelope.MinX @property def min_y(self): "Return the value of the minimum Y coordinate." return self._envelope.MinY @property def max_x(self): "Return the value of the maximum X coordinate." return self._envelope.MaxX @property def max_y(self): "Return the value of the maximum Y coordinate." return self._envelope.MaxY @property def ur(self): "Return the upper-right coordinate." return (self.max_x, self.max_y) @property def ll(self): "Return the lower-left coordinate." return (self.min_x, self.min_y) @property def tuple(self): "Return a tuple representing the envelope." return (self.min_x, self.min_y, self.max_x, self.max_y) @property def wkt(self): "Return WKT representing a Polygon for this envelope." # TODO: Fix significant figures. return "POLYGON((%s %s,%s %s,%s %s,%s %s,%s %s))" % ( self.min_x, self.min_y, self.min_x, self.max_y, self.max_x, self.max_y, self.max_x, self.min_y, self.min_x, self.min_y, )
782ceba8454ec324e571122dad48ab98474d692aec008bf0f633ff67aebdc5db
from ctypes import c_void_p from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.error import GDALException from django.contrib.gis.gdal.prototypes import ds as vcapi from django.contrib.gis.gdal.prototypes import raster as rcapi from django.utils.encoding import force_bytes, force_str class Driver(GDALBase): """ Wrap a GDAL/OGR Data Source Driver. For more information, see the C API documentation: https://gdal.org/api/vector_c_api.html https://gdal.org/api/raster_c_api.html """ # Case-insensitive aliases for some GDAL/OGR Drivers. # For a complete list of original driver names see # https://gdal.org/drivers/vector/ # https://gdal.org/drivers/raster/ _alias = { # vector "esri": "ESRI Shapefile", "shp": "ESRI Shapefile", "shape": "ESRI Shapefile", "tiger": "TIGER", "tiger/line": "TIGER", # raster "tiff": "GTiff", "tif": "GTiff", "jpeg": "JPEG", "jpg": "JPEG", } def __init__(self, dr_input): """ Initialize an GDAL/OGR driver on either a string or integer input. """ if isinstance(dr_input, str): # If a string name of the driver was passed in self.ensure_registered() # Checking the alias dictionary (case-insensitive) to see if an # alias exists for the given driver. if dr_input.lower() in self._alias: name = self._alias[dr_input.lower()] else: name = dr_input # Attempting to get the GDAL/OGR driver by the string name. for iface in (vcapi, rcapi): driver = c_void_p(iface.get_driver_by_name(force_bytes(name))) if driver: break elif isinstance(dr_input, int): self.ensure_registered() for iface in (vcapi, rcapi): driver = iface.get_driver(dr_input) if driver: break elif isinstance(dr_input, c_void_p): driver = dr_input else: raise GDALException( "Unrecognized input type for GDAL/OGR Driver: %s" % type(dr_input) ) # Making sure we get a valid pointer to the OGR Driver if not driver: raise GDALException( "Could not initialize GDAL/OGR Driver on input: %s" % dr_input ) self.ptr = driver def __str__(self): return self.name @classmethod def ensure_registered(cls): """ Attempt to register all the data source drivers. """ # Only register all if the driver counts are 0 (or else all drivers # will be registered over and over again) if not vcapi.get_driver_count(): vcapi.register_all() if not rcapi.get_driver_count(): rcapi.register_all() @classmethod def driver_count(cls): """ Return the number of GDAL/OGR data source drivers registered. """ return vcapi.get_driver_count() + rcapi.get_driver_count() @property def name(self): """ Return description/name string for this driver. """ return force_str(rcapi.get_driver_description(self.ptr))
4df4da15a286a3dcf40bd56b7f7d03e40122fd3883f68d870a832f90c4082fed
import logging import os import re from ctypes import CDLL, CFUNCTYPE, c_char_p, c_int from ctypes.util import find_library from django.contrib.gis.gdal.error import GDALException from django.core.exceptions import ImproperlyConfigured logger = logging.getLogger("django.contrib.gis") # Custom library path set? try: from django.conf import settings lib_path = settings.GDAL_LIBRARY_PATH except (AttributeError, ImportError, ImproperlyConfigured, OSError): lib_path = None if lib_path: lib_names = None elif os.name == "nt": # Windows NT shared libraries lib_names = [ "gdal303", "gdal302", "gdal301", "gdal300", "gdal204", "gdal203", "gdal202", ] elif os.name == "posix": # *NIX library names. lib_names = [ "gdal", "GDAL", "gdal3.3.0", "gdal3.2.0", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0", ] else: raise ImproperlyConfigured('GDAL is unsupported on OS "%s".' % os.name) # Using the ctypes `find_library` utility to find the # path to the GDAL library from the list of library names. if lib_names: for lib_name in lib_names: lib_path = find_library(lib_name) if lib_path is not None: break if lib_path is None: raise ImproperlyConfigured( 'Could not find the GDAL library (tried "%s"). Is GDAL installed? ' "If it is, try setting GDAL_LIBRARY_PATH in your settings." % '", "'.join(lib_names) ) # This loads the GDAL/OGR C library lgdal = CDLL(lib_path) # On Windows, the GDAL binaries have some OSR routines exported with # STDCALL, while others are not. Thus, the library will also need to # be loaded up as WinDLL for said OSR functions that require the # different calling convention. if os.name == "nt": from ctypes import WinDLL lwingdal = WinDLL(lib_path) def std_call(func): """ Return the correct STDCALL function for certain OSR routines on Win32 platforms. """ if os.name == "nt": return lwingdal[func] else: return lgdal[func] # #### Version-information functions. #### # Return GDAL library version information with the given key. _version_info = std_call("GDALVersionInfo") _version_info.argtypes = [c_char_p] _version_info.restype = c_char_p def gdal_version(): "Return only the GDAL version number information." return _version_info(b"RELEASE_NAME") def gdal_full_version(): "Return the full GDAL version information." return _version_info(b"") def gdal_version_info(): ver = gdal_version() m = re.match(rb"^(?P<major>\d+)\.(?P<minor>\d+)(?:\.(?P<subminor>\d+))?", ver) if not m: raise GDALException('Could not parse GDAL version string "%s"' % ver) major, minor, subminor = m.groups() return (int(major), int(minor), subminor and int(subminor)) GDAL_VERSION = gdal_version_info() # Set library error handling so as errors are logged CPLErrorHandler = CFUNCTYPE(None, c_int, c_int, c_char_p) def err_handler(error_class, error_number, message): logger.error("GDAL_ERROR %d: %s", error_number, message) err_handler = CPLErrorHandler(err_handler) def function(name, args, restype): func = std_call(name) func.argtypes = args func.restype = restype return func set_error_handler = function("CPLSetErrorHandler", [CPLErrorHandler], CPLErrorHandler) set_error_handler(err_handler)
3f280082c459cd67a4a7a92ae8d10067abe14134a8d4d938735622fe939d2b9f
from ctypes import byref, c_double from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope from django.contrib.gis.gdal.error import GDALException, SRSException from django.contrib.gis.gdal.feature import Feature from django.contrib.gis.gdal.field import OGRFieldTypes from django.contrib.gis.gdal.geometries import OGRGeometry from django.contrib.gis.gdal.geomtype import OGRGeomType from django.contrib.gis.gdal.prototypes import ds as capi from django.contrib.gis.gdal.prototypes import geom as geom_api from django.contrib.gis.gdal.prototypes import srs as srs_api from django.contrib.gis.gdal.srs import SpatialReference from django.utils.encoding import force_bytes, force_str # For more information, see the OGR C API source code: # https://gdal.org/api/vector_c_api.html # # The OGR_L_* routines are relevant here. class Layer(GDALBase): """ A class that wraps an OGR Layer, needs to be instantiated from a DataSource object. """ def __init__(self, layer_ptr, ds): """ Initialize on an OGR C pointer to the Layer and the `DataSource` object that owns this layer. The `DataSource` object is required so that a reference to it is kept with this Layer. This prevents garbage collection of the `DataSource` while this Layer is still active. """ if not layer_ptr: raise GDALException("Cannot create Layer, invalid pointer given") self.ptr = layer_ptr self._ds = ds self._ldefn = capi.get_layer_defn(self._ptr) # Does the Layer support random reading? self._random_read = self.test_capability(b"RandomRead") def __getitem__(self, index): "Get the Feature at the specified index." if isinstance(index, int): # An integer index was given -- we cannot do a check based on the # number of features because the beginning and ending feature IDs # are not guaranteed to be 0 and len(layer)-1, respectively. if index < 0: raise IndexError("Negative indices are not allowed on OGR Layers.") return self._make_feature(index) elif isinstance(index, slice): # A slice was given start, stop, stride = index.indices(self.num_feat) return [self._make_feature(fid) for fid in range(start, stop, stride)] else: raise TypeError( "Integers and slices may only be used when indexing OGR Layers." ) def __iter__(self): "Iterate over each Feature in the Layer." # ResetReading() must be called before iteration is to begin. capi.reset_reading(self._ptr) for i in range(self.num_feat): yield Feature(capi.get_next_feature(self._ptr), self) def __len__(self): "The length is the number of features." return self.num_feat def __str__(self): "The string name of the layer." return self.name def _make_feature(self, feat_id): """ Helper routine for __getitem__ that constructs a Feature from the given Feature ID. If the OGR Layer does not support random-access reading, then each feature of the layer will be incremented through until the a Feature is found matching the given feature ID. """ if self._random_read: # If the Layer supports random reading, return. try: return Feature(capi.get_feature(self.ptr, feat_id), self) except GDALException: pass else: # Random access isn't supported, have to increment through # each feature until the given feature ID is encountered. for feat in self: if feat.fid == feat_id: return feat # Should have returned a Feature, raise an IndexError. raise IndexError("Invalid feature id: %s." % feat_id) # #### Layer properties #### @property def extent(self): "Return the extent (an Envelope) of this layer." env = OGREnvelope() capi.get_extent(self.ptr, byref(env), 1) return Envelope(env) @property def name(self): "Return the name of this layer in the Data Source." name = capi.get_fd_name(self._ldefn) return force_str(name, self._ds.encoding, strings_only=True) @property def num_feat(self, force=1): "Return the number of features in the Layer." return capi.get_feature_count(self.ptr, force) @property def num_fields(self): "Return the number of fields in the Layer." return capi.get_field_count(self._ldefn) @property def geom_type(self): "Return the geometry type (OGRGeomType) of the Layer." return OGRGeomType(capi.get_fd_geom_type(self._ldefn)) @property def srs(self): "Return the Spatial Reference used in this Layer." try: ptr = capi.get_layer_srs(self.ptr) return SpatialReference(srs_api.clone_srs(ptr)) except SRSException: return None @property def fields(self): """ Return a list of string names corresponding to each of the Fields available in this Layer. """ return [ force_str( capi.get_field_name(capi.get_field_defn(self._ldefn, i)), self._ds.encoding, strings_only=True, ) for i in range(self.num_fields) ] @property def field_types(self): """ Return a list of the types of fields in this Layer. For example, return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that has an integer, a floating-point, and string fields. """ return [ OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))] for i in range(self.num_fields) ] @property def field_widths(self): "Return a list of the maximum field widths for the features." return [ capi.get_field_width(capi.get_field_defn(self._ldefn, i)) for i in range(self.num_fields) ] @property def field_precisions(self): "Return the field precisions for the features." return [ capi.get_field_precision(capi.get_field_defn(self._ldefn, i)) for i in range(self.num_fields) ] def _get_spatial_filter(self): try: return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr))) except GDALException: return None def _set_spatial_filter(self, filter): if isinstance(filter, OGRGeometry): capi.set_spatial_filter(self.ptr, filter.ptr) elif isinstance(filter, (tuple, list)): if not len(filter) == 4: raise ValueError("Spatial filter list/tuple must have 4 elements.") # Map c_double onto params -- if a bad type is passed in it # will be caught here. xmin, ymin, xmax, ymax = map(c_double, filter) capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax) elif filter is None: capi.set_spatial_filter(self.ptr, None) else: raise TypeError( "Spatial filter must be either an OGRGeometry instance, a 4-tuple, or " "None." ) spatial_filter = property(_get_spatial_filter, _set_spatial_filter) # #### Layer Methods #### def get_fields(self, field_name): """ Return a list containing the given field name for every Feature in the Layer. """ if field_name not in self.fields: raise GDALException("invalid field name: %s" % field_name) return [feat.get(field_name) for feat in self] def get_geoms(self, geos=False): """ Return a list containing the OGRGeometry for every Feature in the Layer. """ if geos: from django.contrib.gis.geos import GEOSGeometry return [GEOSGeometry(feat.geom.wkb) for feat in self] else: return [feat.geom for feat in self] def test_capability(self, capability): """ Return a bool indicating whether the this Layer supports the given capability (a string). Valid capability strings include: 'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter', 'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions', 'DeleteFeature', and 'FastSetNextByIndex'. """ return bool(capi.test_capability(self.ptr, force_bytes(capability)))
b8817d58be4519386157faeca4defd0c04c4278d57b5c728dc7f9983b472b8d7
""" The Spatial Reference class, represents OGR Spatial Reference objects. Example: >>> from django.contrib.gis.gdal import SpatialReference >>> srs = SpatialReference('WGS84') >>> print(srs) GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]], TOWGS84[0,0,0,0,0,0,0], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich",0, AUTHORITY["EPSG","8901"]], UNIT["degree",0.01745329251994328, AUTHORITY["EPSG","9122"]], AUTHORITY["EPSG","4326"]] >>> print(srs.proj) +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs >>> print(srs.ellipsoid) (6378137.0, 6356752.3142451793, 298.25722356300003) >>> print(srs.projected, srs.geographic) False True >>> srs.import_epsg(32140) >>> print(srs.name) NAD83 / Texas South Central """ from ctypes import byref, c_char_p, c_int from enum import IntEnum from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.error import SRSException from django.contrib.gis.gdal.libgdal import GDAL_VERSION from django.contrib.gis.gdal.prototypes import srs as capi from django.utils.encoding import force_bytes, force_str class AxisOrder(IntEnum): TRADITIONAL = 0 AUTHORITY = 1 class SpatialReference(GDALBase): """ A wrapper for the OGRSpatialReference object. According to the GDAL web site, the SpatialReference object "provide[s] services to represent coordinate systems (projections and datums) and to transform between them." """ destructor = capi.release_srs def __init__(self, srs_input="", srs_type="user", axis_order=None): """ Create a GDAL OSR Spatial Reference object from the given input. The input may be string of OGC Well Known Text (WKT), an integer EPSG code, a PROJ string, and/or a projection "well known" shorthand string (one of 'WGS84', 'WGS72', 'NAD27', 'NAD83'). """ if not isinstance(axis_order, (type(None), AxisOrder)): raise ValueError( "SpatialReference.axis_order must be an AxisOrder instance." ) self.axis_order = axis_order or AxisOrder.TRADITIONAL if srs_type == "wkt": self.ptr = capi.new_srs(c_char_p(b"")) self.import_wkt(srs_input) if self.axis_order == AxisOrder.TRADITIONAL and GDAL_VERSION >= (3, 0): capi.set_axis_strategy(self.ptr, self.axis_order) elif self.axis_order != AxisOrder.TRADITIONAL and GDAL_VERSION < (3, 0): raise ValueError("%s is not supported in GDAL < 3.0." % self.axis_order) return elif isinstance(srs_input, str): try: # If SRID is a string, e.g., '4326', then make acceptable # as user input. srid = int(srs_input) srs_input = "EPSG:%d" % srid except ValueError: pass elif isinstance(srs_input, int): # EPSG integer code was input. srs_type = "epsg" elif isinstance(srs_input, self.ptr_type): srs = srs_input srs_type = "ogr" else: raise TypeError('Invalid SRS type "%s"' % srs_type) if srs_type == "ogr": # Input is already an SRS pointer. srs = srs_input else: # Creating a new SRS pointer, using the string buffer. buf = c_char_p(b"") srs = capi.new_srs(buf) # If the pointer is NULL, throw an exception. if not srs: raise SRSException( "Could not create spatial reference from: %s" % srs_input ) else: self.ptr = srs if self.axis_order == AxisOrder.TRADITIONAL and GDAL_VERSION >= (3, 0): capi.set_axis_strategy(self.ptr, self.axis_order) elif self.axis_order != AxisOrder.TRADITIONAL and GDAL_VERSION < (3, 0): raise ValueError("%s is not supported in GDAL < 3.0." % self.axis_order) # Importing from either the user input string or an integer SRID. if srs_type == "user": self.import_user_input(srs_input) elif srs_type == "epsg": self.import_epsg(srs_input) def __getitem__(self, target): """ Return the value of the given string attribute node, None if the node doesn't exist. Can also take a tuple as a parameter, (target, child), where child is the index of the attribute in the WKT. For example: >>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]' >>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326 >>> print(srs['GEOGCS']) WGS 84 >>> print(srs['DATUM']) WGS_1984 >>> print(srs['AUTHORITY']) EPSG >>> print(srs['AUTHORITY', 1]) # The authority value 4326 >>> print(srs['TOWGS84', 4]) # the fourth value in this wkt 0 >>> # For the units authority, have to use the pipe symbole. >>> print(srs['UNIT|AUTHORITY']) EPSG >>> print(srs['UNIT|AUTHORITY', 1]) # The authority value for the units 9122 """ if isinstance(target, tuple): return self.attr_value(*target) else: return self.attr_value(target) def __str__(self): "Use 'pretty' WKT." return self.pretty_wkt # #### SpatialReference Methods #### def attr_value(self, target, index=0): """ The attribute value for the given target node (e.g. 'PROJCS'). The index keyword specifies an index of the child node to return. """ if not isinstance(target, str) or not isinstance(index, int): raise TypeError return capi.get_attr_value(self.ptr, force_bytes(target), index) def auth_name(self, target): "Return the authority name for the given string target node." return capi.get_auth_name(self.ptr, force_bytes(target)) def auth_code(self, target): "Return the authority code for the given string target node." return capi.get_auth_code(self.ptr, force_bytes(target)) def clone(self): "Return a clone of this SpatialReference object." return SpatialReference(capi.clone_srs(self.ptr), axis_order=self.axis_order) def from_esri(self): "Morph this SpatialReference from ESRI's format to EPSG." capi.morph_from_esri(self.ptr) def identify_epsg(self): """ This method inspects the WKT of this SpatialReference, and will add EPSG authority nodes where an EPSG identifier is applicable. """ capi.identify_epsg(self.ptr) def to_esri(self): "Morph this SpatialReference to ESRI's format." capi.morph_to_esri(self.ptr) def validate(self): "Check to see if the given spatial reference is valid." capi.srs_validate(self.ptr) # #### Name & SRID properties #### @property def name(self): "Return the name of this Spatial Reference." if self.projected: return self.attr_value("PROJCS") elif self.geographic: return self.attr_value("GEOGCS") elif self.local: return self.attr_value("LOCAL_CS") else: return None @property def srid(self): "Return the SRID of top-level authority, or None if undefined." try: return int(self.attr_value("AUTHORITY", 1)) except (TypeError, ValueError): return None # #### Unit Properties #### @property def linear_name(self): "Return the name of the linear units." units, name = capi.linear_units(self.ptr, byref(c_char_p())) return name @property def linear_units(self): "Return the value of the linear units." units, name = capi.linear_units(self.ptr, byref(c_char_p())) return units @property def angular_name(self): "Return the name of the angular units." units, name = capi.angular_units(self.ptr, byref(c_char_p())) return name @property def angular_units(self): "Return the value of the angular units." units, name = capi.angular_units(self.ptr, byref(c_char_p())) return units @property def units(self): """ Return a 2-tuple of the units value and the units name. Automatically determine whether to return the linear or angular units. """ units, name = None, None if self.projected or self.local: units, name = capi.linear_units(self.ptr, byref(c_char_p())) elif self.geographic: units, name = capi.angular_units(self.ptr, byref(c_char_p())) if name is not None: name = force_str(name) return (units, name) # #### Spheroid/Ellipsoid Properties #### @property def ellipsoid(self): """ Return a tuple of the ellipsoid parameters: (semimajor axis, semiminor axis, and inverse flattening) """ return (self.semi_major, self.semi_minor, self.inverse_flattening) @property def semi_major(self): "Return the Semi Major Axis for this Spatial Reference." return capi.semi_major(self.ptr, byref(c_int())) @property def semi_minor(self): "Return the Semi Minor Axis for this Spatial Reference." return capi.semi_minor(self.ptr, byref(c_int())) @property def inverse_flattening(self): "Return the Inverse Flattening for this Spatial Reference." return capi.invflattening(self.ptr, byref(c_int())) # #### Boolean Properties #### @property def geographic(self): """ Return True if this SpatialReference is geographic (root node is GEOGCS). """ return bool(capi.isgeographic(self.ptr)) @property def local(self): "Return True if this SpatialReference is local (root node is LOCAL_CS)." return bool(capi.islocal(self.ptr)) @property def projected(self): """ Return True if this SpatialReference is a projected coordinate system (root node is PROJCS). """ return bool(capi.isprojected(self.ptr)) # #### Import Routines ##### def import_epsg(self, epsg): "Import the Spatial Reference from the EPSG code (an integer)." capi.from_epsg(self.ptr, epsg) def import_proj(self, proj): """Import the Spatial Reference from a PROJ string.""" capi.from_proj(self.ptr, proj) def import_user_input(self, user_input): "Import the Spatial Reference from the given user input string." capi.from_user_input(self.ptr, force_bytes(user_input)) def import_wkt(self, wkt): "Import the Spatial Reference from OGC WKT (string)" capi.from_wkt(self.ptr, byref(c_char_p(force_bytes(wkt)))) def import_xml(self, xml): "Import the Spatial Reference from an XML string." capi.from_xml(self.ptr, xml) # #### Export Properties #### @property def wkt(self): "Return the WKT representation of this Spatial Reference." return capi.to_wkt(self.ptr, byref(c_char_p())) @property def pretty_wkt(self, simplify=0): "Return the 'pretty' representation of the WKT." return capi.to_pretty_wkt(self.ptr, byref(c_char_p()), simplify) @property def proj(self): """Return the PROJ representation for this Spatial Reference.""" return capi.to_proj(self.ptr, byref(c_char_p())) @property def proj4(self): "Alias for proj()." return self.proj @property def xml(self, dialect=""): "Return the XML representation of this Spatial Reference." return capi.to_xml(self.ptr, byref(c_char_p()), force_bytes(dialect)) class CoordTransform(GDALBase): "The coordinate system transformation object." destructor = capi.destroy_ct def __init__(self, source, target): "Initialize on a source and target SpatialReference objects." if not isinstance(source, SpatialReference) or not isinstance( target, SpatialReference ): raise TypeError("source and target must be of type SpatialReference") self.ptr = capi.new_ct(source._ptr, target._ptr) self._srs1_name = source.name self._srs2_name = target.name def __str__(self): return 'Transform from "%s" to "%s"' % (self._srs1_name, self._srs2_name)
e18f06b5b5d9e64989bad4800d58ad88c072cf767deb099795e17d6d40b92f7c
from django.contrib.admin import ( HORIZONTAL, VERTICAL, AdminSite, ModelAdmin, StackedInline, TabularInline, action, autodiscover, display, register, site, ) from django.contrib.gis.admin.options import GeoModelAdmin, GISModelAdmin, OSMGeoAdmin from django.contrib.gis.admin.widgets import OpenLayersWidget __all__ = [ "HORIZONTAL", "VERTICAL", "AdminSite", "ModelAdmin", "StackedInline", "TabularInline", "action", "autodiscover", "display", "register", "site", "GISModelAdmin", "OpenLayersWidget", # RemovedInDjango50Warning. "GeoModelAdmin", "OSMGeoAdmin", ]
edd47ab7f903df299afe9733f20c2bb9d5a229b68890887a7055fb4f996aa165
import warnings from django.contrib.admin import ModelAdmin from django.contrib.gis.admin.widgets import OpenLayersWidget from django.contrib.gis.db import models from django.contrib.gis.forms import OSMWidget from django.contrib.gis.gdal import OGRGeomType from django.forms import Media from django.utils.deprecation import RemovedInDjango50Warning class GeoModelAdminMixin: gis_widget = OSMWidget gis_widget_kwargs = {} def formfield_for_dbfield(self, db_field, request, **kwargs): if isinstance(db_field, models.GeometryField) and ( db_field.dim < 3 or self.gis_widget.supports_3d ): kwargs["widget"] = self.gis_widget(**self.gis_widget_kwargs) return db_field.formfield(**kwargs) else: return super().formfield_for_dbfield(db_field, request, **kwargs) class GISModelAdmin(GeoModelAdminMixin, ModelAdmin): pass # RemovedInDjango50Warning. spherical_mercator_srid = 3857 # RemovedInDjango50Warning. class GeoModelAdmin(ModelAdmin): """ The administration options class for Geographic models. Map settings may be overloaded from their defaults to create custom maps. """ # The default map settings that may be overloaded -- still subject # to API changes. default_lon = 0 default_lat = 0 default_zoom = 4 display_wkt = False display_srid = False extra_js = [] num_zoom = 18 max_zoom = False min_zoom = False units = False max_resolution = False max_extent = False modifiable = True mouse_position = True scale_text = True layerswitcher = True scrollable = True map_width = 600 map_height = 400 map_srid = 4326 map_template = "gis/admin/openlayers.html" openlayers_url = ( "https://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/OpenLayers.js" ) point_zoom = num_zoom - 6 wms_url = "http://vmap0.tiles.osgeo.org/wms/vmap0" wms_layer = "basic" wms_name = "OpenLayers WMS" wms_options = {"format": "image/jpeg"} debug = False widget = OpenLayersWidget def __init__(self, *args, **kwargs): warnings.warn( "django.contrib.gis.admin.GeoModelAdmin and OSMGeoAdmin are " "deprecated in favor of django.contrib.admin.ModelAdmin and " "django.contrib.gis.admin.GISModelAdmin.", RemovedInDjango50Warning, stacklevel=2, ) super().__init__(*args, **kwargs) @property def media(self): "Injects OpenLayers JavaScript into the admin." return super().media + Media(js=[self.openlayers_url] + self.extra_js) def formfield_for_dbfield(self, db_field, request, **kwargs): """ Overloaded from ModelAdmin so that an OpenLayersWidget is used for viewing/editing 2D GeometryFields (OpenLayers 2 does not support 3D editing). """ if isinstance(db_field, models.GeometryField) and db_field.dim < 3: # Setting the widget with the newly defined widget. kwargs["widget"] = self.get_map_widget(db_field) return db_field.formfield(**kwargs) else: return super().formfield_for_dbfield(db_field, request, **kwargs) def get_map_widget(self, db_field): """ Return a subclass of the OpenLayersWidget (or whatever was specified in the `widget` attribute) using the settings from the attributes set in this class. """ is_collection = db_field.geom_type in ( "MULTIPOINT", "MULTILINESTRING", "MULTIPOLYGON", "GEOMETRYCOLLECTION", ) if is_collection: if db_field.geom_type == "GEOMETRYCOLLECTION": collection_type = "Any" else: collection_type = OGRGeomType(db_field.geom_type.replace("MULTI", "")) else: collection_type = "None" class OLMap(self.widget): template_name = self.map_template geom_type = db_field.geom_type wms_options = "" if self.wms_options: wms_options = ["%s: '%s'" % pair for pair in self.wms_options.items()] wms_options = ", %s" % ", ".join(wms_options) params = { "default_lon": self.default_lon, "default_lat": self.default_lat, "default_zoom": self.default_zoom, "display_wkt": self.debug or self.display_wkt, "geom_type": OGRGeomType(db_field.geom_type), "field_name": db_field.name, "is_collection": is_collection, "scrollable": self.scrollable, "layerswitcher": self.layerswitcher, "collection_type": collection_type, "is_generic": db_field.geom_type == "GEOMETRY", "is_linestring": db_field.geom_type in ("LINESTRING", "MULTILINESTRING"), "is_polygon": db_field.geom_type in ("POLYGON", "MULTIPOLYGON"), "is_point": db_field.geom_type in ("POINT", "MULTIPOINT"), "num_zoom": self.num_zoom, "max_zoom": self.max_zoom, "min_zoom": self.min_zoom, "units": self.units, # likely should get from object "max_resolution": self.max_resolution, "max_extent": self.max_extent, "modifiable": self.modifiable, "mouse_position": self.mouse_position, "scale_text": self.scale_text, "map_width": self.map_width, "map_height": self.map_height, "point_zoom": self.point_zoom, "srid": self.map_srid, "display_srid": self.display_srid, "wms_url": self.wms_url, "wms_layer": self.wms_layer, "wms_name": self.wms_name, "wms_options": wms_options, "debug": self.debug, } return OLMap # RemovedInDjango50Warning. class OSMGeoAdmin(GeoModelAdmin): map_template = "gis/admin/osm.html" num_zoom = 20 map_srid = spherical_mercator_srid max_extent = "-20037508,-20037508,20037508,20037508" max_resolution = "156543.0339" point_zoom = num_zoom - 6 units = "m"
fcf47b15ec829444a351a6c22c07729dec18b9f4c54b0e6226161cb90349e02e
import logging from django.contrib.gis.gdal import GDALException from django.contrib.gis.geos import GEOSException, GEOSGeometry from django.forms.widgets import Textarea from django.utils import translation # Creating a template context that contains Django settings # values needed by admin map templates. geo_context = {"LANGUAGE_BIDI": translation.get_language_bidi()} logger = logging.getLogger("django.contrib.gis") class OpenLayersWidget(Textarea): """ Render an OpenLayers map using the WKT of the geometry. """ def get_context(self, name, value, attrs): # Update the template parameters with any attributes passed in. if attrs: self.params.update(attrs) self.params["editable"] = self.params["modifiable"] else: self.params["editable"] = True # Defaulting the WKT value to a blank string -- this # will be tested in the JavaScript and the appropriate # interface will be constructed. self.params["wkt"] = "" # If a string reaches here (via a validation error on another # field) then just reconstruct the Geometry. if value and isinstance(value, str): try: value = GEOSGeometry(value) except (GEOSException, ValueError) as err: logger.error("Error creating geometry from value '%s' (%s)", value, err) value = None if ( value and value.geom_type.upper() != self.geom_type and self.geom_type != "GEOMETRY" ): value = None # Constructing the dictionary of the map options. self.params["map_options"] = self.map_options() # Constructing the JavaScript module name using the name of # the GeometryField (passed in via the `attrs` keyword). # Use the 'name' attr for the field name (rather than 'field') self.params["name"] = name # note: we must switch out dashes for underscores since js # functions are created using the module variable js_safe_name = self.params["name"].replace("-", "_") self.params["module"] = "geodjango_%s" % js_safe_name if value: # Transforming the geometry to the projection used on the # OpenLayers map. srid = self.params["srid"] if value.srid != srid: try: ogr = value.ogr ogr.transform(srid) wkt = ogr.wkt except GDALException as err: logger.error( "Error transforming geometry from srid '%s' to srid '%s' (%s)", value.srid, srid, err, ) wkt = "" else: wkt = value.wkt # Setting the parameter WKT with that of the transformed # geometry. self.params["wkt"] = wkt self.params.update(geo_context) return self.params def map_options(self): """Build the map options hash for the OpenLayers template.""" # JavaScript construction utilities for the Bounds and Projection. def ol_bounds(extent): return "new OpenLayers.Bounds(%s)" % extent def ol_projection(srid): return 'new OpenLayers.Projection("EPSG:%s")' % srid # An array of the parameter name, the name of their OpenLayers # counterpart, and the type of variable they are. map_types = [ ("srid", "projection", "srid"), ("display_srid", "displayProjection", "srid"), ("units", "units", str), ("max_resolution", "maxResolution", float), ("max_extent", "maxExtent", "bounds"), ("num_zoom", "numZoomLevels", int), ("max_zoom", "maxZoomLevels", int), ("min_zoom", "minZoomLevel", int), ] # Building the map options hash. map_options = {} for param_name, js_name, option_type in map_types: if self.params.get(param_name, False): if option_type == "srid": value = ol_projection(self.params[param_name]) elif option_type == "bounds": value = ol_bounds(self.params[param_name]) elif option_type in (float, int): value = self.params[param_name] elif option_type in (str,): value = '"%s"' % self.params[param_name] else: raise TypeError map_options[js_name] = value return map_options
9ed842b50d05b09ac319ddbd712111c176feb499292b7e557344ffcb00a75e07
# Copyright (c) 2008-2009 Aryeh Leib Taurog, all rights reserved. # Released under the New BSD license. """ This module contains a base type which provides list-style mutations without specific data storage methods. See also http://static.aryehleib.com/oldsite/MutableLists.html Author: Aryeh Leib Taurog. """ from functools import total_ordering @total_ordering class ListMixin: """ A base class which provides complete list interface. Derived classes must call ListMixin's __init__() function and implement the following: function _get_single_external(self, i): Return single item with index i for general use. The index i will always satisfy 0 <= i < len(self). function _get_single_internal(self, i): Same as above, but for use within the class [Optional] Note that if _get_single_internal and _get_single_internal return different types of objects, _set_list must distinguish between the two and handle each appropriately. function _set_list(self, length, items): Recreate the entire object. NOTE: items may be a generator which calls _get_single_internal. Therefore, it is necessary to cache the values in a temporary: temp = list(items) before clobbering the original storage. function _set_single(self, i, value): Set the single item at index i to value [Optional] If left undefined, all mutations will result in rebuilding the object using _set_list. function __len__(self): Return the length int _minlength: The minimum legal length [Optional] int _maxlength: The maximum legal length [Optional] type or tuple _allowed: A type or tuple of allowed item types [Optional] """ _minlength = 0 _maxlength = None # ### Python initialization and special list interface methods ### def __init__(self, *args, **kwargs): if not hasattr(self, "_get_single_internal"): self._get_single_internal = self._get_single_external if not hasattr(self, "_set_single"): self._set_single = self._set_single_rebuild self._assign_extended_slice = self._assign_extended_slice_rebuild super().__init__(*args, **kwargs) def __getitem__(self, index): "Get the item(s) at the specified index/slice." if isinstance(index, slice): return [ self._get_single_external(i) for i in range(*index.indices(len(self))) ] else: index = self._checkindex(index) return self._get_single_external(index) def __delitem__(self, index): "Delete the item(s) at the specified index/slice." if not isinstance(index, (int, slice)): raise TypeError("%s is not a legal index" % index) # calculate new length and dimensions origLen = len(self) if isinstance(index, int): index = self._checkindex(index) indexRange = [index] else: indexRange = range(*index.indices(origLen)) newLen = origLen - len(indexRange) newItems = ( self._get_single_internal(i) for i in range(origLen) if i not in indexRange ) self._rebuild(newLen, newItems) def __setitem__(self, index, val): "Set the item(s) at the specified index/slice." if isinstance(index, slice): self._set_slice(index, val) else: index = self._checkindex(index) self._check_allowed((val,)) self._set_single(index, val) # ### Special methods for arithmetic operations ### def __add__(self, other): "add another list-like object" return self.__class__([*self, *other]) def __radd__(self, other): "add to another list-like object" return other.__class__([*other, *self]) def __iadd__(self, other): "add another list-like object to self" self.extend(other) return self def __mul__(self, n): "multiply" return self.__class__(list(self) * n) def __rmul__(self, n): "multiply" return self.__class__(list(self) * n) def __imul__(self, n): "multiply" if n <= 0: del self[:] else: cache = list(self) for i in range(n - 1): self.extend(cache) return self def __eq__(self, other): olen = len(other) for i in range(olen): try: c = self[i] == other[i] except IndexError: # self must be shorter return False if not c: return False return len(self) == olen def __lt__(self, other): olen = len(other) for i in range(olen): try: c = self[i] < other[i] except IndexError: # self must be shorter return True if c: return c elif other[i] < self[i]: return False return len(self) < olen # ### Public list interface Methods ### # ## Non-mutating ## def count(self, val): "Standard list count method" count = 0 for i in self: if val == i: count += 1 return count def index(self, val): "Standard list index method" for i in range(0, len(self)): if self[i] == val: return i raise ValueError("%s not found in object" % val) # ## Mutating ## def append(self, val): "Standard list append method" self[len(self) :] = [val] def extend(self, vals): "Standard list extend method" self[len(self) :] = vals def insert(self, index, val): "Standard list insert method" if not isinstance(index, int): raise TypeError("%s is not a legal index" % index) self[index:index] = [val] def pop(self, index=-1): "Standard list pop method" result = self[index] del self[index] return result def remove(self, val): "Standard list remove method" del self[self.index(val)] def reverse(self): "Standard list reverse method" self[:] = self[-1::-1] def sort(self, key=None, reverse=False): "Standard list sort method" self[:] = sorted(self, key=key, reverse=reverse) # ### Private routines ### def _rebuild(self, newLen, newItems): if newLen and newLen < self._minlength: raise ValueError("Must have at least %d items" % self._minlength) if self._maxlength is not None and newLen > self._maxlength: raise ValueError("Cannot have more than %d items" % self._maxlength) self._set_list(newLen, newItems) def _set_single_rebuild(self, index, value): self._set_slice(slice(index, index + 1, 1), [value]) def _checkindex(self, index): length = len(self) if 0 <= index < length: return index if -length <= index < 0: return index + length raise IndexError("invalid index: %s" % index) def _check_allowed(self, items): if hasattr(self, "_allowed"): if False in [isinstance(val, self._allowed) for val in items]: raise TypeError("Invalid type encountered in the arguments.") def _set_slice(self, index, values): "Assign values to a slice of the object" try: valueList = list(values) except TypeError: raise TypeError("can only assign an iterable to a slice") self._check_allowed(valueList) origLen = len(self) start, stop, step = index.indices(origLen) # CAREFUL: index.step and step are not the same! # step will never be None if index.step is None: self._assign_simple_slice(start, stop, valueList) else: self._assign_extended_slice(start, stop, step, valueList) def _assign_extended_slice_rebuild(self, start, stop, step, valueList): "Assign an extended slice by rebuilding entire list" indexList = range(start, stop, step) # extended slice, only allow assigning slice of same size if len(valueList) != len(indexList): raise ValueError( "attempt to assign sequence of size %d " "to extended slice of size %d" % (len(valueList), len(indexList)) ) # we're not changing the length of the sequence newLen = len(self) newVals = dict(zip(indexList, valueList)) def newItems(): for i in range(newLen): if i in newVals: yield newVals[i] else: yield self._get_single_internal(i) self._rebuild(newLen, newItems()) def _assign_extended_slice(self, start, stop, step, valueList): "Assign an extended slice by re-assigning individual items" indexList = range(start, stop, step) # extended slice, only allow assigning slice of same size if len(valueList) != len(indexList): raise ValueError( "attempt to assign sequence of size %d " "to extended slice of size %d" % (len(valueList), len(indexList)) ) for i, val in zip(indexList, valueList): self._set_single(i, val) def _assign_simple_slice(self, start, stop, valueList): "Assign a simple slice; Can assign slice of any length" origLen = len(self) stop = max(start, stop) newLen = origLen - stop + start + len(valueList) def newItems(): for i in range(origLen + 1): if i == start: yield from valueList if i < origLen: if i < start or i >= stop: yield self._get_single_internal(i) self._rebuild(newLen, newItems())
a77fa6ef28eac6c28f84b671bcba1052d34a125337b508dbb3ceb42d30929d83
""" This module houses the Geometry Collection objects: GeometryCollection, MultiPoint, MultiLineString, and MultiPolygon """ from django.contrib.gis.geos import prototypes as capi from django.contrib.gis.geos.geometry import GEOSGeometry, LinearGeometryMixin from django.contrib.gis.geos.libgeos import GEOM_PTR from django.contrib.gis.geos.linestring import LinearRing, LineString from django.contrib.gis.geos.point import Point from django.contrib.gis.geos.polygon import Polygon class GeometryCollection(GEOSGeometry): _typeid = 7 def __init__(self, *args, **kwargs): "Initialize a Geometry Collection from a sequence of Geometry objects." # Checking the arguments if len(args) == 1: # If only one geometry provided or a list of geometries is provided # in the first argument. if isinstance(args[0], (tuple, list)): init_geoms = args[0] else: init_geoms = args else: init_geoms = args # Ensuring that only the permitted geometries are allowed in this collection # this is moved to list mixin super class self._check_allowed(init_geoms) # Creating the geometry pointer array. collection = self._create_collection(len(init_geoms), init_geoms) super().__init__(collection, **kwargs) def __iter__(self): "Iterate over each Geometry in the Collection." for i in range(len(self)): yield self[i] def __len__(self): "Return the number of geometries in this Collection." return self.num_geom # ### Methods for compatibility with ListMixin ### def _create_collection(self, length, items): # Creating the geometry pointer array. geoms = (GEOM_PTR * length)( *[ # this is a little sloppy, but makes life easier # allow GEOSGeometry types (python wrappers) or pointer types capi.geom_clone(getattr(g, "ptr", g)) for g in items ] ) return capi.create_collection(self._typeid, geoms, length) def _get_single_internal(self, index): return capi.get_geomn(self.ptr, index) def _get_single_external(self, index): "Return the Geometry from this Collection at the given index (0-based)." # Checking the index and returning the corresponding GEOS geometry. return GEOSGeometry( capi.geom_clone(self._get_single_internal(index)), srid=self.srid ) def _set_list(self, length, items): "Create a new collection, and destroy the contents of the previous pointer." prev_ptr = self.ptr srid = self.srid self.ptr = self._create_collection(length, items) if srid: self.srid = srid capi.destroy_geom(prev_ptr) _set_single = GEOSGeometry._set_single_rebuild _assign_extended_slice = GEOSGeometry._assign_extended_slice_rebuild @property def kml(self): "Return the KML for this Geometry Collection." return "<MultiGeometry>%s</MultiGeometry>" % "".join(g.kml for g in self) @property def tuple(self): "Return a tuple of all the coordinates in this Geometry Collection" return tuple(g.tuple for g in self) coords = tuple # MultiPoint, MultiLineString, and MultiPolygon class definitions. class MultiPoint(GeometryCollection): _allowed = Point _typeid = 4 class MultiLineString(LinearGeometryMixin, GeometryCollection): _allowed = (LineString, LinearRing) _typeid = 5 class MultiPolygon(GeometryCollection): _allowed = Polygon _typeid = 6 # Setting the allowed types here since GeometryCollection is defined before # its subclasses. GeometryCollection._allowed = ( Point, LineString, LinearRing, Polygon, MultiPoint, MultiLineString, MultiPolygon, )
8d2a249b440b04a8eeefb753a9d8197b0237d88312c5bd932d44459accacf7fd
""" This module contains the 'base' GEOSGeometry object -- all GEOS Geometries inherit from this object. """ import re from ctypes import addressof, byref, c_double from django.contrib.gis import gdal from django.contrib.gis.geometry import hex_regex, json_regex, wkt_regex from django.contrib.gis.geos import prototypes as capi from django.contrib.gis.geos.base import GEOSBase from django.contrib.gis.geos.coordseq import GEOSCoordSeq from django.contrib.gis.geos.error import GEOSException from django.contrib.gis.geos.libgeos import GEOM_PTR, geos_version_tuple from django.contrib.gis.geos.mutable_list import ListMixin from django.contrib.gis.geos.prepared import PreparedGeometry from django.contrib.gis.geos.prototypes.io import ewkb_w, wkb_r, wkb_w, wkt_r, wkt_w from django.utils.deconstruct import deconstructible from django.utils.encoding import force_bytes, force_str class GEOSGeometryBase(GEOSBase): _GEOS_CLASSES = None ptr_type = GEOM_PTR destructor = capi.destroy_geom has_cs = False # Only Point, LineString, LinearRing have coordinate sequences def __init__(self, ptr, cls): self._ptr = ptr # Setting the class type (e.g., Point, Polygon, etc.) if type(self) in (GEOSGeometryBase, GEOSGeometry): if cls is None: if GEOSGeometryBase._GEOS_CLASSES is None: # Inner imports avoid import conflicts with GEOSGeometry. from .collections import ( GeometryCollection, MultiLineString, MultiPoint, MultiPolygon, ) from .linestring import LinearRing, LineString from .point import Point from .polygon import Polygon GEOSGeometryBase._GEOS_CLASSES = { 0: Point, 1: LineString, 2: LinearRing, 3: Polygon, 4: MultiPoint, 5: MultiLineString, 6: MultiPolygon, 7: GeometryCollection, } cls = GEOSGeometryBase._GEOS_CLASSES[self.geom_typeid] self.__class__ = cls self._post_init() def _post_init(self): "Perform post-initialization setup." # Setting the coordinate sequence for the geometry (will be None on # geometries that do not have coordinate sequences) self._cs = ( GEOSCoordSeq(capi.get_cs(self.ptr), self.hasz) if self.has_cs else None ) def __copy__(self): """ Return a clone because the copy of a GEOSGeometry may contain an invalid pointer location if the original is garbage collected. """ return self.clone() def __deepcopy__(self, memodict): """ The `deepcopy` routine is used by the `Node` class of django.utils.tree; thus, the protocol routine needs to be implemented to return correct copies (clones) of these GEOS objects, which use C pointers. """ return self.clone() def __str__(self): "EWKT is used for the string representation." return self.ewkt def __repr__(self): "Short-hand representation because WKT may be very large." return "<%s object at %s>" % (self.geom_type, hex(addressof(self.ptr))) # Pickling support def _to_pickle_wkb(self): return bytes(self.wkb) def _from_pickle_wkb(self, wkb): return wkb_r().read(memoryview(wkb)) def __getstate__(self): # The pickled state is simply a tuple of the WKB (in string form) # and the SRID. return self._to_pickle_wkb(), self.srid def __setstate__(self, state): # Instantiating from the tuple state that was pickled. wkb, srid = state ptr = self._from_pickle_wkb(wkb) if not ptr: raise GEOSException("Invalid Geometry loaded from pickled state.") self.ptr = ptr self._post_init() self.srid = srid @classmethod def _from_wkb(cls, wkb): return wkb_r().read(wkb) @staticmethod def from_ewkt(ewkt): ewkt = force_bytes(ewkt) srid = None parts = ewkt.split(b";", 1) if len(parts) == 2: srid_part, wkt = parts match = re.match(rb"SRID=(?P<srid>\-?\d+)", srid_part) if not match: raise ValueError("EWKT has invalid SRID part.") srid = int(match["srid"]) else: wkt = ewkt if not wkt: raise ValueError("Expected WKT but got an empty string.") return GEOSGeometry(GEOSGeometry._from_wkt(wkt), srid=srid) @staticmethod def _from_wkt(wkt): return wkt_r().read(wkt) @classmethod def from_gml(cls, gml_string): return gdal.OGRGeometry.from_gml(gml_string).geos # Comparison operators def __eq__(self, other): """ Equivalence testing, a Geometry may be compared with another Geometry or an EWKT representation. """ if isinstance(other, str): try: other = GEOSGeometry.from_ewkt(other) except (ValueError, GEOSException): return False return ( isinstance(other, GEOSGeometry) and self.srid == other.srid and self.equals_exact(other) ) def __hash__(self): return hash((self.srid, self.wkt)) # ### Geometry set-like operations ### # Thanks to Sean Gillies for inspiration: # http://lists.gispython.org/pipermail/community/2007-July/001034.html # g = g1 | g2 def __or__(self, other): "Return the union of this Geometry and the other." return self.union(other) # g = g1 & g2 def __and__(self, other): "Return the intersection of this Geometry and the other." return self.intersection(other) # g = g1 - g2 def __sub__(self, other): "Return the difference this Geometry and the other." return self.difference(other) # g = g1 ^ g2 def __xor__(self, other): "Return the symmetric difference of this Geometry and the other." return self.sym_difference(other) # #### Coordinate Sequence Routines #### @property def coord_seq(self): "Return a clone of the coordinate sequence for this Geometry." if self.has_cs: return self._cs.clone() # #### Geometry Info #### @property def geom_type(self): "Return a string representing the Geometry type, e.g. 'Polygon'" return capi.geos_type(self.ptr).decode() @property def geom_typeid(self): "Return an integer representing the Geometry type." return capi.geos_typeid(self.ptr) @property def num_geom(self): "Return the number of geometries in the Geometry." return capi.get_num_geoms(self.ptr) @property def num_coords(self): "Return the number of coordinates in the Geometry." return capi.get_num_coords(self.ptr) @property def num_points(self): "Return the number points, or coordinates, in the Geometry." return self.num_coords @property def dims(self): "Return the dimension of this Geometry (0=point, 1=line, 2=surface)." return capi.get_dims(self.ptr) def normalize(self): "Convert this Geometry to normal form (or canonical form)." capi.geos_normalize(self.ptr) def make_valid(self): """ Attempt to create a valid representation of a given invalid geometry without losing any of the input vertices. """ if geos_version_tuple() < (3, 8): raise GEOSException("GEOSGeometry.make_valid() requires GEOS >= 3.8.0.") return GEOSGeometry(capi.geos_makevalid(self.ptr), srid=self.srid) # #### Unary predicates #### @property def empty(self): """ Return a boolean indicating whether the set of points in this Geometry are empty. """ return capi.geos_isempty(self.ptr) @property def hasz(self): "Return whether the geometry has a 3D dimension." return capi.geos_hasz(self.ptr) @property def ring(self): "Return whether or not the geometry is a ring." return capi.geos_isring(self.ptr) @property def simple(self): "Return false if the Geometry isn't simple." return capi.geos_issimple(self.ptr) @property def valid(self): "Test the validity of this Geometry." return capi.geos_isvalid(self.ptr) @property def valid_reason(self): """ Return a string containing the reason for any invalidity. """ return capi.geos_isvalidreason(self.ptr).decode() # #### Binary predicates. #### def contains(self, other): "Return true if other.within(this) returns true." return capi.geos_contains(self.ptr, other.ptr) def covers(self, other): """ Return True if the DE-9IM Intersection Matrix for the two geometries is T*****FF*, *T****FF*, ***T**FF*, or ****T*FF*. If either geometry is empty, return False. """ return capi.geos_covers(self.ptr, other.ptr) def crosses(self, other): """ Return true if the DE-9IM intersection matrix for the two Geometries is T*T****** (for a point and a curve,a point and an area or a line and an area) 0******** (for two curves). """ return capi.geos_crosses(self.ptr, other.ptr) def disjoint(self, other): """ Return true if the DE-9IM intersection matrix for the two Geometries is FF*FF****. """ return capi.geos_disjoint(self.ptr, other.ptr) def equals(self, other): """ Return true if the DE-9IM intersection matrix for the two Geometries is T*F**FFF*. """ return capi.geos_equals(self.ptr, other.ptr) def equals_exact(self, other, tolerance=0): """ Return true if the two Geometries are exactly equal, up to a specified tolerance. """ return capi.geos_equalsexact(self.ptr, other.ptr, float(tolerance)) def intersects(self, other): "Return true if disjoint return false." return capi.geos_intersects(self.ptr, other.ptr) def overlaps(self, other): """ Return true if the DE-9IM intersection matrix for the two Geometries is T*T***T** (for two points or two surfaces) 1*T***T** (for two curves). """ return capi.geos_overlaps(self.ptr, other.ptr) def relate_pattern(self, other, pattern): """ Return true if the elements in the DE-9IM intersection matrix for the two Geometries match the elements in pattern. """ if not isinstance(pattern, str) or len(pattern) > 9: raise GEOSException("invalid intersection matrix pattern") return capi.geos_relatepattern(self.ptr, other.ptr, force_bytes(pattern)) def touches(self, other): """ Return true if the DE-9IM intersection matrix for the two Geometries is FT*******, F**T***** or F***T****. """ return capi.geos_touches(self.ptr, other.ptr) def within(self, other): """ Return true if the DE-9IM intersection matrix for the two Geometries is T*F**F***. """ return capi.geos_within(self.ptr, other.ptr) # #### SRID Routines #### @property def srid(self): "Get the SRID for the geometry. Return None if no SRID is set." s = capi.geos_get_srid(self.ptr) if s == 0: return None else: return s @srid.setter def srid(self, srid): "Set the SRID for the geometry." capi.geos_set_srid(self.ptr, 0 if srid is None else srid) # #### Output Routines #### @property def ewkt(self): """ Return the EWKT (SRID + WKT) of the Geometry. """ srid = self.srid return "SRID=%s;%s" % (srid, self.wkt) if srid else self.wkt @property def wkt(self): "Return the WKT (Well-Known Text) representation of this Geometry." return wkt_w(dim=3 if self.hasz else 2, trim=True).write(self).decode() @property def hex(self): """ Return the WKB of this Geometry in hexadecimal form. Please note that the SRID is not included in this representation because it is not a part of the OGC specification (use the `hexewkb` property instead). """ # A possible faster, all-python, implementation: # str(self.wkb).encode('hex') return wkb_w(dim=3 if self.hasz else 2).write_hex(self) @property def hexewkb(self): """ Return the EWKB of this Geometry in hexadecimal form. This is an extension of the WKB specification that includes SRID value that are a part of this geometry. """ return ewkb_w(dim=3 if self.hasz else 2).write_hex(self) @property def json(self): """ Return GeoJSON representation of this Geometry. """ return self.ogr.json geojson = json @property def wkb(self): """ Return the WKB (Well-Known Binary) representation of this Geometry as a Python buffer. SRID and Z values are not included, use the `ewkb` property instead. """ return wkb_w(3 if self.hasz else 2).write(self) @property def ewkb(self): """ Return the EWKB representation of this Geometry as a Python buffer. This is an extension of the WKB specification that includes any SRID value that are a part of this geometry. """ return ewkb_w(3 if self.hasz else 2).write(self) @property def kml(self): "Return the KML representation of this Geometry." gtype = self.geom_type return "<%s>%s</%s>" % (gtype, self.coord_seq.kml, gtype) @property def prepared(self): """ Return a PreparedGeometry corresponding to this geometry -- it is optimized for the contains, intersects, and covers operations. """ return PreparedGeometry(self) # #### GDAL-specific output routines #### def _ogr_ptr(self): return gdal.OGRGeometry._from_wkb(self.wkb) @property def ogr(self): "Return the OGR Geometry for this Geometry." return gdal.OGRGeometry(self._ogr_ptr(), self.srs) @property def srs(self): "Return the OSR SpatialReference for SRID of this Geometry." if self.srid: try: return gdal.SpatialReference(self.srid) except (gdal.GDALException, gdal.SRSException): pass return None @property def crs(self): "Alias for `srs` property." return self.srs def transform(self, ct, clone=False): """ Requires GDAL. Transform the geometry according to the given transformation object, which may be an integer SRID, and WKT or PROJ string. By default, transform the geometry in-place and return nothing. However if the `clone` keyword is set, don't modify the geometry and return a transformed clone instead. """ srid = self.srid if ct == srid: # short-circuit where source & dest SRIDs match if clone: return self.clone() else: return if isinstance(ct, gdal.CoordTransform): # We don't care about SRID because CoordTransform presupposes # source SRS. srid = None elif srid is None or srid < 0: raise GEOSException("Calling transform() with no SRID set is not supported") # Creating an OGR Geometry, which is then transformed. g = gdal.OGRGeometry(self._ogr_ptr(), srid) g.transform(ct) # Getting a new GEOS pointer ptr = g._geos_ptr() if clone: # User wants a cloned transformed geometry returned. return GEOSGeometry(ptr, srid=g.srid) if ptr: # Reassigning pointer, and performing post-initialization setup # again due to the reassignment. capi.destroy_geom(self.ptr) self.ptr = ptr self._post_init() self.srid = g.srid else: raise GEOSException("Transformed WKB was invalid.") # #### Topology Routines #### def _topology(self, gptr): "Return Geometry from the given pointer." return GEOSGeometry(gptr, srid=self.srid) @property def boundary(self): "Return the boundary as a newly allocated Geometry object." return self._topology(capi.geos_boundary(self.ptr)) def buffer(self, width, quadsegs=8): """ Return a geometry that represents all points whose distance from this Geometry is less than or equal to distance. Calculations are in the Spatial Reference System of this Geometry. The optional third parameter sets the number of segment used to approximate a quarter circle (defaults to 8). (Text from PostGIS documentation at ch. 6.1.3) """ return self._topology(capi.geos_buffer(self.ptr, width, quadsegs)) def buffer_with_style( self, width, quadsegs=8, end_cap_style=1, join_style=1, mitre_limit=5.0 ): """ Same as buffer() but allows customizing the style of the buffer. End cap style can be round (1), flat (2), or square (3). Join style can be round (1), mitre (2), or bevel (3). Mitre ratio limit only affects mitered join style. """ return self._topology( capi.geos_bufferwithstyle( self.ptr, width, quadsegs, end_cap_style, join_style, mitre_limit ), ) @property def centroid(self): """ The centroid is equal to the centroid of the set of component Geometries of highest dimension (since the lower-dimension geometries contribute zero "weight" to the centroid). """ return self._topology(capi.geos_centroid(self.ptr)) @property def convex_hull(self): """ Return the smallest convex Polygon that contains all the points in the Geometry. """ return self._topology(capi.geos_convexhull(self.ptr)) def difference(self, other): """ Return a Geometry representing the points making up this Geometry that do not make up other. """ return self._topology(capi.geos_difference(self.ptr, other.ptr)) @property def envelope(self): "Return the envelope for this geometry (a polygon)." return self._topology(capi.geos_envelope(self.ptr)) def intersection(self, other): "Return a Geometry representing the points shared by this Geometry and other." return self._topology(capi.geos_intersection(self.ptr, other.ptr)) @property def point_on_surface(self): "Compute an interior point of this Geometry." return self._topology(capi.geos_pointonsurface(self.ptr)) def relate(self, other): "Return the DE-9IM intersection matrix for this Geometry and the other." return capi.geos_relate(self.ptr, other.ptr).decode() def simplify(self, tolerance=0.0, preserve_topology=False): """ Return the Geometry, simplified using the Douglas-Peucker algorithm to the specified tolerance (higher tolerance => less points). If no tolerance provided, defaults to 0. By default, don't preserve topology - e.g. polygons can be split, collapse to lines or disappear holes can be created or disappear, and lines can cross. By specifying preserve_topology=True, the result will have the same dimension and number of components as the input. This is significantly slower. """ if preserve_topology: return self._topology(capi.geos_preservesimplify(self.ptr, tolerance)) else: return self._topology(capi.geos_simplify(self.ptr, tolerance)) def sym_difference(self, other): """ Return a set combining the points in this Geometry not in other, and the points in other not in this Geometry. """ return self._topology(capi.geos_symdifference(self.ptr, other.ptr)) @property def unary_union(self): "Return the union of all the elements of this geometry." return self._topology(capi.geos_unary_union(self.ptr)) def union(self, other): "Return a Geometry representing all the points in this Geometry and other." return self._topology(capi.geos_union(self.ptr, other.ptr)) # #### Other Routines #### @property def area(self): "Return the area of the Geometry." return capi.geos_area(self.ptr, byref(c_double())) def distance(self, other): """ Return the distance between the closest points on this Geometry and the other. Units will be in those of the coordinate system of the Geometry. """ if not isinstance(other, GEOSGeometry): raise TypeError("distance() works only on other GEOS Geometries.") return capi.geos_distance(self.ptr, other.ptr, byref(c_double())) @property def extent(self): """ Return the extent of this geometry as a 4-tuple, consisting of (xmin, ymin, xmax, ymax). """ from .point import Point env = self.envelope if isinstance(env, Point): xmin, ymin = env.tuple xmax, ymax = xmin, ymin else: xmin, ymin = env[0][0] xmax, ymax = env[0][2] return (xmin, ymin, xmax, ymax) @property def length(self): """ Return the length of this Geometry (e.g., 0 for point, or the circumference of a Polygon). """ return capi.geos_length(self.ptr, byref(c_double())) def clone(self): "Clone this Geometry." return GEOSGeometry(capi.geom_clone(self.ptr)) class LinearGeometryMixin: """ Used for LineString and MultiLineString. """ def interpolate(self, distance): return self._topology(capi.geos_interpolate(self.ptr, distance)) def interpolate_normalized(self, distance): return self._topology(capi.geos_interpolate_normalized(self.ptr, distance)) def project(self, point): from .point import Point if not isinstance(point, Point): raise TypeError("locate_point argument must be a Point") return capi.geos_project(self.ptr, point.ptr) def project_normalized(self, point): from .point import Point if not isinstance(point, Point): raise TypeError("locate_point argument must be a Point") return capi.geos_project_normalized(self.ptr, point.ptr) @property def merged(self): """ Return the line merge of this Geometry. """ return self._topology(capi.geos_linemerge(self.ptr)) @property def closed(self): """ Return whether or not this Geometry is closed. """ return capi.geos_isclosed(self.ptr) @deconstructible class GEOSGeometry(GEOSGeometryBase, ListMixin): "A class that, generally, encapsulates a GEOS geometry." def __init__(self, geo_input, srid=None): """ The base constructor for GEOS geometry objects. It may take the following inputs: * strings: - WKT - HEXEWKB (a PostGIS-specific canonical form) - GeoJSON (requires GDAL) * buffer: - WKB The `srid` keyword specifies the Source Reference Identifier (SRID) number for this Geometry. If not provided, it defaults to None. """ input_srid = None if isinstance(geo_input, bytes): geo_input = force_str(geo_input) if isinstance(geo_input, str): wkt_m = wkt_regex.match(geo_input) if wkt_m: # Handle WKT input. if wkt_m["srid"]: input_srid = int(wkt_m["srid"]) g = self._from_wkt(force_bytes(wkt_m["wkt"])) elif hex_regex.match(geo_input): # Handle HEXEWKB input. g = wkb_r().read(force_bytes(geo_input)) elif json_regex.match(geo_input): # Handle GeoJSON input. ogr = gdal.OGRGeometry.from_json(geo_input) g = ogr._geos_ptr() input_srid = ogr.srid else: raise ValueError("String input unrecognized as WKT EWKT, and HEXEWKB.") elif isinstance(geo_input, GEOM_PTR): # When the input is a pointer to a geometry (GEOM_PTR). g = geo_input elif isinstance(geo_input, memoryview): # When the input is a buffer (WKB). g = wkb_r().read(geo_input) elif isinstance(geo_input, GEOSGeometry): g = capi.geom_clone(geo_input.ptr) else: raise TypeError("Improper geometry input type: %s" % type(geo_input)) if not g: raise GEOSException("Could not initialize GEOS Geometry with given input.") input_srid = input_srid or capi.geos_get_srid(g) or None if input_srid and srid and input_srid != srid: raise ValueError("Input geometry already has SRID: %d." % input_srid) super().__init__(g, None) # Set the SRID, if given. srid = input_srid or srid if srid and isinstance(srid, int): self.srid = srid
29017a96a021e4a4651520e037e0525d6a2399615a6db114160cf6206617fef9
from django.contrib.gis.geos.geometry import GEOSGeometry, hex_regex, wkt_regex def fromfile(file_h): """ Given a string file name, returns a GEOSGeometry. The file may contain WKB, WKT, or HEX. """ # If given a file name, get a real handle. if isinstance(file_h, str): with open(file_h, "rb") as file_h: buf = file_h.read() else: buf = file_h.read() # If we get WKB need to wrap in memoryview(), so run through regexes. if isinstance(buf, bytes): try: decoded = buf.decode() except UnicodeDecodeError: pass else: if wkt_regex.match(decoded) or hex_regex.match(decoded): return GEOSGeometry(decoded) else: return GEOSGeometry(buf) return GEOSGeometry(memoryview(buf)) def fromstr(string, **kwargs): "Given a string value, return a GEOSGeometry object." return GEOSGeometry(string, **kwargs)
2c219ba451565d89ba4ae9ec33357d2e83cb351b4328459a43b3f8554b6c93ce
""" The GeoDjango GEOS module. Please consult the GeoDjango documentation for more details: https://docs.djangoproject.com/en/dev/ref/contrib/gis/geos/ """ from .collections import ( # NOQA GeometryCollection, MultiLineString, MultiPoint, MultiPolygon, ) from .error import GEOSException # NOQA from .factory import fromfile, fromstr # NOQA from .geometry import GEOSGeometry, hex_regex, wkt_regex # NOQA from .io import WKBReader, WKBWriter, WKTReader, WKTWriter # NOQA from .libgeos import geos_version # NOQA from .linestring import LinearRing, LineString # NOQA from .point import Point # NOQA from .polygon import Polygon # NOQA
6ef6adb1d5d36f55d8cb511a499be9e119ebd8bc17654d76cc82de7cbbbab11c
from ctypes import c_uint from django.contrib.gis import gdal from django.contrib.gis.geos import prototypes as capi from django.contrib.gis.geos.error import GEOSException from django.contrib.gis.geos.geometry import GEOSGeometry class Point(GEOSGeometry): _minlength = 2 _maxlength = 3 has_cs = True def __init__(self, x=None, y=None, z=None, srid=None): """ The Point object may be initialized with either a tuple, or individual parameters. For example: >>> p = Point((5, 23)) # 2D point, passed in as a tuple >>> p = Point(5, 23, 8) # 3D point, passed in with individual parameters """ if x is None: coords = [] elif isinstance(x, (tuple, list)): # Here a tuple or list was passed in under the `x` parameter. coords = x elif isinstance(x, (float, int)) and isinstance(y, (float, int)): # Here X, Y, and (optionally) Z were passed in individually, as parameters. if isinstance(z, (float, int)): coords = [x, y, z] else: coords = [x, y] else: raise TypeError("Invalid parameters given for Point initialization.") point = self._create_point(len(coords), coords) # Initializing using the address returned from the GEOS # createPoint factory. super().__init__(point, srid=srid) def _to_pickle_wkb(self): return None if self.empty else super()._to_pickle_wkb() def _from_pickle_wkb(self, wkb): return self._create_empty() if wkb is None else super()._from_pickle_wkb(wkb) def _ogr_ptr(self): return ( gdal.geometries.Point._create_empty() if self.empty else super()._ogr_ptr() ) @classmethod def _create_empty(cls): return cls._create_point(None, None) @classmethod def _create_point(cls, ndim, coords): """ Create a coordinate sequence, set X, Y, [Z], and create point """ if not ndim: return capi.create_point(None) if ndim < 2 or ndim > 3: raise TypeError("Invalid point dimension: %s" % ndim) cs = capi.create_cs(c_uint(1), c_uint(ndim)) i = iter(coords) capi.cs_setx(cs, 0, next(i)) capi.cs_sety(cs, 0, next(i)) if ndim == 3: capi.cs_setz(cs, 0, next(i)) return capi.create_point(cs) def _set_list(self, length, items): ptr = self._create_point(length, items) if ptr: srid = self.srid capi.destroy_geom(self.ptr) self._ptr = ptr if srid is not None: self.srid = srid self._post_init() else: # can this happen? raise GEOSException("Geometry resulting from slice deletion was invalid.") def _set_single(self, index, value): self._cs.setOrdinate(index, 0, value) def __iter__(self): "Iterate over coordinates of this Point." for i in range(len(self)): yield self[i] def __len__(self): "Return the number of dimensions for this Point (either 0, 2 or 3)." if self.empty: return 0 if self.hasz: return 3 else: return 2 def _get_single_external(self, index): if index == 0: return self.x elif index == 1: return self.y elif index == 2: return self.z _get_single_internal = _get_single_external @property def x(self): "Return the X component of the Point." return self._cs.getOrdinate(0, 0) @x.setter def x(self, value): "Set the X component of the Point." self._cs.setOrdinate(0, 0, value) @property def y(self): "Return the Y component of the Point." return self._cs.getOrdinate(1, 0) @y.setter def y(self, value): "Set the Y component of the Point." self._cs.setOrdinate(1, 0, value) @property def z(self): "Return the Z component of the Point." return self._cs.getOrdinate(2, 0) if self.hasz else None @z.setter def z(self, value): "Set the Z component of the Point." if not self.hasz: raise GEOSException("Cannot set Z on 2D Point.") self._cs.setOrdinate(2, 0, value) # ### Tuple setting and retrieval routines. ### @property def tuple(self): "Return a tuple of the point." return self._cs.tuple @tuple.setter def tuple(self, tup): "Set the coordinates of the point with the given tuple." self._cs[0] = tup # The tuple and coords properties coords = tuple
ac4a0abe8ddc27dcaa214c9509e412231c6e1dd54099bbab13572a15015bb593
""" This module houses the ctypes initialization procedures, as well as the notice and error handler function callbacks (get called when an error occurs in GEOS). This module also houses GEOS Pointer utilities, including get_pointer_arr(), and GEOM_PTR. """ import logging import os from ctypes import CDLL, CFUNCTYPE, POINTER, Structure, c_char_p from ctypes.util import find_library from django.core.exceptions import ImproperlyConfigured from django.utils.functional import SimpleLazyObject, cached_property from django.utils.version import get_version_tuple logger = logging.getLogger("django.contrib.gis") def load_geos(): # Custom library path set? try: from django.conf import settings lib_path = settings.GEOS_LIBRARY_PATH except (AttributeError, ImportError, ImproperlyConfigured, OSError): lib_path = None # Setting the appropriate names for the GEOS-C library. if lib_path: lib_names = None elif os.name == "nt": # Windows NT libraries lib_names = ["geos_c", "libgeos_c-1"] elif os.name == "posix": # *NIX libraries lib_names = ["geos_c", "GEOS"] else: raise ImportError('Unsupported OS "%s"' % os.name) # Using the ctypes `find_library` utility to find the path to the GEOS # shared library. This is better than manually specifying each library name # and extension (e.g., libgeos_c.[so|so.1|dylib].). if lib_names: for lib_name in lib_names: lib_path = find_library(lib_name) if lib_path is not None: break # No GEOS library could be found. if lib_path is None: raise ImportError( 'Could not find the GEOS library (tried "%s"). ' "Try setting GEOS_LIBRARY_PATH in your settings." % '", "'.join(lib_names) ) # Getting the GEOS C library. The C interface (CDLL) is used for # both *NIX and Windows. # See the GEOS C API source code for more details on the library function calls: # https://libgeos.org/doxygen/geos__c_8h_source.html _lgeos = CDLL(lib_path) # Here we set up the prototypes for the initGEOS_r and finishGEOS_r # routines. These functions aren't actually called until they are # attached to a GEOS context handle -- this actually occurs in # geos/prototypes/threadsafe.py. _lgeos.initGEOS_r.restype = CONTEXT_PTR _lgeos.finishGEOS_r.argtypes = [CONTEXT_PTR] # Set restype for compatibility across 32 and 64-bit platforms. _lgeos.GEOSversion.restype = c_char_p return _lgeos # The notice and error handler C function callback definitions. # Supposed to mimic the GEOS message handler (C below): # typedef void (*GEOSMessageHandler)(const char *fmt, ...); NOTICEFUNC = CFUNCTYPE(None, c_char_p, c_char_p) def notice_h(fmt, lst): fmt, lst = fmt.decode(), lst.decode() try: warn_msg = fmt % lst except TypeError: warn_msg = fmt logger.warning("GEOS_NOTICE: %s\n", warn_msg) notice_h = NOTICEFUNC(notice_h) ERRORFUNC = CFUNCTYPE(None, c_char_p, c_char_p) def error_h(fmt, lst): fmt, lst = fmt.decode(), lst.decode() try: err_msg = fmt % lst except TypeError: err_msg = fmt logger.error("GEOS_ERROR: %s\n", err_msg) error_h = ERRORFUNC(error_h) # #### GEOS Geometry C data structures, and utility functions. #### # Opaque GEOS geometry structures, used for GEOM_PTR and CS_PTR class GEOSGeom_t(Structure): pass class GEOSPrepGeom_t(Structure): pass class GEOSCoordSeq_t(Structure): pass class GEOSContextHandle_t(Structure): pass # Pointers to opaque GEOS geometry structures. GEOM_PTR = POINTER(GEOSGeom_t) PREPGEOM_PTR = POINTER(GEOSPrepGeom_t) CS_PTR = POINTER(GEOSCoordSeq_t) CONTEXT_PTR = POINTER(GEOSContextHandle_t) lgeos = SimpleLazyObject(load_geos) class GEOSFuncFactory: """ Lazy loading of GEOS functions. """ argtypes = None restype = None errcheck = None def __init__(self, func_name, *, restype=None, errcheck=None, argtypes=None): self.func_name = func_name if restype is not None: self.restype = restype if errcheck is not None: self.errcheck = errcheck if argtypes is not None: self.argtypes = argtypes def __call__(self, *args): return self.func(*args) @cached_property def func(self): from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc func = GEOSFunc(self.func_name) func.argtypes = self.argtypes or [] func.restype = self.restype if self.errcheck: func.errcheck = self.errcheck return func def geos_version(): """Return the string version of the GEOS library.""" return lgeos.GEOSversion() def geos_version_tuple(): """Return the GEOS version as a tuple (major, minor, subminor).""" return get_version_tuple(geos_version().decode())
04902859f1d6d3c117d54a4d155074f6248a5dd4d2ea966c4c805ce8371971f7
from django.contrib.gis.geos import prototypes as capi from django.contrib.gis.geos.coordseq import GEOSCoordSeq from django.contrib.gis.geos.error import GEOSException from django.contrib.gis.geos.geometry import GEOSGeometry, LinearGeometryMixin from django.contrib.gis.geos.point import Point from django.contrib.gis.shortcuts import numpy class LineString(LinearGeometryMixin, GEOSGeometry): _init_func = capi.create_linestring _minlength = 2 has_cs = True def __init__(self, *args, **kwargs): """ Initialize on the given sequence -- may take lists, tuples, NumPy arrays of X,Y pairs, or Point objects. If Point objects are used, ownership is _not_ transferred to the LineString object. Examples: ls = LineString((1, 1), (2, 2)) ls = LineString([(1, 1), (2, 2)]) ls = LineString(array([(1, 1), (2, 2)])) ls = LineString(Point(1, 1), Point(2, 2)) """ # If only one argument provided, set the coords array appropriately if len(args) == 1: coords = args[0] else: coords = args if not ( isinstance(coords, (tuple, list)) or numpy and isinstance(coords, numpy.ndarray) ): raise TypeError("Invalid initialization input for LineStrings.") # If SRID was passed in with the keyword arguments srid = kwargs.get("srid") ncoords = len(coords) if not ncoords: super().__init__(self._init_func(None), srid=srid) return if ncoords < self._minlength: raise ValueError( "%s requires at least %d points, got %s." % ( self.__class__.__name__, self._minlength, ncoords, ) ) numpy_coords = not isinstance(coords, (tuple, list)) if numpy_coords: shape = coords.shape # Using numpy's shape. if len(shape) != 2: raise TypeError("Too many dimensions.") self._checkdim(shape[1]) ndim = shape[1] else: # Getting the number of coords and the number of dimensions -- which # must stay the same, e.g., no LineString((1, 2), (1, 2, 3)). ndim = None # Incrementing through each of the coordinates and verifying for coord in coords: if not isinstance(coord, (tuple, list, Point)): raise TypeError( "Each coordinate should be a sequence (list or tuple)" ) if ndim is None: ndim = len(coord) self._checkdim(ndim) elif len(coord) != ndim: raise TypeError("Dimension mismatch.") # Creating a coordinate sequence object because it is easier to # set the points using its methods. cs = GEOSCoordSeq(capi.create_cs(ncoords, ndim), z=bool(ndim == 3)) point_setter = cs._set_point_3d if ndim == 3 else cs._set_point_2d for i in range(ncoords): if numpy_coords: point_coords = coords[i, :] elif isinstance(coords[i], Point): point_coords = coords[i].tuple else: point_coords = coords[i] point_setter(i, point_coords) # Calling the base geometry initialization with the returned pointer # from the function. super().__init__(self._init_func(cs.ptr), srid=srid) def __iter__(self): "Allow iteration over this LineString." for i in range(len(self)): yield self[i] def __len__(self): "Return the number of points in this LineString." return len(self._cs) def _get_single_external(self, index): return self._cs[index] _get_single_internal = _get_single_external def _set_list(self, length, items): ndim = self._cs.dims hasz = self._cs.hasz # I don't understand why these are different srid = self.srid # create a new coordinate sequence and populate accordingly cs = GEOSCoordSeq(capi.create_cs(length, ndim), z=hasz) for i, c in enumerate(items): cs[i] = c ptr = self._init_func(cs.ptr) if ptr: capi.destroy_geom(self.ptr) self.ptr = ptr if srid is not None: self.srid = srid self._post_init() else: # can this happen? raise GEOSException("Geometry resulting from slice deletion was invalid.") def _set_single(self, index, value): self._cs[index] = value def _checkdim(self, dim): if dim not in (2, 3): raise TypeError("Dimension mismatch.") # #### Sequence Properties #### @property def tuple(self): "Return a tuple version of the geometry from the coordinate sequence." return self._cs.tuple coords = tuple def _listarr(self, func): """ Return a sequence (list) corresponding with the given function. Return a numpy array if possible. """ lst = [func(i) for i in range(len(self))] if numpy: return numpy.array(lst) # ARRRR! else: return lst @property def array(self): "Return a numpy array for the LineString." return self._listarr(self._cs.__getitem__) @property def x(self): "Return a list or numpy array of the X variable." return self._listarr(self._cs.getX) @property def y(self): "Return a list or numpy array of the Y variable." return self._listarr(self._cs.getY) @property def z(self): "Return a list or numpy array of the Z variable." if not self.hasz: return None else: return self._listarr(self._cs.getZ) # LinearRings are LineStrings used within Polygons. class LinearRing(LineString): _minlength = 4 _init_func = capi.create_linearring @property def is_counterclockwise(self): if self.empty: raise ValueError("Orientation of an empty LinearRing cannot be determined.") return self._cs.is_counterclockwise
3f76df8370085aff7d96baa6cc56723fe8ba7b96220ae0b7d9faa5fc85cf814a
""" Module that holds classes for performing I/O operations on GEOS geometry objects. Specifically, this has Python implementations of WKB/WKT reader and writer classes. """ from django.contrib.gis.geos.geometry import GEOSGeometry from django.contrib.gis.geos.prototypes.io import ( WKBWriter, WKTWriter, _WKBReader, _WKTReader, ) __all__ = ["WKBWriter", "WKTWriter", "WKBReader", "WKTReader"] # Public classes for (WKB|WKT)Reader, which return GEOSGeometry class WKBReader(_WKBReader): def read(self, wkb): "Return a GEOSGeometry for the given WKB buffer." return GEOSGeometry(super().read(wkb)) class WKTReader(_WKTReader): def read(self, wkt): "Return a GEOSGeometry for the given WKT string." return GEOSGeometry(super().read(wkt))
2790e3e9edeede011f54f34e33513faef726717476f82770b5b01ca220d4e5ad
from .base import GEOSBase from .prototypes import prepared as capi class PreparedGeometry(GEOSBase): """ A geometry that is prepared for performing certain operations. At the moment this includes the contains covers, and intersects operations. """ ptr_type = capi.PREPGEOM_PTR destructor = capi.prepared_destroy def __init__(self, geom): # Keeping a reference to the original geometry object to prevent it # from being garbage collected which could then crash the prepared one # See #21662 self._base_geom = geom from .geometry import GEOSGeometry if not isinstance(geom, GEOSGeometry): raise TypeError self.ptr = capi.geos_prepare(geom.ptr) def contains(self, other): return capi.prepared_contains(self.ptr, other.ptr) def contains_properly(self, other): return capi.prepared_contains_properly(self.ptr, other.ptr) def covers(self, other): return capi.prepared_covers(self.ptr, other.ptr) def intersects(self, other): return capi.prepared_intersects(self.ptr, other.ptr) def crosses(self, other): return capi.prepared_crosses(self.ptr, other.ptr) def disjoint(self, other): return capi.prepared_disjoint(self.ptr, other.ptr) def overlaps(self, other): return capi.prepared_overlaps(self.ptr, other.ptr) def touches(self, other): return capi.prepared_touches(self.ptr, other.ptr) def within(self, other): return capi.prepared_within(self.ptr, other.ptr)
ccada9e25ccd1f3830e878184f5bd7c0481083f69ddc175420c4831d24b61fe5
""" This module houses the GEOSCoordSeq object, which is used internally by GEOSGeometry to house the actual coordinates of the Point, LineString, and LinearRing geometries. """ from ctypes import byref, c_byte, c_double, c_uint from django.contrib.gis.geos import prototypes as capi from django.contrib.gis.geos.base import GEOSBase from django.contrib.gis.geos.error import GEOSException from django.contrib.gis.geos.libgeos import CS_PTR, geos_version_tuple from django.contrib.gis.shortcuts import numpy class GEOSCoordSeq(GEOSBase): "The internal representation of a list of coordinates inside a Geometry." ptr_type = CS_PTR def __init__(self, ptr, z=False): "Initialize from a GEOS pointer." if not isinstance(ptr, CS_PTR): raise TypeError("Coordinate sequence should initialize with a CS_PTR.") self._ptr = ptr self._z = z def __iter__(self): "Iterate over each point in the coordinate sequence." for i in range(self.size): yield self[i] def __len__(self): "Return the number of points in the coordinate sequence." return self.size def __str__(self): "Return the string representation of the coordinate sequence." return str(self.tuple) def __getitem__(self, index): "Return the coordinate sequence value at the given index." self._checkindex(index) return self._point_getter(index) def __setitem__(self, index, value): "Set the coordinate sequence value at the given index." # Checking the input value if isinstance(value, (list, tuple)): pass elif numpy and isinstance(value, numpy.ndarray): pass else: raise TypeError( "Must set coordinate with a sequence (list, tuple, or numpy array)." ) # Checking the dims of the input if self.dims == 3 and self._z: n_args = 3 point_setter = self._set_point_3d else: n_args = 2 point_setter = self._set_point_2d if len(value) != n_args: raise TypeError("Dimension of value does not match.") self._checkindex(index) point_setter(index, value) # #### Internal Routines #### def _checkindex(self, index): "Check the given index." if not (0 <= index < self.size): raise IndexError("invalid GEOS Geometry index: %s" % index) def _checkdim(self, dim): "Check the given dimension." if dim < 0 or dim > 2: raise GEOSException('invalid ordinate dimension "%d"' % dim) def _get_x(self, index): return capi.cs_getx(self.ptr, index, byref(c_double())) def _get_y(self, index): return capi.cs_gety(self.ptr, index, byref(c_double())) def _get_z(self, index): return capi.cs_getz(self.ptr, index, byref(c_double())) def _set_x(self, index, value): capi.cs_setx(self.ptr, index, value) def _set_y(self, index, value): capi.cs_sety(self.ptr, index, value) def _set_z(self, index, value): capi.cs_setz(self.ptr, index, value) @property def _point_getter(self): return self._get_point_3d if self.dims == 3 and self._z else self._get_point_2d def _get_point_2d(self, index): return (self._get_x(index), self._get_y(index)) def _get_point_3d(self, index): return (self._get_x(index), self._get_y(index), self._get_z(index)) def _set_point_2d(self, index, value): x, y = value self._set_x(index, x) self._set_y(index, y) def _set_point_3d(self, index, value): x, y, z = value self._set_x(index, x) self._set_y(index, y) self._set_z(index, z) # #### Ordinate getting and setting routines #### def getOrdinate(self, dimension, index): "Return the value for the given dimension and index." self._checkindex(index) self._checkdim(dimension) return capi.cs_getordinate(self.ptr, index, dimension, byref(c_double())) def setOrdinate(self, dimension, index, value): "Set the value for the given dimension and index." self._checkindex(index) self._checkdim(dimension) capi.cs_setordinate(self.ptr, index, dimension, value) def getX(self, index): "Get the X value at the index." return self.getOrdinate(0, index) def setX(self, index, value): "Set X with the value at the given index." self.setOrdinate(0, index, value) def getY(self, index): "Get the Y value at the given index." return self.getOrdinate(1, index) def setY(self, index, value): "Set Y with the value at the given index." self.setOrdinate(1, index, value) def getZ(self, index): "Get Z with the value at the given index." return self.getOrdinate(2, index) def setZ(self, index, value): "Set Z with the value at the given index." self.setOrdinate(2, index, value) # ### Dimensions ### @property def size(self): "Return the size of this coordinate sequence." return capi.cs_getsize(self.ptr, byref(c_uint())) @property def dims(self): "Return the dimensions of this coordinate sequence." return capi.cs_getdims(self.ptr, byref(c_uint())) @property def hasz(self): """ Return whether this coordinate sequence is 3D. This property value is inherited from the parent Geometry. """ return self._z # ### Other Methods ### def clone(self): "Clone this coordinate sequence." return GEOSCoordSeq(capi.cs_clone(self.ptr), self.hasz) @property def kml(self): "Return the KML representation for the coordinates." # Getting the substitution string depending on whether the coordinates have # a Z dimension. if self.hasz: substr = "%s,%s,%s " else: substr = "%s,%s,0 " return ( "<coordinates>%s</coordinates>" % "".join(substr % self[i] for i in range(len(self))).strip() ) @property def tuple(self): "Return a tuple version of this coordinate sequence." n = self.size get_point = self._point_getter if n == 1: return get_point(0) return tuple(get_point(i) for i in range(n)) @property def is_counterclockwise(self): """Return whether this coordinate sequence is counterclockwise.""" if geos_version_tuple() < (3, 7): # A modified shoelace algorithm to determine polygon orientation. # See https://en.wikipedia.org/wiki/Shoelace_formula. area = 0.0 n = len(self) for i in range(n): j = (i + 1) % n area += self[i][0] * self[j][1] area -= self[j][0] * self[i][1] return area > 0.0 ret = c_byte() if not capi.cs_is_ccw(self.ptr, byref(ret)): raise GEOSException( 'Error encountered in GEOS C function "%s".' % capi.cs_is_ccw.func_name ) return ret.value == 1
01db3a3466dbbedad9b4075f1c8c7fd43bfe5d3dc45f9a994db1e799441e9341
from django.contrib.gis.geos import prototypes as capi from django.contrib.gis.geos.geometry import GEOSGeometry from django.contrib.gis.geos.libgeos import GEOM_PTR from django.contrib.gis.geos.linestring import LinearRing class Polygon(GEOSGeometry): _minlength = 1 def __init__(self, *args, **kwargs): """ Initialize on an exterior ring and a sequence of holes (both instances may be either LinearRing instances, or a tuple/list that may be constructed into a LinearRing). Examples of initialization, where shell, hole1, and hole2 are valid LinearRing geometries: >>> from django.contrib.gis.geos import LinearRing, Polygon >>> shell = hole1 = hole2 = LinearRing() >>> poly = Polygon(shell, hole1, hole2) >>> poly = Polygon(shell, (hole1, hole2)) >>> # Example where a tuple parameters are used: >>> poly = Polygon(((0, 0), (0, 10), (10, 10), (0, 10), (0, 0)), ... ((4, 4), (4, 6), (6, 6), (6, 4), (4, 4))) """ if not args: super().__init__(self._create_polygon(0, None), **kwargs) return # Getting the ext_ring and init_holes parameters from the argument list ext_ring, *init_holes = args n_holes = len(init_holes) # If initialized as Polygon(shell, (LinearRing, LinearRing)) # [for backward-compatibility] if n_holes == 1 and isinstance(init_holes[0], (tuple, list)): if not init_holes[0]: init_holes = () n_holes = 0 elif isinstance(init_holes[0][0], LinearRing): init_holes = init_holes[0] n_holes = len(init_holes) polygon = self._create_polygon(n_holes + 1, [ext_ring, *init_holes]) super().__init__(polygon, **kwargs) def __iter__(self): "Iterate over each ring in the polygon." for i in range(len(self)): yield self[i] def __len__(self): "Return the number of rings in this Polygon." return self.num_interior_rings + 1 @classmethod def from_bbox(cls, bbox): "Construct a Polygon from a bounding box (4-tuple)." x0, y0, x1, y1 = bbox for z in bbox: if not isinstance(z, (float, int)): return GEOSGeometry( "POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))" % (x0, y0, x0, y1, x1, y1, x1, y0, x0, y0) ) return Polygon(((x0, y0), (x0, y1), (x1, y1), (x1, y0), (x0, y0))) # ### These routines are needed for list-like operation w/ListMixin ### def _create_polygon(self, length, items): # Instantiate LinearRing objects if necessary, but don't clone them yet # _construct_ring will throw a TypeError if a parameter isn't a valid ring # If we cloned the pointers here, we wouldn't be able to clean up # in case of error. if not length: return capi.create_empty_polygon() rings = [] for r in items: if isinstance(r, GEOM_PTR): rings.append(r) else: rings.append(self._construct_ring(r)) shell = self._clone(rings.pop(0)) n_holes = length - 1 if n_holes: holes_param = (GEOM_PTR * n_holes)(*[self._clone(r) for r in rings]) else: holes_param = None return capi.create_polygon(shell, holes_param, n_holes) def _clone(self, g): if isinstance(g, GEOM_PTR): return capi.geom_clone(g) else: return capi.geom_clone(g.ptr) def _construct_ring( self, param, msg=( "Parameter must be a sequence of LinearRings or objects that can " "initialize to LinearRings" ), ): "Try to construct a ring from the given parameter." if isinstance(param, LinearRing): return param try: ring = LinearRing(param) return ring except TypeError: raise TypeError(msg) def _set_list(self, length, items): # Getting the current pointer, replacing with the newly constructed # geometry, and destroying the old geometry. prev_ptr = self.ptr srid = self.srid self.ptr = self._create_polygon(length, items) if srid: self.srid = srid capi.destroy_geom(prev_ptr) def _get_single_internal(self, index): """ Return the ring at the specified index. The first index, 0, will always return the exterior ring. Indices > 0 will return the interior ring at the given index (e.g., poly[1] and poly[2] would return the first and second interior ring, respectively). CAREFUL: Internal/External are not the same as Interior/Exterior! Return a pointer from the existing geometries for use internally by the object's methods. _get_single_external() returns a clone of the same geometry for use by external code. """ if index == 0: return capi.get_extring(self.ptr) else: # Getting the interior ring, have to subtract 1 from the index. return capi.get_intring(self.ptr, index - 1) def _get_single_external(self, index): return GEOSGeometry( capi.geom_clone(self._get_single_internal(index)), srid=self.srid ) _set_single = GEOSGeometry._set_single_rebuild _assign_extended_slice = GEOSGeometry._assign_extended_slice_rebuild # #### Polygon Properties #### @property def num_interior_rings(self): "Return the number of interior rings." # Getting the number of rings return capi.get_nrings(self.ptr) def _get_ext_ring(self): "Get the exterior ring of the Polygon." return self[0] def _set_ext_ring(self, ring): "Set the exterior ring of the Polygon." self[0] = ring # Properties for the exterior ring/shell. exterior_ring = property(_get_ext_ring, _set_ext_ring) shell = exterior_ring @property def tuple(self): "Get the tuple for each ring in this Polygon." return tuple(self[i].tuple for i in range(len(self))) coords = tuple @property def kml(self): "Return the KML representation of this Polygon." inner_kml = "".join( "<innerBoundaryIs>%s</innerBoundaryIs>" % self[i + 1].kml for i in range(self.num_interior_rings) ) return "<Polygon><outerBoundaryIs>%s</outerBoundaryIs>%s</Polygon>" % ( self[0].kml, inner_kml, )
90cf8629f8f0bab77b0f73fab036e412965705aa1caa86dc49aad0f3d384264a
from django.contrib.gis.db.models.fields import ( ExtentField, GeometryCollectionField, GeometryField, LineStringField, ) from django.db.models import Aggregate, Value from django.utils.functional import cached_property __all__ = ["Collect", "Extent", "Extent3D", "MakeLine", "Union"] class GeoAggregate(Aggregate): function = None is_extent = False @cached_property def output_field(self): return self.output_field_class(self.source_expressions[0].output_field.srid) def as_sql(self, compiler, connection, function=None, **extra_context): # this will be called again in parent, but it's needed now - before # we get the spatial_aggregate_name connection.ops.check_expression_support(self) return super().as_sql( compiler, connection, function=function or connection.ops.spatial_aggregate_name(self.name), **extra_context, ) def as_oracle(self, compiler, connection, **extra_context): if not self.is_extent: tolerance = self.extra.get("tolerance") or getattr(self, "tolerance", 0.05) clone = self.copy() clone.set_source_expressions( [ *self.get_source_expressions(), Value(tolerance), ] ) template = "%(function)s(SDOAGGRTYPE(%(expressions)s))" return clone.as_sql( compiler, connection, template=template, **extra_context ) return self.as_sql(compiler, connection, **extra_context) def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): c = super().resolve_expression(query, allow_joins, reuse, summarize, for_save) for expr in c.get_source_expressions(): if not hasattr(expr.field, "geom_type"): raise ValueError( "Geospatial aggregates only allowed on geometry fields." ) return c class Collect(GeoAggregate): name = "Collect" output_field_class = GeometryCollectionField class Extent(GeoAggregate): name = "Extent" is_extent = "2D" def __init__(self, expression, **extra): super().__init__(expression, output_field=ExtentField(), **extra) def convert_value(self, value, expression, connection): return connection.ops.convert_extent(value) class Extent3D(GeoAggregate): name = "Extent3D" is_extent = "3D" def __init__(self, expression, **extra): super().__init__(expression, output_field=ExtentField(), **extra) def convert_value(self, value, expression, connection): return connection.ops.convert_extent3d(value) class MakeLine(GeoAggregate): name = "MakeLine" output_field_class = LineStringField class Union(GeoAggregate): name = "Union" output_field_class = GeometryField
a36c175b7b052168638644abcebc0568275ab6f64b17c67966cdecd6e826ae20
""" The SpatialProxy object allows for lazy-geometries and lazy-rasters. The proxy uses Python descriptors for instantiating and setting Geometry or Raster objects corresponding to geographic model fields. Thanks to Robert Coup for providing this functionality (see #4322). """ from django.db.models.query_utils import DeferredAttribute class SpatialProxy(DeferredAttribute): def __init__(self, klass, field, load_func=None): """ Initialize on the given Geometry or Raster class (not an instance) and the corresponding field. """ self._klass = klass self._load_func = load_func or klass super().__init__(field) def __get__(self, instance, cls=None): """ Retrieve the geometry or raster, initializing it using the corresponding class specified during initialization and the value of the field. Currently, GEOS or OGR geometries as well as GDALRasters are supported. """ if instance is None: # Accessed on a class, not an instance return self # Getting the value of the field. try: geo_value = instance.__dict__[self.field.attname] except KeyError: geo_value = super().__get__(instance, cls) if isinstance(geo_value, self._klass): geo_obj = geo_value elif (geo_value is None) or (geo_value == ""): geo_obj = None else: # Otherwise, a geometry or raster object is built using the field's # contents, and the model's corresponding attribute is set. geo_obj = self._load_func(geo_value) setattr(instance, self.field.attname, geo_obj) return geo_obj def __set__(self, instance, value): """ Retrieve the proxied geometry or raster with the corresponding class specified during initialization. To set geometries, use values of None, HEXEWKB, or WKT. To set rasters, use JSON or dict values. """ # The geographic type of the field. gtype = self.field.geom_type if gtype == "RASTER" and ( value is None or isinstance(value, (str, dict, self._klass)) ): # For raster fields, ensure input is None or a string, dict, or # raster instance. pass elif isinstance(value, self._klass): # The geometry type must match that of the field -- unless the # general GeometryField is used. if value.srid is None: # Assigning the field SRID if the geometry has no SRID. value.srid = self.field.srid elif value is None or isinstance(value, (str, memoryview)): # Set geometries with None, WKT, HEX, or WKB pass else: raise TypeError( "Cannot set %s SpatialProxy (%s) with value of type: %s" % (instance.__class__.__name__, gtype, type(value)) ) # Setting the objects dictionary with the value, and returning. instance.__dict__[self.field.attname] = value return value
4eb092dbb25d55af90ec7a24f98689c5be1e2eb3ddcaf4666ac24622ed397ef0
from django.db.models import * # NOQA isort:skip from django.db.models import __all__ as models_all # isort:skip import django.contrib.gis.db.models.functions # NOQA import django.contrib.gis.db.models.lookups # NOQA from django.contrib.gis.db.models.aggregates import * # NOQA from django.contrib.gis.db.models.aggregates import __all__ as aggregates_all from django.contrib.gis.db.models.fields import ( GeometryCollectionField, GeometryField, LineStringField, MultiLineStringField, MultiPointField, MultiPolygonField, PointField, PolygonField, RasterField, ) __all__ = models_all + aggregates_all __all__ += [ "GeometryCollectionField", "GeometryField", "LineStringField", "MultiLineStringField", "MultiPointField", "MultiPolygonField", "PointField", "PolygonField", "RasterField", ]
9f8d2cf4761ba95a452885bd6f85f8210f0835652eb3b4198b941d89654fb132
from collections import defaultdict, namedtuple from django.contrib.gis import forms, gdal from django.contrib.gis.db.models.proxy import SpatialProxy from django.contrib.gis.gdal.error import GDALException from django.contrib.gis.geos import ( GeometryCollection, GEOSException, GEOSGeometry, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, ) from django.core.exceptions import ImproperlyConfigured from django.db.models import Field from django.utils.translation import gettext_lazy as _ # Local cache of the spatial_ref_sys table, which holds SRID data for each # spatial database alias. This cache exists so that the database isn't queried # for SRID info each time a distance query is constructed. _srid_cache = defaultdict(dict) SRIDCacheEntry = namedtuple( "SRIDCacheEntry", ["units", "units_name", "spheroid", "geodetic"] ) def get_srid_info(srid, connection): """ Return the units, unit name, and spheroid WKT associated with the given SRID from the `spatial_ref_sys` (or equivalent) spatial database table for the given database connection. These results are cached. """ from django.contrib.gis.gdal import SpatialReference global _srid_cache try: # The SpatialRefSys model for the spatial backend. SpatialRefSys = connection.ops.spatial_ref_sys() except NotImplementedError: SpatialRefSys = None alias, get_srs = ( ( connection.alias, lambda srid: SpatialRefSys.objects.using(connection.alias) .get(srid=srid) .srs, ) if SpatialRefSys else (None, SpatialReference) ) if srid not in _srid_cache[alias]: srs = get_srs(srid) units, units_name = srs.units _srid_cache[alias][srid] = SRIDCacheEntry( units=units, units_name=units_name, spheroid='SPHEROID["%s",%s,%s]' % (srs["spheroid"], srs.semi_major, srs.inverse_flattening), geodetic=srs.geographic, ) return _srid_cache[alias][srid] class BaseSpatialField(Field): """ The Base GIS Field. It's used as a base class for GeometryField and RasterField. Defines properties that are common to all GIS fields such as the characteristics of the spatial reference system of the field. """ description = _("The base GIS field.") empty_strings_allowed = False def __init__(self, verbose_name=None, srid=4326, spatial_index=True, **kwargs): """ The initialization function for base spatial fields. Takes the following as keyword arguments: srid: The spatial reference system identifier, an OGC standard. Defaults to 4326 (WGS84). spatial_index: Indicates whether to create a spatial index. Defaults to True. Set this instead of 'db_index' for geographic fields since index creation is different for geometry columns. """ # Setting the index flag with the value of the `spatial_index` keyword. self.spatial_index = spatial_index # Setting the SRID and getting the units. Unit information must be # easily available in the field instance for distance queries. self.srid = srid # Setting the verbose_name keyword argument with the positional # first parameter, so this works like normal fields. kwargs["verbose_name"] = verbose_name super().__init__(**kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() # Always include SRID for less fragility; include spatial index if it's # not the default value. kwargs["srid"] = self.srid if self.spatial_index is not True: kwargs["spatial_index"] = self.spatial_index return name, path, args, kwargs def db_type(self, connection): return connection.ops.geo_db_type(self) def spheroid(self, connection): return get_srid_info(self.srid, connection).spheroid def units(self, connection): return get_srid_info(self.srid, connection).units def units_name(self, connection): return get_srid_info(self.srid, connection).units_name def geodetic(self, connection): """ Return true if this field's SRID corresponds with a coordinate system that uses non-projected units (e.g., latitude/longitude). """ return get_srid_info(self.srid, connection).geodetic def get_placeholder(self, value, compiler, connection): """ Return the placeholder for the spatial column for the given value. """ return connection.ops.get_geom_placeholder(self, value, compiler) def get_srid(self, obj): """ Return the default SRID for the given geometry or raster, taking into account the SRID set for the field. For example, if the input geometry or raster doesn't have an SRID, then the SRID of the field will be returned. """ srid = obj.srid # SRID of given geometry. if srid is None or self.srid == -1 or (srid == -1 and self.srid != -1): return self.srid else: return srid def get_db_prep_value(self, value, connection, *args, **kwargs): if value is None: return None return connection.ops.Adapter( super().get_db_prep_value(value, connection, *args, **kwargs), **( {"geography": True} if self.geography and connection.features.supports_geography else {} ), ) def get_raster_prep_value(self, value, is_candidate): """ Return a GDALRaster if conversion is successful, otherwise return None. """ if isinstance(value, gdal.GDALRaster): return value elif is_candidate: try: return gdal.GDALRaster(value) except GDALException: pass elif isinstance(value, dict): try: return gdal.GDALRaster(value) except GDALException: raise ValueError( "Couldn't create spatial object from lookup value '%s'." % value ) def get_prep_value(self, value): obj = super().get_prep_value(value) if obj is None: return None # When the input is not a geometry or raster, attempt to construct one # from the given string input. if isinstance(obj, GEOSGeometry): pass else: # Check if input is a candidate for conversion to raster or geometry. is_candidate = isinstance(obj, (bytes, str)) or hasattr( obj, "__geo_interface__" ) # Try to convert the input to raster. raster = self.get_raster_prep_value(obj, is_candidate) if raster: obj = raster elif is_candidate: try: obj = GEOSGeometry(obj) except (GEOSException, GDALException): raise ValueError( "Couldn't create spatial object from lookup value '%s'." % obj ) else: raise ValueError( "Cannot use object with type %s for a spatial lookup parameter." % type(obj).__name__ ) # Assigning the SRID value. obj.srid = self.get_srid(obj) return obj class GeometryField(BaseSpatialField): """ The base Geometry field -- maps to the OpenGIS Specification Geometry type. """ description = _( "The base Geometry field — maps to the OpenGIS Specification Geometry type." ) form_class = forms.GeometryField # The OpenGIS Geometry name. geom_type = "GEOMETRY" geom_class = None def __init__( self, verbose_name=None, dim=2, geography=False, *, extent=(-180.0, -90.0, 180.0, 90.0), tolerance=0.05, **kwargs, ): """ The initialization function for geometry fields. In addition to the parameters from BaseSpatialField, it takes the following as keyword arguments: dim: The number of dimensions for this geometry. Defaults to 2. extent: Customize the extent, in a 4-tuple of WGS 84 coordinates, for the geometry field entry in the `USER_SDO_GEOM_METADATA` table. Defaults to (-180.0, -90.0, 180.0, 90.0). tolerance: Define the tolerance, in meters, to use for the geometry field entry in the `USER_SDO_GEOM_METADATA` table. Defaults to 0.05. """ # Setting the dimension of the geometry field. self.dim = dim # Is this a geography rather than a geometry column? self.geography = geography # Oracle-specific private attributes for creating the entry in # `USER_SDO_GEOM_METADATA` self._extent = extent self._tolerance = tolerance super().__init__(verbose_name=verbose_name, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() # Include kwargs if they're not the default values. if self.dim != 2: kwargs["dim"] = self.dim if self.geography is not False: kwargs["geography"] = self.geography if self._extent != (-180.0, -90.0, 180.0, 90.0): kwargs["extent"] = self._extent if self._tolerance != 0.05: kwargs["tolerance"] = self._tolerance return name, path, args, kwargs def contribute_to_class(self, cls, name, **kwargs): super().contribute_to_class(cls, name, **kwargs) # Setup for lazy-instantiated Geometry object. setattr( cls, self.attname, SpatialProxy(self.geom_class or GEOSGeometry, self, load_func=GEOSGeometry), ) def formfield(self, **kwargs): defaults = { "form_class": self.form_class, "geom_type": self.geom_type, "srid": self.srid, **kwargs, } if self.dim > 2 and not getattr( defaults["form_class"].widget, "supports_3d", False ): defaults.setdefault("widget", forms.Textarea) return super().formfield(**defaults) def select_format(self, compiler, sql, params): """ Return the selection format string, depending on the requirements of the spatial backend. For example, Oracle and MySQL require custom selection formats in order to retrieve geometries in OGC WKB. """ if not compiler.query.subquery: return compiler.connection.ops.select % sql, params return sql, params # The OpenGIS Geometry Type Fields class PointField(GeometryField): geom_type = "POINT" geom_class = Point form_class = forms.PointField description = _("Point") class LineStringField(GeometryField): geom_type = "LINESTRING" geom_class = LineString form_class = forms.LineStringField description = _("Line string") class PolygonField(GeometryField): geom_type = "POLYGON" geom_class = Polygon form_class = forms.PolygonField description = _("Polygon") class MultiPointField(GeometryField): geom_type = "MULTIPOINT" geom_class = MultiPoint form_class = forms.MultiPointField description = _("Multi-point") class MultiLineStringField(GeometryField): geom_type = "MULTILINESTRING" geom_class = MultiLineString form_class = forms.MultiLineStringField description = _("Multi-line string") class MultiPolygonField(GeometryField): geom_type = "MULTIPOLYGON" geom_class = MultiPolygon form_class = forms.MultiPolygonField description = _("Multi polygon") class GeometryCollectionField(GeometryField): geom_type = "GEOMETRYCOLLECTION" geom_class = GeometryCollection form_class = forms.GeometryCollectionField description = _("Geometry collection") class ExtentField(Field): "Used as a return value from an extent aggregate" description = _("Extent Aggregate Field") def get_internal_type(self): return "ExtentField" def select_format(self, compiler, sql, params): select = compiler.connection.ops.select_extent return select % sql if select else sql, params class RasterField(BaseSpatialField): """ Raster field for GeoDjango -- evaluates into GDALRaster objects. """ description = _("Raster Field") geom_type = "RASTER" geography = False def _check_connection(self, connection): # Make sure raster fields are used only on backends with raster support. if ( not connection.features.gis_enabled or not connection.features.supports_raster ): raise ImproperlyConfigured( "Raster fields require backends with raster support." ) def db_type(self, connection): self._check_connection(connection) return super().db_type(connection) def from_db_value(self, value, expression, connection): return connection.ops.parse_raster(value) def contribute_to_class(self, cls, name, **kwargs): super().contribute_to_class(cls, name, **kwargs) # Setup for lazy-instantiated Raster object. For large querysets, the # instantiation of all GDALRasters can potentially be expensive. This # delays the instantiation of the objects to the moment of evaluation # of the raster attribute. setattr(cls, self.attname, SpatialProxy(gdal.GDALRaster, self)) def get_transform(self, name): from django.contrib.gis.db.models.lookups import RasterBandTransform try: band_index = int(name) return type( "SpecificRasterBandTransform", (RasterBandTransform,), {"band_index": band_index}, ) except ValueError: pass return super().get_transform(name)
bfe0d22c4f907c10a084d9fe3366735db284a32303ba54b9f350887920480af8
from decimal import Decimal from django.contrib.gis.db.models.fields import BaseSpatialField, GeometryField from django.contrib.gis.db.models.sql import AreaField, DistanceField from django.contrib.gis.geos import GEOSGeometry from django.core.exceptions import FieldError from django.db import NotSupportedError from django.db.models import ( BinaryField, BooleanField, FloatField, Func, IntegerField, TextField, Transform, Value, ) from django.db.models.functions import Cast from django.utils.functional import cached_property NUMERIC_TYPES = (int, float, Decimal) class GeoFuncMixin: function = None geom_param_pos = (0,) def __init__(self, *expressions, **extra): super().__init__(*expressions, **extra) # Ensure that value expressions are geometric. for pos in self.geom_param_pos: expr = self.source_expressions[pos] if not isinstance(expr, Value): continue try: output_field = expr.output_field except FieldError: output_field = None geom = expr.value if ( not isinstance(geom, GEOSGeometry) or output_field and not isinstance(output_field, GeometryField) ): raise TypeError( "%s function requires a geometric argument in position %d." % (self.name, pos + 1) ) if not geom.srid and not output_field: raise ValueError("SRID is required for all geometries.") if not output_field: self.source_expressions[pos] = Value( geom, output_field=GeometryField(srid=geom.srid) ) @property def name(self): return self.__class__.__name__ @cached_property def geo_field(self): return self.source_expressions[self.geom_param_pos[0]].field def as_sql(self, compiler, connection, function=None, **extra_context): if self.function is None and function is None: function = connection.ops.spatial_function_name(self.name) return super().as_sql(compiler, connection, function=function, **extra_context) def resolve_expression(self, *args, **kwargs): res = super().resolve_expression(*args, **kwargs) # Ensure that expressions are geometric. source_fields = res.get_source_fields() for pos in self.geom_param_pos: field = source_fields[pos] if not isinstance(field, GeometryField): raise TypeError( "%s function requires a GeometryField in position %s, got %s." % ( self.name, pos + 1, type(field).__name__, ) ) base_srid = res.geo_field.srid for pos in self.geom_param_pos[1:]: expr = res.source_expressions[pos] expr_srid = expr.output_field.srid if expr_srid != base_srid: # Automatic SRID conversion so objects are comparable. res.source_expressions[pos] = Transform( expr, base_srid ).resolve_expression(*args, **kwargs) return res def _handle_param(self, value, param_name="", check_types=None): if not hasattr(value, "resolve_expression"): if check_types and not isinstance(value, check_types): raise TypeError( "The %s parameter has the wrong type: should be %s." % (param_name, check_types) ) return value class GeoFunc(GeoFuncMixin, Func): pass class GeomOutputGeoFunc(GeoFunc): @cached_property def output_field(self): return GeometryField(srid=self.geo_field.srid) class SQLiteDecimalToFloatMixin: """ By default, Decimal values are converted to str by the SQLite backend, which is not acceptable by the GIS functions expecting numeric values. """ def as_sqlite(self, compiler, connection, **extra_context): copy = self.copy() copy.set_source_expressions( [ Value(float(expr.value)) if hasattr(expr, "value") and isinstance(expr.value, Decimal) else expr for expr in copy.get_source_expressions() ] ) return copy.as_sql(compiler, connection, **extra_context) class OracleToleranceMixin: tolerance = 0.05 def as_oracle(self, compiler, connection, **extra_context): tolerance = Value( self._handle_param( self.extra.get("tolerance", self.tolerance), "tolerance", NUMERIC_TYPES, ) ) clone = self.copy() clone.set_source_expressions([*self.get_source_expressions(), tolerance]) return clone.as_sql(compiler, connection, **extra_context) class Area(OracleToleranceMixin, GeoFunc): arity = 1 @cached_property def output_field(self): return AreaField(self.geo_field) def as_sql(self, compiler, connection, **extra_context): if not connection.features.supports_area_geodetic and self.geo_field.geodetic( connection ): raise NotSupportedError( "Area on geodetic coordinate systems not supported." ) return super().as_sql(compiler, connection, **extra_context) def as_sqlite(self, compiler, connection, **extra_context): if self.geo_field.geodetic(connection): extra_context["template"] = "%(function)s(%(expressions)s, %(spheroid)d)" extra_context["spheroid"] = True return self.as_sql(compiler, connection, **extra_context) class Azimuth(GeoFunc): output_field = FloatField() arity = 2 geom_param_pos = (0, 1) class AsGeoJSON(GeoFunc): output_field = TextField() def __init__(self, expression, bbox=False, crs=False, precision=8, **extra): expressions = [expression] if precision is not None: expressions.append(self._handle_param(precision, "precision", int)) options = 0 if crs and bbox: options = 3 elif bbox: options = 1 elif crs: options = 2 if options: expressions.append(options) super().__init__(*expressions, **extra) def as_oracle(self, compiler, connection, **extra_context): source_expressions = self.get_source_expressions() clone = self.copy() clone.set_source_expressions(source_expressions[:1]) return super(AsGeoJSON, clone).as_sql(compiler, connection, **extra_context) class AsGML(GeoFunc): geom_param_pos = (1,) output_field = TextField() def __init__(self, expression, version=2, precision=8, **extra): expressions = [version, expression] if precision is not None: expressions.append(self._handle_param(precision, "precision", int)) super().__init__(*expressions, **extra) def as_oracle(self, compiler, connection, **extra_context): source_expressions = self.get_source_expressions() version = source_expressions[0] clone = self.copy() clone.set_source_expressions([source_expressions[1]]) extra_context["function"] = ( "SDO_UTIL.TO_GML311GEOMETRY" if version.value == 3 else "SDO_UTIL.TO_GMLGEOMETRY" ) return super(AsGML, clone).as_sql(compiler, connection, **extra_context) class AsKML(GeoFunc): output_field = TextField() def __init__(self, expression, precision=8, **extra): expressions = [expression] if precision is not None: expressions.append(self._handle_param(precision, "precision", int)) super().__init__(*expressions, **extra) class AsSVG(GeoFunc): output_field = TextField() def __init__(self, expression, relative=False, precision=8, **extra): relative = ( relative if hasattr(relative, "resolve_expression") else int(relative) ) expressions = [ expression, relative, self._handle_param(precision, "precision", int), ] super().__init__(*expressions, **extra) class AsWKB(GeoFunc): output_field = BinaryField() arity = 1 class AsWKT(GeoFunc): output_field = TextField() arity = 1 class BoundingCircle(OracleToleranceMixin, GeomOutputGeoFunc): def __init__(self, expression, num_seg=48, **extra): super().__init__(expression, num_seg, **extra) def as_oracle(self, compiler, connection, **extra_context): clone = self.copy() clone.set_source_expressions([self.get_source_expressions()[0]]) return super(BoundingCircle, clone).as_oracle( compiler, connection, **extra_context ) class Centroid(OracleToleranceMixin, GeomOutputGeoFunc): arity = 1 class Difference(OracleToleranceMixin, GeomOutputGeoFunc): arity = 2 geom_param_pos = (0, 1) class DistanceResultMixin: @cached_property def output_field(self): return DistanceField(self.geo_field) def source_is_geography(self): return self.geo_field.geography and self.geo_field.srid == 4326 class Distance(DistanceResultMixin, OracleToleranceMixin, GeoFunc): geom_param_pos = (0, 1) spheroid = None def __init__(self, expr1, expr2, spheroid=None, **extra): expressions = [expr1, expr2] if spheroid is not None: self.spheroid = self._handle_param(spheroid, "spheroid", bool) super().__init__(*expressions, **extra) def as_postgresql(self, compiler, connection, **extra_context): clone = self.copy() function = None expr2 = clone.source_expressions[1] geography = self.source_is_geography() if expr2.output_field.geography != geography: if isinstance(expr2, Value): expr2.output_field.geography = geography else: clone.source_expressions[1] = Cast( expr2, GeometryField(srid=expr2.output_field.srid, geography=geography), ) if not geography and self.geo_field.geodetic(connection): # Geometry fields with geodetic (lon/lat) coordinates need special # distance functions. if self.spheroid: # DistanceSpheroid is more accurate and resource intensive than # DistanceSphere. function = connection.ops.spatial_function_name("DistanceSpheroid") # Replace boolean param by the real spheroid of the base field clone.source_expressions.append( Value(self.geo_field.spheroid(connection)) ) else: function = connection.ops.spatial_function_name("DistanceSphere") return super(Distance, clone).as_sql( compiler, connection, function=function, **extra_context ) def as_sqlite(self, compiler, connection, **extra_context): if self.geo_field.geodetic(connection): # SpatiaLite returns NULL instead of zero on geodetic coordinates extra_context[ "template" ] = "COALESCE(%(function)s(%(expressions)s, %(spheroid)s), 0)" extra_context["spheroid"] = int(bool(self.spheroid)) return super().as_sql(compiler, connection, **extra_context) class Envelope(GeomOutputGeoFunc): arity = 1 class ForcePolygonCW(GeomOutputGeoFunc): arity = 1 class GeoHash(GeoFunc): output_field = TextField() def __init__(self, expression, precision=None, **extra): expressions = [expression] if precision is not None: expressions.append(self._handle_param(precision, "precision", int)) super().__init__(*expressions, **extra) def as_mysql(self, compiler, connection, **extra_context): clone = self.copy() # If no precision is provided, set it to the maximum. if len(clone.source_expressions) < 2: clone.source_expressions.append(Value(100)) return clone.as_sql(compiler, connection, **extra_context) class GeometryDistance(GeoFunc): output_field = FloatField() arity = 2 function = "" arg_joiner = " <-> " geom_param_pos = (0, 1) class Intersection(OracleToleranceMixin, GeomOutputGeoFunc): arity = 2 geom_param_pos = (0, 1) @BaseSpatialField.register_lookup class IsValid(OracleToleranceMixin, GeoFuncMixin, Transform): lookup_name = "isvalid" output_field = BooleanField() def as_oracle(self, compiler, connection, **extra_context): sql, params = super().as_oracle(compiler, connection, **extra_context) return "CASE %s WHEN 'TRUE' THEN 1 ELSE 0 END" % sql, params class Length(DistanceResultMixin, OracleToleranceMixin, GeoFunc): def __init__(self, expr1, spheroid=True, **extra): self.spheroid = spheroid super().__init__(expr1, **extra) def as_sql(self, compiler, connection, **extra_context): if ( self.geo_field.geodetic(connection) and not connection.features.supports_length_geodetic ): raise NotSupportedError( "This backend doesn't support Length on geodetic fields" ) return super().as_sql(compiler, connection, **extra_context) def as_postgresql(self, compiler, connection, **extra_context): clone = self.copy() function = None if self.source_is_geography(): clone.source_expressions.append(Value(self.spheroid)) elif self.geo_field.geodetic(connection): # Geometry fields with geodetic (lon/lat) coordinates need length_spheroid function = connection.ops.spatial_function_name("LengthSpheroid") clone.source_expressions.append(Value(self.geo_field.spheroid(connection))) else: dim = min(f.dim for f in self.get_source_fields() if f) if dim > 2: function = connection.ops.length3d return super(Length, clone).as_sql( compiler, connection, function=function, **extra_context ) def as_sqlite(self, compiler, connection, **extra_context): function = None if self.geo_field.geodetic(connection): function = "GeodesicLength" if self.spheroid else "GreatCircleLength" return super().as_sql(compiler, connection, function=function, **extra_context) class LineLocatePoint(GeoFunc): output_field = FloatField() arity = 2 geom_param_pos = (0, 1) class MakeValid(GeomOutputGeoFunc): pass class MemSize(GeoFunc): output_field = IntegerField() arity = 1 class NumGeometries(GeoFunc): output_field = IntegerField() arity = 1 class NumPoints(GeoFunc): output_field = IntegerField() arity = 1 class Perimeter(DistanceResultMixin, OracleToleranceMixin, GeoFunc): arity = 1 def as_postgresql(self, compiler, connection, **extra_context): function = None if self.geo_field.geodetic(connection) and not self.source_is_geography(): raise NotSupportedError( "ST_Perimeter cannot use a non-projected non-geography field." ) dim = min(f.dim for f in self.get_source_fields()) if dim > 2: function = connection.ops.perimeter3d return super().as_sql(compiler, connection, function=function, **extra_context) def as_sqlite(self, compiler, connection, **extra_context): if self.geo_field.geodetic(connection): raise NotSupportedError("Perimeter cannot use a non-projected field.") return super().as_sql(compiler, connection, **extra_context) class PointOnSurface(OracleToleranceMixin, GeomOutputGeoFunc): arity = 1 class Reverse(GeoFunc): arity = 1 class Scale(SQLiteDecimalToFloatMixin, GeomOutputGeoFunc): def __init__(self, expression, x, y, z=0.0, **extra): expressions = [ expression, self._handle_param(x, "x", NUMERIC_TYPES), self._handle_param(y, "y", NUMERIC_TYPES), ] if z != 0.0: expressions.append(self._handle_param(z, "z", NUMERIC_TYPES)) super().__init__(*expressions, **extra) class SnapToGrid(SQLiteDecimalToFloatMixin, GeomOutputGeoFunc): def __init__(self, expression, *args, **extra): nargs = len(args) expressions = [expression] if nargs in (1, 2): expressions.extend( [self._handle_param(arg, "", NUMERIC_TYPES) for arg in args] ) elif nargs == 4: # Reverse origin and size param ordering expressions += [ *(self._handle_param(arg, "", NUMERIC_TYPES) for arg in args[2:]), *(self._handle_param(arg, "", NUMERIC_TYPES) for arg in args[0:2]), ] else: raise ValueError("Must provide 1, 2, or 4 arguments to `SnapToGrid`.") super().__init__(*expressions, **extra) class SymDifference(OracleToleranceMixin, GeomOutputGeoFunc): arity = 2 geom_param_pos = (0, 1) class Transform(GeomOutputGeoFunc): def __init__(self, expression, srid, **extra): expressions = [ expression, self._handle_param(srid, "srid", int), ] if "output_field" not in extra: extra["output_field"] = GeometryField(srid=srid) super().__init__(*expressions, **extra) class Translate(Scale): def as_sqlite(self, compiler, connection, **extra_context): clone = self.copy() if len(self.source_expressions) < 4: # Always provide the z parameter for ST_Translate clone.source_expressions.append(Value(0)) return super(Translate, clone).as_sqlite(compiler, connection, **extra_context) class Union(OracleToleranceMixin, GeomOutputGeoFunc): arity = 2 geom_param_pos = (0, 1)
d6b68474a3359bb7b6add311678837d142b32e2789d5009770075e032b87d4b0
from django.contrib.gis.db.models.fields import BaseSpatialField from django.contrib.gis.measure import Distance from django.db import NotSupportedError from django.db.models import Expression, Lookup, Transform from django.db.models.sql.query import Query from django.utils.regex_helper import _lazy_re_compile class RasterBandTransform(Transform): def as_sql(self, compiler, connection): return compiler.compile(self.lhs) class GISLookup(Lookup): sql_template = None transform_func = None distance = False band_rhs = None band_lhs = None def __init__(self, lhs, rhs): rhs, *self.rhs_params = rhs if isinstance(rhs, (list, tuple)) else [rhs] super().__init__(lhs, rhs) self.template_params = {} self.process_rhs_params() def process_rhs_params(self): if self.rhs_params: # Check if a band index was passed in the query argument. if len(self.rhs_params) == (2 if self.lookup_name == "relate" else 1): self.process_band_indices() elif len(self.rhs_params) > 1: raise ValueError("Tuple too long for lookup %s." % self.lookup_name) elif isinstance(self.lhs, RasterBandTransform): self.process_band_indices(only_lhs=True) def process_band_indices(self, only_lhs=False): """ Extract the lhs band index from the band transform class and the rhs band index from the input tuple. """ # PostGIS band indices are 1-based, so the band index needs to be # increased to be consistent with the GDALRaster band indices. if only_lhs: self.band_rhs = 1 self.band_lhs = self.lhs.band_index + 1 return if isinstance(self.lhs, RasterBandTransform): self.band_lhs = self.lhs.band_index + 1 else: self.band_lhs = 1 self.band_rhs, *self.rhs_params = self.rhs_params def get_db_prep_lookup(self, value, connection): # get_db_prep_lookup is called by process_rhs from super class return ("%s", [connection.ops.Adapter(value)]) def process_rhs(self, compiler, connection): if isinstance(self.rhs, Query): # If rhs is some Query, don't touch it. return super().process_rhs(compiler, connection) if isinstance(self.rhs, Expression): self.rhs = self.rhs.resolve_expression(compiler.query) rhs, rhs_params = super().process_rhs(compiler, connection) placeholder = connection.ops.get_geom_placeholder( self.lhs.output_field, self.rhs, compiler ) return placeholder % rhs, rhs_params def get_rhs_op(self, connection, rhs): # Unlike BuiltinLookup, the GIS get_rhs_op() implementation should return # an object (SpatialOperator) with an as_sql() method to allow for more # complex computations (where the lhs part can be mixed in). return connection.ops.gis_operators[self.lookup_name] def as_sql(self, compiler, connection): lhs_sql, lhs_params = self.process_lhs(compiler, connection) rhs_sql, rhs_params = self.process_rhs(compiler, connection) sql_params = (*lhs_params, *rhs_params) template_params = { "lhs": lhs_sql, "rhs": rhs_sql, "value": "%s", **self.template_params, } rhs_op = self.get_rhs_op(connection, rhs_sql) return rhs_op.as_sql(connection, self, template_params, sql_params) # ------------------ # Geometry operators # ------------------ @BaseSpatialField.register_lookup class OverlapsLeftLookup(GISLookup): """ The overlaps_left operator returns true if A's bounding box overlaps or is to the left of B's bounding box. """ lookup_name = "overlaps_left" @BaseSpatialField.register_lookup class OverlapsRightLookup(GISLookup): """ The 'overlaps_right' operator returns true if A's bounding box overlaps or is to the right of B's bounding box. """ lookup_name = "overlaps_right" @BaseSpatialField.register_lookup class OverlapsBelowLookup(GISLookup): """ The 'overlaps_below' operator returns true if A's bounding box overlaps or is below B's bounding box. """ lookup_name = "overlaps_below" @BaseSpatialField.register_lookup class OverlapsAboveLookup(GISLookup): """ The 'overlaps_above' operator returns true if A's bounding box overlaps or is above B's bounding box. """ lookup_name = "overlaps_above" @BaseSpatialField.register_lookup class LeftLookup(GISLookup): """ The 'left' operator returns true if A's bounding box is strictly to the left of B's bounding box. """ lookup_name = "left" @BaseSpatialField.register_lookup class RightLookup(GISLookup): """ The 'right' operator returns true if A's bounding box is strictly to the right of B's bounding box. """ lookup_name = "right" @BaseSpatialField.register_lookup class StrictlyBelowLookup(GISLookup): """ The 'strictly_below' operator returns true if A's bounding box is strictly below B's bounding box. """ lookup_name = "strictly_below" @BaseSpatialField.register_lookup class StrictlyAboveLookup(GISLookup): """ The 'strictly_above' operator returns true if A's bounding box is strictly above B's bounding box. """ lookup_name = "strictly_above" @BaseSpatialField.register_lookup class SameAsLookup(GISLookup): """ The "~=" operator is the "same as" operator. It tests actual geometric equality of two features. So if A and B are the same feature, vertex-by-vertex, the operator returns true. """ lookup_name = "same_as" BaseSpatialField.register_lookup(SameAsLookup, "exact") @BaseSpatialField.register_lookup class BBContainsLookup(GISLookup): """ The 'bbcontains' operator returns true if A's bounding box completely contains by B's bounding box. """ lookup_name = "bbcontains" @BaseSpatialField.register_lookup class BBOverlapsLookup(GISLookup): """ The 'bboverlaps' operator returns true if A's bounding box overlaps B's bounding box. """ lookup_name = "bboverlaps" @BaseSpatialField.register_lookup class ContainedLookup(GISLookup): """ The 'contained' operator returns true if A's bounding box is completely contained by B's bounding box. """ lookup_name = "contained" # ------------------ # Geometry functions # ------------------ @BaseSpatialField.register_lookup class ContainsLookup(GISLookup): lookup_name = "contains" @BaseSpatialField.register_lookup class ContainsProperlyLookup(GISLookup): lookup_name = "contains_properly" @BaseSpatialField.register_lookup class CoveredByLookup(GISLookup): lookup_name = "coveredby" @BaseSpatialField.register_lookup class CoversLookup(GISLookup): lookup_name = "covers" @BaseSpatialField.register_lookup class CrossesLookup(GISLookup): lookup_name = "crosses" @BaseSpatialField.register_lookup class DisjointLookup(GISLookup): lookup_name = "disjoint" @BaseSpatialField.register_lookup class EqualsLookup(GISLookup): lookup_name = "equals" @BaseSpatialField.register_lookup class IntersectsLookup(GISLookup): lookup_name = "intersects" @BaseSpatialField.register_lookup class OverlapsLookup(GISLookup): lookup_name = "overlaps" @BaseSpatialField.register_lookup class RelateLookup(GISLookup): lookup_name = "relate" sql_template = "%(func)s(%(lhs)s, %(rhs)s, %%s)" pattern_regex = _lazy_re_compile(r"^[012TF\*]{9}$") def process_rhs(self, compiler, connection): # Check the pattern argument pattern = self.rhs_params[0] backend_op = connection.ops.gis_operators[self.lookup_name] if hasattr(backend_op, "check_relate_argument"): backend_op.check_relate_argument(pattern) elif not isinstance(pattern, str) or not self.pattern_regex.match(pattern): raise ValueError('Invalid intersection matrix pattern "%s".' % pattern) sql, params = super().process_rhs(compiler, connection) return sql, params + [pattern] @BaseSpatialField.register_lookup class TouchesLookup(GISLookup): lookup_name = "touches" @BaseSpatialField.register_lookup class WithinLookup(GISLookup): lookup_name = "within" class DistanceLookupBase(GISLookup): distance = True sql_template = "%(func)s(%(lhs)s, %(rhs)s) %(op)s %(value)s" def process_rhs_params(self): if not 1 <= len(self.rhs_params) <= 3: raise ValueError( "2, 3, or 4-element tuple required for '%s' lookup." % self.lookup_name ) elif len(self.rhs_params) == 3 and self.rhs_params[2] != "spheroid": raise ValueError( "For 4-element tuples the last argument must be the 'spheroid' " "directive." ) # Check if the second parameter is a band index. if len(self.rhs_params) > 1 and self.rhs_params[1] != "spheroid": self.process_band_indices() def process_distance(self, compiler, connection): dist_param = self.rhs_params[0] return ( compiler.compile(dist_param.resolve_expression(compiler.query)) if hasattr(dist_param, "resolve_expression") else ( "%s", connection.ops.get_distance( self.lhs.output_field, self.rhs_params, self.lookup_name ), ) ) @BaseSpatialField.register_lookup class DWithinLookup(DistanceLookupBase): lookup_name = "dwithin" sql_template = "%(func)s(%(lhs)s, %(rhs)s, %(value)s)" def process_distance(self, compiler, connection): dist_param = self.rhs_params[0] if ( not connection.features.supports_dwithin_distance_expr and hasattr(dist_param, "resolve_expression") and not isinstance(dist_param, Distance) ): raise NotSupportedError( "This backend does not support expressions for specifying " "distance in the dwithin lookup." ) return super().process_distance(compiler, connection) def process_rhs(self, compiler, connection): dist_sql, dist_params = self.process_distance(compiler, connection) self.template_params["value"] = dist_sql rhs_sql, params = super().process_rhs(compiler, connection) return rhs_sql, params + dist_params class DistanceLookupFromFunction(DistanceLookupBase): def as_sql(self, compiler, connection): spheroid = ( len(self.rhs_params) == 2 and self.rhs_params[-1] == "spheroid" ) or None distance_expr = connection.ops.distance_expr_for_lookup( self.lhs, self.rhs, spheroid=spheroid ) sql, params = compiler.compile(distance_expr.resolve_expression(compiler.query)) dist_sql, dist_params = self.process_distance(compiler, connection) return ( "%(func)s %(op)s %(dist)s" % {"func": sql, "op": self.op, "dist": dist_sql}, params + dist_params, ) @BaseSpatialField.register_lookup class DistanceGTLookup(DistanceLookupFromFunction): lookup_name = "distance_gt" op = ">" @BaseSpatialField.register_lookup class DistanceGTELookup(DistanceLookupFromFunction): lookup_name = "distance_gte" op = ">=" @BaseSpatialField.register_lookup class DistanceLTLookup(DistanceLookupFromFunction): lookup_name = "distance_lt" op = "<" @BaseSpatialField.register_lookup class DistanceLTELookup(DistanceLookupFromFunction): lookup_name = "distance_lte" op = "<="
acbc12bfbf6d2893f1bc31c0098f2b84f0cb1590bbf66108948c924f297faaa7
""" A collection of utility routines and classes used by the spatial backends. """ class SpatialOperator: """ Class encapsulating the behavior specific to a GIS operation (used by lookups). """ sql_template = None def __init__(self, op=None, func=None): self.op = op self.func = func @property def default_template(self): if self.func: return "%(func)s(%(lhs)s, %(rhs)s)" else: return "%(lhs)s %(op)s %(rhs)s" def as_sql(self, connection, lookup, template_params, sql_params): sql_template = self.sql_template or lookup.sql_template or self.default_template template_params.update({"op": self.op, "func": self.func}) return sql_template % template_params, sql_params
fabcdc0b78b33098b66e7bf241408ccc83ab8a006763a37fe444088a6e300926
from django.contrib.gis.db.models.sql.conversion import AreaField, DistanceField __all__ = [ "AreaField", "DistanceField", ]
0192c908c4b0fecbd22d03c1e4b4ef03e61116731949761d1ddbcf4931662b86
""" This module holds simple classes to convert geospatial values from the database. """ from decimal import Decimal from django.contrib.gis.measure import Area, Distance from django.db import models class AreaField(models.FloatField): "Wrapper for Area values." def __init__(self, geo_field): super().__init__() self.geo_field = geo_field def get_prep_value(self, value): if not isinstance(value, Area): raise ValueError("AreaField only accepts Area measurement objects.") return value def get_db_prep_value(self, value, connection, prepared=False): if value is None: return area_att = connection.ops.get_area_att_for_field(self.geo_field) return getattr(value, area_att) if area_att else value def from_db_value(self, value, expression, connection): if value is None: return # If the database returns a Decimal, convert it to a float as expected # by the Python geometric objects. if isinstance(value, Decimal): value = float(value) # If the units are known, convert value into area measure. area_att = connection.ops.get_area_att_for_field(self.geo_field) return Area(**{area_att: value}) if area_att else value def get_internal_type(self): return "AreaField" class DistanceField(models.FloatField): "Wrapper for Distance values." def __init__(self, geo_field): super().__init__() self.geo_field = geo_field def get_prep_value(self, value): if isinstance(value, Distance): return value return super().get_prep_value(value) def get_db_prep_value(self, value, connection, prepared=False): if not isinstance(value, Distance): return value distance_att = connection.ops.get_distance_att_for_field(self.geo_field) if not distance_att: raise ValueError( "Distance measure is supplied, but units are unknown for result." ) return getattr(value, distance_att) def from_db_value(self, value, expression, connection): if value is None: return distance_att = connection.ops.get_distance_att_for_field(self.geo_field) return Distance(**{distance_att: value}) if distance_att else value def get_internal_type(self): return "DistanceField"
df2083bad2b3e225f4d5e3a32dfd022defdc7a631a4630e61fc64a372fd26f29
from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures from django.db.backends.oracle.features import ( DatabaseFeatures as OracleDatabaseFeatures, ) from django.utils.functional import cached_property class DatabaseFeatures(BaseSpatialFeatures, OracleDatabaseFeatures): supports_add_srs_entry = False supports_geometry_field_introspection = False supports_geometry_field_unique_index = False supports_perimeter_geodetic = True supports_dwithin_distance_expr = False supports_tolerance_parameter = True unsupported_geojson_options = {"bbox", "crs", "precision"} @cached_property def django_test_skips(self): skips = super().django_test_skips skips.update( { "Oracle doesn't support spatial operators in constraints.": { "gis_tests.gis_migrations.test_operations.OperationTests." "test_add_check_constraint", }, } ) return skips
e75fe7cfcfce2863f54c2c38e27a36d15b7a115d41f4c4cabbc8ab4a792a641a
import cx_Oracle from django.db.backends.oracle.introspection import DatabaseIntrospection from django.utils.functional import cached_property class OracleIntrospection(DatabaseIntrospection): # Associating any OBJECTVAR instances with GeometryField. This won't work # right on Oracle objects that aren't MDSYS.SDO_GEOMETRY, but it is the # only object type supported within Django anyways. @cached_property def data_types_reverse(self): return { **super().data_types_reverse, cx_Oracle.OBJECT: "GeometryField", } def get_geometry_type(self, table_name, description): with self.connection.cursor() as cursor: # Querying USER_SDO_GEOM_METADATA to get the SRID and dimension information. try: cursor.execute( 'SELECT "DIMINFO", "SRID" FROM "USER_SDO_GEOM_METADATA" ' 'WHERE "TABLE_NAME"=%s AND "COLUMN_NAME"=%s', (table_name.upper(), description.name.upper()), ) row = cursor.fetchone() except Exception as exc: raise Exception( "Could not find entry in USER_SDO_GEOM_METADATA " 'corresponding to "%s"."%s"' % (table_name, description.name) ) from exc # TODO: Research way to find a more specific geometry field type for # the column's contents. field_type = "GeometryField" # Getting the field parameters. field_params = {} dim, srid = row if srid != 4326: field_params["srid"] = srid # Size of object array (SDO_DIM_ARRAY) is number of dimensions. dim = dim.size() if dim != 2: field_params["dim"] = dim return field_type, field_params
ee68a3ee8c269b0a8097ee2b3c998453fcd6de1659234862c7b1f214ec09926b
""" The GeometryColumns and SpatialRefSys models for the Oracle spatial backend. It should be noted that Oracle Spatial does not have database tables named according to the OGC standard, so the closest analogs are used. For example, the `USER_SDO_GEOM_METADATA` is used for the GeometryColumns model and the `SDO_COORD_REF_SYS` is used for the SpatialRefSys model. """ from django.contrib.gis.db import models from django.contrib.gis.db.backends.base.models import SpatialRefSysMixin class OracleGeometryColumns(models.Model): "Maps to the Oracle USER_SDO_GEOM_METADATA table." table_name = models.CharField(max_length=32) column_name = models.CharField(max_length=1024) srid = models.IntegerField(primary_key=True) # TODO: Add support for `diminfo` column (type MDSYS.SDO_DIM_ARRAY). class Meta: app_label = "gis" db_table = "USER_SDO_GEOM_METADATA" managed = False def __str__(self): return "%s - %s (SRID: %s)" % (self.table_name, self.column_name, self.srid) @classmethod def table_name_col(cls): """ Return the name of the metadata column used to store the feature table name. """ return "table_name" @classmethod def geom_col_name(cls): """ Return the name of the metadata column used to store the feature geometry column. """ return "column_name" class OracleSpatialRefSys(models.Model, SpatialRefSysMixin): "Maps to the Oracle MDSYS.CS_SRS table." cs_name = models.CharField(max_length=68) srid = models.IntegerField(primary_key=True) auth_srid = models.IntegerField() auth_name = models.CharField(max_length=256) wktext = models.CharField(max_length=2046) # Optional geometry representing the bounds of this coordinate # system. By default, all are NULL in the table. cs_bounds = models.PolygonField(null=True) class Meta: app_label = "gis" db_table = "CS_SRS" managed = False @property def wkt(self): return self.wktext
ffbaa1bc475b9eb25010a2f9d6c83c618bbc91162640d02506035bd8e51b064c
from django.db.backends.oracle.base import DatabaseWrapper as OracleDatabaseWrapper from .features import DatabaseFeatures from .introspection import OracleIntrospection from .operations import OracleOperations from .schema import OracleGISSchemaEditor class DatabaseWrapper(OracleDatabaseWrapper): SchemaEditorClass = OracleGISSchemaEditor # Classes instantiated in __init__(). features_class = DatabaseFeatures introspection_class = OracleIntrospection ops_class = OracleOperations
c7aceb680ca83196bcadd70b01cda4df9ae9ac9c41028ab30d274560c726e769
""" This module contains the spatial lookup types, and the `get_geo_where_clause` routine for Oracle Spatial. Please note that WKT support is broken on the XE version, and thus this backend will not work on such platforms. Specifically, XE lacks support for an internal JVM, and Java libraries are required to use the WKT constructors. """ import re from django.contrib.gis.db import models from django.contrib.gis.db.backends.base.operations import BaseSpatialOperations from django.contrib.gis.db.backends.oracle.adapter import OracleSpatialAdapter from django.contrib.gis.db.backends.utils import SpatialOperator from django.contrib.gis.geos.geometry import GEOSGeometry, GEOSGeometryBase from django.contrib.gis.geos.prototypes.io import wkb_r from django.contrib.gis.measure import Distance from django.db.backends.oracle.operations import DatabaseOperations DEFAULT_TOLERANCE = "0.05" class SDOOperator(SpatialOperator): sql_template = "%(func)s(%(lhs)s, %(rhs)s) = 'TRUE'" class SDODWithin(SpatialOperator): sql_template = "SDO_WITHIN_DISTANCE(%(lhs)s, %(rhs)s, %%s) = 'TRUE'" class SDODisjoint(SpatialOperator): sql_template = ( "SDO_GEOM.RELATE(%%(lhs)s, 'DISJOINT', %%(rhs)s, %s) = 'DISJOINT'" % DEFAULT_TOLERANCE ) class SDORelate(SpatialOperator): sql_template = "SDO_RELATE(%(lhs)s, %(rhs)s, 'mask=%(mask)s') = 'TRUE'" def check_relate_argument(self, arg): masks = ( "TOUCH|OVERLAPBDYDISJOINT|OVERLAPBDYINTERSECT|EQUAL|INSIDE|COVEREDBY|" "CONTAINS|COVERS|ANYINTERACT|ON" ) mask_regex = re.compile(r"^(%s)(\+(%s))*$" % (masks, masks), re.I) if not isinstance(arg, str) or not mask_regex.match(arg): raise ValueError('Invalid SDO_RELATE mask: "%s"' % arg) def as_sql(self, connection, lookup, template_params, sql_params): template_params["mask"] = sql_params[-1] return super().as_sql(connection, lookup, template_params, sql_params[:-1]) class OracleOperations(BaseSpatialOperations, DatabaseOperations): name = "oracle" oracle = True disallowed_aggregates = (models.Collect, models.Extent3D, models.MakeLine) Adapter = OracleSpatialAdapter extent = "SDO_AGGR_MBR" unionagg = "SDO_AGGR_UNION" from_text = "SDO_GEOMETRY" function_names = { "Area": "SDO_GEOM.SDO_AREA", "AsGeoJSON": "SDO_UTIL.TO_GEOJSON", "AsWKB": "SDO_UTIL.TO_WKBGEOMETRY", "AsWKT": "SDO_UTIL.TO_WKTGEOMETRY", "BoundingCircle": "SDO_GEOM.SDO_MBC", "Centroid": "SDO_GEOM.SDO_CENTROID", "Difference": "SDO_GEOM.SDO_DIFFERENCE", "Distance": "SDO_GEOM.SDO_DISTANCE", "Envelope": "SDO_GEOM_MBR", "Intersection": "SDO_GEOM.SDO_INTERSECTION", "IsValid": "SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT", "Length": "SDO_GEOM.SDO_LENGTH", "NumGeometries": "SDO_UTIL.GETNUMELEM", "NumPoints": "SDO_UTIL.GETNUMVERTICES", "Perimeter": "SDO_GEOM.SDO_LENGTH", "PointOnSurface": "SDO_GEOM.SDO_POINTONSURFACE", "Reverse": "SDO_UTIL.REVERSE_LINESTRING", "SymDifference": "SDO_GEOM.SDO_XOR", "Transform": "SDO_CS.TRANSFORM", "Union": "SDO_GEOM.SDO_UNION", } # We want to get SDO Geometries as WKT because it is much easier to # instantiate GEOS proxies from WKT than SDO_GEOMETRY(...) strings. # However, this adversely affects performance (i.e., Java is called # to convert to WKT on every query). If someone wishes to write a # SDO_GEOMETRY(...) parser in Python, let me know =) select = "SDO_UTIL.TO_WKBGEOMETRY(%s)" gis_operators = { "contains": SDOOperator(func="SDO_CONTAINS"), "coveredby": SDOOperator(func="SDO_COVEREDBY"), "covers": SDOOperator(func="SDO_COVERS"), "disjoint": SDODisjoint(), "intersects": SDOOperator( func="SDO_OVERLAPBDYINTERSECT" ), # TODO: Is this really the same as ST_Intersects()? "equals": SDOOperator(func="SDO_EQUAL"), "exact": SDOOperator(func="SDO_EQUAL"), "overlaps": SDOOperator(func="SDO_OVERLAPS"), "same_as": SDOOperator(func="SDO_EQUAL"), # Oracle uses a different syntax, e.g., 'mask=inside+touch' "relate": SDORelate(), "touches": SDOOperator(func="SDO_TOUCH"), "within": SDOOperator(func="SDO_INSIDE"), "dwithin": SDODWithin(), } unsupported_functions = { "AsKML", "AsSVG", "Azimuth", "ForcePolygonCW", "GeoHash", "GeometryDistance", "LineLocatePoint", "MakeValid", "MemSize", "Scale", "SnapToGrid", "Translate", } def geo_quote_name(self, name): return super().geo_quote_name(name).upper() def convert_extent(self, clob): if clob: # Generally, Oracle returns a polygon for the extent -- however, # it can return a single point if there's only one Point in the # table. ext_geom = GEOSGeometry(memoryview(clob.read())) gtype = str(ext_geom.geom_type) if gtype == "Polygon": # Construct the 4-tuple from the coordinates in the polygon. shell = ext_geom.shell ll, ur = shell[0][:2], shell[2][:2] elif gtype == "Point": ll = ext_geom.coords[:2] ur = ll else: raise Exception( "Unexpected geometry type returned for extent: %s" % gtype ) xmin, ymin = ll xmax, ymax = ur return (xmin, ymin, xmax, ymax) else: return None def geo_db_type(self, f): """ Return the geometry database type for Oracle. Unlike other spatial backends, no stored procedure is necessary and it's the same for all geometry types. """ return "MDSYS.SDO_GEOMETRY" def get_distance(self, f, value, lookup_type): """ Return the distance parameters given the value and the lookup type. On Oracle, geometry columns with a geodetic coordinate system behave implicitly like a geography column, and thus meters will be used as the distance parameter on them. """ if not value: return [] value = value[0] if isinstance(value, Distance): if f.geodetic(self.connection): dist_param = value.m else: dist_param = getattr( value, Distance.unit_attname(f.units_name(self.connection)) ) else: dist_param = value # dwithin lookups on Oracle require a special string parameter # that starts with "distance=". if lookup_type == "dwithin": dist_param = "distance=%s" % dist_param return [dist_param] def get_geom_placeholder(self, f, value, compiler): if value is None: return "NULL" return super().get_geom_placeholder(f, value, compiler) def spatial_aggregate_name(self, agg_name): """ Return the spatial aggregate SQL name. """ agg_name = "unionagg" if agg_name.lower() == "union" else agg_name.lower() return getattr(self, agg_name) # Routines for getting the OGC-compliant models. def geometry_columns(self): from django.contrib.gis.db.backends.oracle.models import OracleGeometryColumns return OracleGeometryColumns def spatial_ref_sys(self): from django.contrib.gis.db.backends.oracle.models import OracleSpatialRefSys return OracleSpatialRefSys def modify_insert_params(self, placeholder, params): """Drop out insert parameters for NULL placeholder. Needed for Oracle Spatial backend due to #10888. """ if placeholder == "NULL": return [] return super().modify_insert_params(placeholder, params) def get_geometry_converter(self, expression): read = wkb_r().read srid = expression.output_field.srid if srid == -1: srid = None geom_class = expression.output_field.geom_class def converter(value, expression, connection): if value is not None: geom = GEOSGeometryBase(read(memoryview(value.read())), geom_class) if srid: geom.srid = srid return geom return converter def get_area_att_for_field(self, field): return "sq_m"
e1b8ecb1db52976fe7dc2597ebb938c8b3822f37af53909883ecb1f2ce00dfd6
from django.contrib.gis.db.models import GeometryField from django.db.backends.oracle.schema import DatabaseSchemaEditor from django.db.backends.utils import strip_quotes, truncate_name class OracleGISSchemaEditor(DatabaseSchemaEditor): sql_add_geometry_metadata = """ INSERT INTO USER_SDO_GEOM_METADATA ("TABLE_NAME", "COLUMN_NAME", "DIMINFO", "SRID") VALUES ( %(table)s, %(column)s, MDSYS.SDO_DIM_ARRAY( MDSYS.SDO_DIM_ELEMENT('LONG', %(dim0)s, %(dim2)s, %(tolerance)s), MDSYS.SDO_DIM_ELEMENT('LAT', %(dim1)s, %(dim3)s, %(tolerance)s) ), %(srid)s )""" sql_add_spatial_index = ( "CREATE INDEX %(index)s ON %(table)s(%(column)s) " "INDEXTYPE IS MDSYS.SPATIAL_INDEX" ) sql_drop_spatial_index = "DROP INDEX %(index)s" sql_clear_geometry_table_metadata = ( "DELETE FROM USER_SDO_GEOM_METADATA WHERE TABLE_NAME = %(table)s" ) sql_clear_geometry_field_metadata = ( "DELETE FROM USER_SDO_GEOM_METADATA WHERE TABLE_NAME = %(table)s " "AND COLUMN_NAME = %(column)s" ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.geometry_sql = [] def geo_quote_name(self, name): return self.connection.ops.geo_quote_name(name) def quote_value(self, value): if isinstance(value, self.connection.ops.Adapter): return super().quote_value(str(value)) return super().quote_value(value) def column_sql(self, model, field, include_default=False): column_sql = super().column_sql(model, field, include_default) if isinstance(field, GeometryField): db_table = model._meta.db_table self.geometry_sql.append( self.sql_add_geometry_metadata % { "table": self.geo_quote_name(db_table), "column": self.geo_quote_name(field.column), "dim0": field._extent[0], "dim1": field._extent[1], "dim2": field._extent[2], "dim3": field._extent[3], "tolerance": field._tolerance, "srid": field.srid, } ) if field.spatial_index: self.geometry_sql.append( self.sql_add_spatial_index % { "index": self.quote_name( self._create_spatial_index_name(model, field) ), "table": self.quote_name(db_table), "column": self.quote_name(field.column), } ) return column_sql def create_model(self, model): super().create_model(model) self.run_geometry_sql() def delete_model(self, model): super().delete_model(model) self.execute( self.sql_clear_geometry_table_metadata % { "table": self.geo_quote_name(model._meta.db_table), } ) def add_field(self, model, field): super().add_field(model, field) self.run_geometry_sql() def remove_field(self, model, field): if isinstance(field, GeometryField): self.execute( self.sql_clear_geometry_field_metadata % { "table": self.geo_quote_name(model._meta.db_table), "column": self.geo_quote_name(field.column), } ) if field.spatial_index: self.execute( self.sql_drop_spatial_index % { "index": self.quote_name( self._create_spatial_index_name(model, field) ), } ) super().remove_field(model, field) def run_geometry_sql(self): for sql in self.geometry_sql: self.execute(sql) self.geometry_sql = [] def _create_spatial_index_name(self, model, field): # Oracle doesn't allow object names > 30 characters. Use this scheme # instead of self._create_index_name() for backwards compatibility. return truncate_name( "%s_%s_id" % (strip_quotes(model._meta.db_table), field.column), 30 )
201e42ff305eff2bdb67ec3bd64ba1fc0efbb06112b893946f119314a1070f0e
from cx_Oracle import CLOB from django.contrib.gis.db.backends.base.adapter import WKTAdapter from django.contrib.gis.geos import GeometryCollection, Polygon class OracleSpatialAdapter(WKTAdapter): input_size = CLOB def __init__(self, geom): """ Oracle requires that polygon rings are in proper orientation. This affects spatial operations and an invalid orientation may cause failures. Correct orientations are: * Outer ring - counter clockwise * Inner ring(s) - clockwise """ if isinstance(geom, Polygon): if self._polygon_must_be_fixed(geom): geom = self._fix_polygon(geom) elif isinstance(geom, GeometryCollection): if any( isinstance(g, Polygon) and self._polygon_must_be_fixed(g) for g in geom ): geom = self._fix_geometry_collection(geom) self.wkt = geom.wkt self.srid = geom.srid @staticmethod def _polygon_must_be_fixed(poly): return not poly.empty and ( not poly.exterior_ring.is_counterclockwise or any(x.is_counterclockwise for x in poly) ) @classmethod def _fix_polygon(cls, poly, clone=True): """Fix single polygon orientation as described in __init__().""" if clone: poly = poly.clone() if not poly.exterior_ring.is_counterclockwise: poly.exterior_ring = list(reversed(poly.exterior_ring)) for i in range(1, len(poly)): if poly[i].is_counterclockwise: poly[i] = list(reversed(poly[i])) return poly @classmethod def _fix_geometry_collection(cls, coll): """ Fix polygon orientations in geometry collections as described in __init__(). """ coll = coll.clone() for i, geom in enumerate(coll): if isinstance(geom, Polygon): coll[i] = cls._fix_polygon(geom, clone=False) return coll
7c5f80281ebffd18e4c5545a74d90e3fb02fe3031a4469172b26d857a112d869
import re from django.contrib.gis.db import models class BaseSpatialFeatures: gis_enabled = True # Does the database contain a SpatialRefSys model to store SRID information? has_spatialrefsys_table = True # Does the backend support the django.contrib.gis.utils.add_srs_entry() utility? supports_add_srs_entry = True # Does the backend introspect GeometryField to its subtypes? supports_geometry_field_introspection = True # Does the database have a geography type? supports_geography = False # Does the backend support storing 3D geometries? supports_3d_storage = False # Reference implementation of 3D functions is: # https://postgis.net/docs/PostGIS_Special_Functions_Index.html#PostGIS_3D_Functions supports_3d_functions = False # Does the database support SRID transform operations? supports_transform = True # Can geometry fields be null? supports_null_geometries = True # Are empty geometries supported? supports_empty_geometries = False # Can the function be applied on geodetic coordinate systems? supports_distance_geodetic = True supports_length_geodetic = True supports_perimeter_geodetic = False supports_area_geodetic = True # Is the database able to count vertices on polygons (with `num_points`)? supports_num_points_poly = True # Does the backend support expressions for specifying distance in the # dwithin lookup? supports_dwithin_distance_expr = True # Does the database have raster support? supports_raster = False # Does the database support a unique index on geometry fields? supports_geometry_field_unique_index = True # Can SchemaEditor alter geometry fields? can_alter_geometry_field = True # Do the database functions/aggregates support the tolerance parameter? supports_tolerance_parameter = False # Set of options that AsGeoJSON() doesn't support. unsupported_geojson_options = {} # Does Intersection() return None (rather than an empty GeometryCollection) # for empty results? empty_intersection_returns_none = True @property def supports_bbcontains_lookup(self): return "bbcontains" in self.connection.ops.gis_operators @property def supports_contained_lookup(self): return "contained" in self.connection.ops.gis_operators @property def supports_crosses_lookup(self): return "crosses" in self.connection.ops.gis_operators @property def supports_distances_lookups(self): return self.has_Distance_function @property def supports_dwithin_lookup(self): return "dwithin" in self.connection.ops.gis_operators @property def supports_relate_lookup(self): return "relate" in self.connection.ops.gis_operators @property def supports_isvalid_lookup(self): return self.has_IsValid_function # Is the aggregate supported by the database? @property def supports_collect_aggr(self): return models.Collect not in self.connection.ops.disallowed_aggregates @property def supports_extent_aggr(self): return models.Extent not in self.connection.ops.disallowed_aggregates @property def supports_make_line_aggr(self): return models.MakeLine not in self.connection.ops.disallowed_aggregates @property def supports_union_aggr(self): return models.Union not in self.connection.ops.disallowed_aggregates def __getattr__(self, name): m = re.match(r"has_(\w*)_function$", name) if m: func_name = m[1] return func_name not in self.connection.ops.unsupported_functions raise AttributeError
5aaa6654ba8adb59bd27a93f37e4863d7ab555932e34769fc81f71ab15304789
from django.contrib.gis import gdal class SpatialRefSysMixin: """ The SpatialRefSysMixin is a class used by the database-dependent SpatialRefSys objects to reduce redundant code. """ @property def srs(self): """ Return a GDAL SpatialReference object. """ # TODO: Is caching really necessary here? Is complexity worth it? if hasattr(self, "_srs"): # Returning a clone of the cached SpatialReference object. return self._srs.clone() else: # Attempting to cache a SpatialReference object. # Trying to get from WKT first. try: self._srs = gdal.SpatialReference(self.wkt) return self.srs except Exception as e: msg = e try: self._srs = gdal.SpatialReference(self.proj4text) return self.srs except Exception as e: msg = e raise Exception( "Could not get OSR SpatialReference from WKT: %s\nError:\n%s" % (self.wkt, msg) ) @property def ellipsoid(self): """ Return a tuple of the ellipsoid parameters: (semimajor axis, semiminor axis, and inverse flattening). """ return self.srs.ellipsoid @property def name(self): "Return the projection name." return self.srs.name @property def spheroid(self): "Return the spheroid name for this spatial reference." return self.srs["spheroid"] @property def datum(self): "Return the datum for this spatial reference." return self.srs["datum"] @property def projected(self): "Is this Spatial Reference projected?" return self.srs.projected @property def local(self): "Is this Spatial Reference local?" return self.srs.local @property def geographic(self): "Is this Spatial Reference geographic?" return self.srs.geographic @property def linear_name(self): "Return the linear units name." return self.srs.linear_name @property def linear_units(self): "Return the linear units." return self.srs.linear_units @property def angular_name(self): "Return the name of the angular units." return self.srs.angular_name @property def angular_units(self): "Return the angular units." return self.srs.angular_units @property def units(self): "Return a tuple of the units and the name." if self.projected or self.local: return (self.linear_units, self.linear_name) elif self.geographic: return (self.angular_units, self.angular_name) else: return (None, None) @classmethod def get_units(cls, wkt): """ Return a tuple of (unit_value, unit_name) for the given WKT without using any of the database fields. """ return gdal.SpatialReference(wkt).units @classmethod def get_spheroid(cls, wkt, string=True): """ Class method used by GeometryField on initialization to retrieve the `SPHEROID[..]` parameters from the given WKT. """ srs = gdal.SpatialReference(wkt) sphere_params = srs.ellipsoid sphere_name = srs["spheroid"] if not string: return sphere_name, sphere_params else: # `string` parameter used to place in format acceptable by PostGIS if len(sphere_params) == 3: radius, flattening = sphere_params[0], sphere_params[2] else: radius, flattening = sphere_params return 'SPHEROID["%s",%s,%s]' % (sphere_name, radius, flattening) def __str__(self): """ Return the string representation, a 'pretty' OGC WKT. """ return str(self.srs)
4875bd6078c37b1c6150dfc1310f39946343e662d0c0d40e27a51051774d0ceb
from django.contrib.gis.db.models import GeometryField from django.contrib.gis.db.models.functions import Distance from django.contrib.gis.measure import Area as AreaMeasure from django.contrib.gis.measure import Distance as DistanceMeasure from django.db import NotSupportedError from django.utils.functional import cached_property class BaseSpatialOperations: # Quick booleans for the type of this spatial backend, and # an attribute for the spatial database version tuple (if applicable) postgis = False spatialite = False mariadb = False mysql = False oracle = False spatial_version = None # How the geometry column should be selected. select = "%s" @cached_property def select_extent(self): return self.select # Aggregates disallowed_aggregates = () geom_func_prefix = "" # Mapping between Django function names and backend names, when names do not # match; used in spatial_function_name(). function_names = {} # Set of known unsupported functions of the backend unsupported_functions = { "Area", "AsGeoJSON", "AsGML", "AsKML", "AsSVG", "Azimuth", "BoundingCircle", "Centroid", "Difference", "Distance", "Envelope", "GeoHash", "GeometryDistance", "Intersection", "IsValid", "Length", "LineLocatePoint", "MakeValid", "MemSize", "NumGeometries", "NumPoints", "Perimeter", "PointOnSurface", "Reverse", "Scale", "SnapToGrid", "SymDifference", "Transform", "Translate", "Union", } # Constructors from_text = False # Default conversion functions for aggregates; will be overridden if implemented # for the spatial backend. def convert_extent(self, box, srid): raise NotImplementedError( "Aggregate extent not implemented for this spatial backend." ) def convert_extent3d(self, box, srid): raise NotImplementedError( "Aggregate 3D extent not implemented for this spatial backend." ) # For quoting column values, rather than columns. def geo_quote_name(self, name): return "'%s'" % name # GeometryField operations def geo_db_type(self, f): """ Return the database column type for the geometry field on the spatial backend. """ raise NotImplementedError( "subclasses of BaseSpatialOperations must provide a geo_db_type() method" ) def get_distance(self, f, value, lookup_type): """ Return the distance parameters for the given geometry field, lookup value, and lookup type. """ raise NotImplementedError( "Distance operations not available on this spatial backend." ) def get_geom_placeholder(self, f, value, compiler): """ Return the placeholder for the given geometry field with the given value. Depending on the spatial backend, the placeholder may contain a stored procedure call to the transformation function of the spatial backend. """ def transform_value(value, field): return value is not None and value.srid != field.srid if hasattr(value, "as_sql"): return ( "%s(%%s, %s)" % (self.spatial_function_name("Transform"), f.srid) if transform_value(value.output_field, f) else "%s" ) if transform_value(value, f): # Add Transform() to the SQL placeholder. return "%s(%s(%%s,%s), %s)" % ( self.spatial_function_name("Transform"), self.from_text, value.srid, f.srid, ) elif self.connection.features.has_spatialrefsys_table: return "%s(%%s,%s)" % (self.from_text, f.srid) else: # For backwards compatibility on MySQL (#27464). return "%s(%%s)" % self.from_text def check_expression_support(self, expression): if isinstance(expression, self.disallowed_aggregates): raise NotSupportedError( "%s spatial aggregation is not supported by this database backend." % expression.name ) super().check_expression_support(expression) def spatial_aggregate_name(self, agg_name): raise NotImplementedError( "Aggregate support not implemented for this spatial backend." ) def spatial_function_name(self, func_name): if func_name in self.unsupported_functions: raise NotSupportedError( "This backend doesn't support the %s function." % func_name ) return self.function_names.get(func_name, self.geom_func_prefix + func_name) # Routines for getting the OGC-compliant models. def geometry_columns(self): raise NotImplementedError( "Subclasses of BaseSpatialOperations must provide a geometry_columns() " "method." ) def spatial_ref_sys(self): raise NotImplementedError( "subclasses of BaseSpatialOperations must a provide spatial_ref_sys() " "method" ) distance_expr_for_lookup = staticmethod(Distance) def get_db_converters(self, expression): converters = super().get_db_converters(expression) if isinstance(expression.output_field, GeometryField): converters.append(self.get_geometry_converter(expression)) return converters def get_geometry_converter(self, expression): raise NotImplementedError( "Subclasses of BaseSpatialOperations must provide a " "get_geometry_converter() method." ) def get_area_att_for_field(self, field): if field.geodetic(self.connection): if self.connection.features.supports_area_geodetic: return "sq_m" raise NotImplementedError( "Area on geodetic coordinate systems not supported." ) else: units_name = field.units_name(self.connection) if units_name: return AreaMeasure.unit_attname(units_name) def get_distance_att_for_field(self, field): dist_att = None if field.geodetic(self.connection): if self.connection.features.supports_distance_geodetic: dist_att = "m" else: units = field.units_name(self.connection) if units: dist_att = DistanceMeasure.unit_attname(units) return dist_att
a9b2c6fac2c1e8467fb00ebe13fb880a5ca9e44e61cfd510f82b11dc15b1f16f
class WKTAdapter: """ An adaptor for Geometries sent to the MySQL and Oracle database backends. """ def __init__(self, geom): self.wkt = geom.wkt self.srid = geom.srid def __eq__(self, other): return ( isinstance(other, WKTAdapter) and self.wkt == other.wkt and self.srid == other.srid ) def __hash__(self): return hash((self.wkt, self.srid)) def __str__(self): return self.wkt @classmethod def _fix_polygon(cls, poly): # Hook for Oracle. return poly
02d9503376e2e244f1600f8f220d9119e74615335e043bc5ebf30d85aca65937
from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures from django.db.backends.mysql.features import DatabaseFeatures as MySQLDatabaseFeatures from django.utils.functional import cached_property class DatabaseFeatures(BaseSpatialFeatures, MySQLDatabaseFeatures): has_spatialrefsys_table = False supports_add_srs_entry = False supports_distance_geodetic = False supports_length_geodetic = False supports_area_geodetic = False supports_transform = False supports_null_geometries = False supports_num_points_poly = False unsupported_geojson_options = {"crs"} @cached_property def empty_intersection_returns_none(self): return ( not self.connection.mysql_is_mariadb and self.connection.mysql_version < (5, 7, 5) ) @cached_property def supports_geometry_field_unique_index(self): # Not supported in MySQL since https://dev.mysql.com/worklog/task/?id=11808 return self.connection.mysql_is_mariadb @cached_property def django_test_skips(self): skips = super().django_test_skips if not self.connection.mysql_is_mariadb and self.connection.mysql_version < ( 8, 0, 0, ): skips.update( { "MySQL < 8 gives different results.": { "gis_tests.geoapp.tests.GeoLookupTest.test_disjoint_lookup", }, } ) return skips
1111ed0f66a1e9eee4c1293982751fb4b831eed910a1526294b57bfe6137d30a
from MySQLdb.constants import FIELD_TYPE from django.contrib.gis.gdal import OGRGeomType from django.db.backends.mysql.introspection import DatabaseIntrospection class MySQLIntrospection(DatabaseIntrospection): # Updating the data_types_reverse dictionary with the appropriate # type for Geometry fields. data_types_reverse = DatabaseIntrospection.data_types_reverse.copy() data_types_reverse[FIELD_TYPE.GEOMETRY] = "GeometryField" def get_geometry_type(self, table_name, description): with self.connection.cursor() as cursor: # In order to get the specific geometry type of the field, # we introspect on the table definition using `DESCRIBE`. cursor.execute("DESCRIBE %s" % self.connection.ops.quote_name(table_name)) # Increment over description info until we get to the geometry # column. for column, typ, null, key, default, extra in cursor.fetchall(): if column == description.name: # Using OGRGeomType to convert from OGC name to Django field. # MySQL does not support 3D or SRIDs, so the field params # are empty. field_type = OGRGeomType(typ).django field_params = {} break return field_type, field_params def supports_spatial_index(self, cursor, table_name): # Supported with MyISAM/Aria, or InnoDB on MySQL 5.7.5+/MariaDB. storage_engine = self.get_storage_engine(cursor, table_name) if storage_engine == "InnoDB": if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (5, 7, 5) return storage_engine in ("MyISAM", "Aria")
cfbe702a19be7bd25f44b0af803abe8aff4ea8e8c10404b6dfc2534eb59f1d14
from django.db.backends.mysql.base import DatabaseWrapper as MySQLDatabaseWrapper from .features import DatabaseFeatures from .introspection import MySQLIntrospection from .operations import MySQLOperations from .schema import MySQLGISSchemaEditor class DatabaseWrapper(MySQLDatabaseWrapper): SchemaEditorClass = MySQLGISSchemaEditor # Classes instantiated in __init__(). features_class = DatabaseFeatures introspection_class = MySQLIntrospection ops_class = MySQLOperations
a4456fc76938a3c616a59b575d46763edc897e6f8660758137fc232e8dba235a
from django.contrib.gis.db import models from django.contrib.gis.db.backends.base.adapter import WKTAdapter from django.contrib.gis.db.backends.base.operations import BaseSpatialOperations from django.contrib.gis.db.backends.utils import SpatialOperator from django.contrib.gis.geos.geometry import GEOSGeometryBase from django.contrib.gis.geos.prototypes.io import wkb_r from django.contrib.gis.measure import Distance from django.db.backends.mysql.operations import DatabaseOperations from django.utils.functional import cached_property class MySQLOperations(BaseSpatialOperations, DatabaseOperations): name = "mysql" geom_func_prefix = "ST_" Adapter = WKTAdapter @cached_property def mariadb(self): return self.connection.mysql_is_mariadb @cached_property def mysql(self): return not self.connection.mysql_is_mariadb @cached_property def select(self): return self.geom_func_prefix + "AsBinary(%s)" @cached_property def from_text(self): return self.geom_func_prefix + "GeomFromText" @cached_property def gis_operators(self): operators = { "bbcontains": SpatialOperator( func="MBRContains" ), # For consistency w/PostGIS API "bboverlaps": SpatialOperator(func="MBROverlaps"), # ... "contained": SpatialOperator(func="MBRWithin"), # ... "contains": SpatialOperator(func="ST_Contains"), "crosses": SpatialOperator(func="ST_Crosses"), "disjoint": SpatialOperator(func="ST_Disjoint"), "equals": SpatialOperator(func="ST_Equals"), "exact": SpatialOperator(func="ST_Equals"), "intersects": SpatialOperator(func="ST_Intersects"), "overlaps": SpatialOperator(func="ST_Overlaps"), "same_as": SpatialOperator(func="ST_Equals"), "touches": SpatialOperator(func="ST_Touches"), "within": SpatialOperator(func="ST_Within"), } if self.connection.mysql_is_mariadb: operators["relate"] = SpatialOperator(func="ST_Relate") return operators disallowed_aggregates = ( models.Collect, models.Extent, models.Extent3D, models.MakeLine, models.Union, ) @cached_property def unsupported_functions(self): unsupported = { "AsGML", "AsKML", "AsSVG", "Azimuth", "BoundingCircle", "ForcePolygonCW", "GeometryDistance", "LineLocatePoint", "MakeValid", "MemSize", "Perimeter", "PointOnSurface", "Reverse", "Scale", "SnapToGrid", "Transform", "Translate", } if self.connection.mysql_is_mariadb: unsupported.remove("PointOnSurface") unsupported.update({"GeoHash", "IsValid"}) elif self.connection.mysql_version < (5, 7, 5): unsupported.update({"AsGeoJSON", "GeoHash", "IsValid"}) return unsupported def geo_db_type(self, f): return f.geom_type def get_distance(self, f, value, lookup_type): value = value[0] if isinstance(value, Distance): if f.geodetic(self.connection): raise ValueError( "Only numeric values of degree units are allowed on " "geodetic distance queries." ) dist_param = getattr( value, Distance.unit_attname(f.units_name(self.connection)) ) else: dist_param = value return [dist_param] def get_geometry_converter(self, expression): read = wkb_r().read srid = expression.output_field.srid if srid == -1: srid = None geom_class = expression.output_field.geom_class def converter(value, expression, connection): if value is not None: geom = GEOSGeometryBase(read(memoryview(value)), geom_class) if srid: geom.srid = srid return geom return converter
691b027a3eb35fee9382b4a7481673bd72bb73d99742565940f7ae9f3c86a2fa
import logging from django.contrib.gis.db.models import GeometryField from django.db import OperationalError from django.db.backends.mysql.schema import DatabaseSchemaEditor logger = logging.getLogger("django.contrib.gis") class MySQLGISSchemaEditor(DatabaseSchemaEditor): sql_add_spatial_index = "CREATE SPATIAL INDEX %(index)s ON %(table)s(%(column)s)" sql_drop_spatial_index = "DROP INDEX %(index)s ON %(table)s" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.geometry_sql = [] def skip_default(self, field): # Geometry fields are stored as BLOB/TEXT, for which MySQL < 8.0.13 # doesn't support defaults. if ( isinstance(field, GeometryField) and not self._supports_limited_data_type_defaults ): return True return super().skip_default(field) def quote_value(self, value): if isinstance(value, self.connection.ops.Adapter): return super().quote_value(str(value)) return super().quote_value(value) def column_sql(self, model, field, include_default=False): column_sql = super().column_sql(model, field, include_default) # MySQL doesn't support spatial indexes on NULL columns if isinstance(field, GeometryField) and field.spatial_index and not field.null: qn = self.connection.ops.quote_name db_table = model._meta.db_table self.geometry_sql.append( self.sql_add_spatial_index % { "index": qn(self._create_spatial_index_name(model, field)), "table": qn(db_table), "column": qn(field.column), } ) return column_sql def create_model(self, model): super().create_model(model) self.create_spatial_indexes() def add_field(self, model, field): super().add_field(model, field) self.create_spatial_indexes() def remove_field(self, model, field): if isinstance(field, GeometryField) and field.spatial_index: qn = self.connection.ops.quote_name sql = self.sql_drop_spatial_index % { "index": qn(self._create_spatial_index_name(model, field)), "table": qn(model._meta.db_table), } try: self.execute(sql) except OperationalError: logger.error( "Couldn't remove spatial index: %s (may be expected " "if your storage engine doesn't support them).", sql, ) super().remove_field(model, field) def _create_spatial_index_name(self, model, field): return "%s_%s_id" % (model._meta.db_table, field.column) def create_spatial_indexes(self): for sql in self.geometry_sql: try: self.execute(sql) except OperationalError: logger.error( "Cannot create SPATIAL INDEX %s. Only MyISAM and (as of " "MySQL 5.7.5) InnoDB support them.", sql, ) self.geometry_sql = []
ce49893c4c45b51aa3463eb4f194e5b12a7191868f6d5dc0dd211f5f73dc6856
from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures from django.db.backends.sqlite3.features import ( DatabaseFeatures as SQLiteDatabaseFeatures, ) from django.utils.functional import cached_property class DatabaseFeatures(BaseSpatialFeatures, SQLiteDatabaseFeatures): can_alter_geometry_field = False # Not implemented supports_3d_storage = True @cached_property def supports_area_geodetic(self): return bool(self.connection.ops.geom_lib_version()) @cached_property def django_test_skips(self): skips = super().django_test_skips skips.update( { "SpatiaLite doesn't support distance lookups with Distance objects.": { "gis_tests.geogapp.tests.GeographyTest.test02_distance_lookup", }, } ) return skips
57f8b0933d33c85d54f802aaf94971bf20c89aa402b22b5c9afc64d9c530f350
from django.contrib.gis.gdal import OGRGeomType from django.db.backends.sqlite3.introspection import ( DatabaseIntrospection, FlexibleFieldLookupDict, ) class GeoFlexibleFieldLookupDict(FlexibleFieldLookupDict): """ Subclass that includes updates the `base_data_types_reverse` dict for geometry field types. """ base_data_types_reverse = { **FlexibleFieldLookupDict.base_data_types_reverse, "point": "GeometryField", "linestring": "GeometryField", "polygon": "GeometryField", "multipoint": "GeometryField", "multilinestring": "GeometryField", "multipolygon": "GeometryField", "geometrycollection": "GeometryField", } class SpatiaLiteIntrospection(DatabaseIntrospection): data_types_reverse = GeoFlexibleFieldLookupDict() def get_geometry_type(self, table_name, description): with self.connection.cursor() as cursor: # Querying the `geometry_columns` table to get additional metadata. cursor.execute( "SELECT coord_dimension, srid, geometry_type " "FROM geometry_columns " "WHERE f_table_name=%s AND f_geometry_column=%s", (table_name, description.name), ) row = cursor.fetchone() if not row: raise Exception( 'Could not find a geometry column for "%s"."%s"' % (table_name, description.name) ) # OGRGeomType does not require GDAL and makes it easy to convert # from OGC geom type name to Django field. ogr_type = row[2] if isinstance(ogr_type, int) and ogr_type > 1000: # SpatiaLite uses SFSQL 1.2 offsets 1000 (Z), 2000 (M), and # 3000 (ZM) to indicate the presence of higher dimensional # coordinates (M not yet supported by Django). ogr_type = ogr_type % 1000 + OGRGeomType.wkb25bit field_type = OGRGeomType(ogr_type).django # Getting any GeometryField keyword arguments that are not the default. dim = row[0] srid = row[1] field_params = {} if srid != 4326: field_params["srid"] = srid if (isinstance(dim, str) and "Z" in dim) or dim == 3: field_params["dim"] = 3 return field_type, field_params def get_constraints(self, cursor, table_name): constraints = super().get_constraints(cursor, table_name) cursor.execute( "SELECT f_geometry_column " "FROM geometry_columns " "WHERE f_table_name=%s AND spatial_index_enabled=1", (table_name,), ) for row in cursor.fetchall(): constraints["%s__spatial__index" % row[0]] = { "columns": [row[0]], "primary_key": False, "unique": False, "foreign_key": None, "check": False, "index": True, } return constraints
39fe4ed40b745bdc10e4f3cb5693b42d6b61d8a0c2389b7a09fcf9fcec1a611d
""" The GeometryColumns and SpatialRefSys models for the SpatiaLite backend. """ from django.contrib.gis.db.backends.base.models import SpatialRefSysMixin from django.db import models class SpatialiteGeometryColumns(models.Model): """ The 'geometry_columns' table from SpatiaLite. """ f_table_name = models.CharField(max_length=256) f_geometry_column = models.CharField(max_length=256) coord_dimension = models.IntegerField() srid = models.IntegerField(primary_key=True) spatial_index_enabled = models.IntegerField() type = models.IntegerField(db_column="geometry_type") class Meta: app_label = "gis" db_table = "geometry_columns" managed = False def __str__(self): return "%s.%s - %dD %s field (SRID: %d)" % ( self.f_table_name, self.f_geometry_column, self.coord_dimension, self.type, self.srid, ) @classmethod def table_name_col(cls): """ Return the name of the metadata column used to store the feature table name. """ return "f_table_name" @classmethod def geom_col_name(cls): """ Return the name of the metadata column used to store the feature geometry column. """ return "f_geometry_column" class SpatialiteSpatialRefSys(models.Model, SpatialRefSysMixin): """ The 'spatial_ref_sys' table from SpatiaLite. """ srid = models.IntegerField(primary_key=True) auth_name = models.CharField(max_length=256) auth_srid = models.IntegerField() ref_sys_name = models.CharField(max_length=256) proj4text = models.CharField(max_length=2048) srtext = models.CharField(max_length=2048) class Meta: app_label = "gis" db_table = "spatial_ref_sys" managed = False @property def wkt(self): return self.srtext
c14d5f829ebc08bc8a10bb0c7ceeb360cf39a31e20fc69685844842bc10fadf3
from ctypes.util import find_library from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db.backends.sqlite3.base import DatabaseWrapper as SQLiteDatabaseWrapper from .client import SpatiaLiteClient from .features import DatabaseFeatures from .introspection import SpatiaLiteIntrospection from .operations import SpatiaLiteOperations from .schema import SpatialiteSchemaEditor class DatabaseWrapper(SQLiteDatabaseWrapper): SchemaEditorClass = SpatialiteSchemaEditor # Classes instantiated in __init__(). client_class = SpatiaLiteClient features_class = DatabaseFeatures introspection_class = SpatiaLiteIntrospection ops_class = SpatiaLiteOperations def __init__(self, *args, **kwargs): # Trying to find the location of the SpatiaLite library. # Here we are figuring out the path to the SpatiaLite library # (`libspatialite`). If it's not in the system library path (e.g., it # cannot be found by `ctypes.util.find_library`), then it may be set # manually in the settings via the `SPATIALITE_LIBRARY_PATH` setting. self.lib_spatialite_paths = [ name for name in [ getattr(settings, "SPATIALITE_LIBRARY_PATH", None), "mod_spatialite.so", "mod_spatialite", find_library("spatialite"), ] if name is not None ] super().__init__(*args, **kwargs) def get_new_connection(self, conn_params): conn = super().get_new_connection(conn_params) # Enabling extension loading on the SQLite connection. try: conn.enable_load_extension(True) except AttributeError: raise ImproperlyConfigured( "SpatiaLite requires SQLite to be configured to allow " "extension loading." ) # Load the SpatiaLite library extension on the connection. for path in self.lib_spatialite_paths: try: conn.load_extension(path) except Exception: if getattr(settings, "SPATIALITE_LIBRARY_PATH", None): raise ImproperlyConfigured( "Unable to load the SpatiaLite library extension " "as specified in your SPATIALITE_LIBRARY_PATH setting." ) continue else: break else: raise ImproperlyConfigured( "Unable to load the SpatiaLite library extension. " "Library names tried: %s" % ", ".join(self.lib_spatialite_paths) ) return conn def prepare_database(self): super().prepare_database() # Check if spatial metadata have been initialized in the database with self.cursor() as cursor: cursor.execute("PRAGMA table_info(geometry_columns);") if cursor.fetchall() == []: if self.ops.spatial_version < (5,): cursor.execute("SELECT InitSpatialMetaData(1)") else: cursor.execute("SELECT InitSpatialMetaDataFull(1)")
99ee9dbfa123b79550dbe9648900b74e4893f8300107dd98a98f73ec0704adad
""" SQL functions reference lists: https://www.gaia-gis.it/gaia-sins/spatialite-sql-4.3.0.html """ from django.contrib.gis.db import models from django.contrib.gis.db.backends.base.operations import BaseSpatialOperations from django.contrib.gis.db.backends.spatialite.adapter import SpatiaLiteAdapter from django.contrib.gis.db.backends.utils import SpatialOperator from django.contrib.gis.geos.geometry import GEOSGeometry, GEOSGeometryBase from django.contrib.gis.geos.prototypes.io import wkb_r from django.contrib.gis.measure import Distance from django.core.exceptions import ImproperlyConfigured from django.db.backends.sqlite3.operations import DatabaseOperations from django.utils.functional import cached_property from django.utils.version import get_version_tuple class SpatialiteNullCheckOperator(SpatialOperator): def as_sql(self, connection, lookup, template_params, sql_params): sql, params = super().as_sql(connection, lookup, template_params, sql_params) return "%s > 0" % sql, params class SpatiaLiteOperations(BaseSpatialOperations, DatabaseOperations): name = "spatialite" spatialite = True Adapter = SpatiaLiteAdapter collect = "Collect" extent = "Extent" makeline = "MakeLine" unionagg = "GUnion" from_text = "GeomFromText" gis_operators = { # Binary predicates "equals": SpatialiteNullCheckOperator(func="Equals"), "disjoint": SpatialiteNullCheckOperator(func="Disjoint"), "touches": SpatialiteNullCheckOperator(func="Touches"), "crosses": SpatialiteNullCheckOperator(func="Crosses"), "within": SpatialiteNullCheckOperator(func="Within"), "overlaps": SpatialiteNullCheckOperator(func="Overlaps"), "contains": SpatialiteNullCheckOperator(func="Contains"), "intersects": SpatialiteNullCheckOperator(func="Intersects"), "relate": SpatialiteNullCheckOperator(func="Relate"), "coveredby": SpatialiteNullCheckOperator(func="CoveredBy"), "covers": SpatialiteNullCheckOperator(func="Covers"), # Returns true if B's bounding box completely contains A's bounding box. "contained": SpatialOperator(func="MbrWithin"), # Returns true if A's bounding box completely contains B's bounding box. "bbcontains": SpatialOperator(func="MbrContains"), # Returns true if A's bounding box overlaps B's bounding box. "bboverlaps": SpatialOperator(func="MbrOverlaps"), # These are implemented here as synonyms for Equals "same_as": SpatialiteNullCheckOperator(func="Equals"), "exact": SpatialiteNullCheckOperator(func="Equals"), # Distance predicates "dwithin": SpatialOperator(func="PtDistWithin"), } disallowed_aggregates = (models.Extent3D,) select = "CAST (AsEWKB(%s) AS BLOB)" function_names = { "AsWKB": "St_AsBinary", "ForcePolygonCW": "ST_ForceLHR", "Length": "ST_Length", "LineLocatePoint": "ST_Line_Locate_Point", "NumPoints": "ST_NPoints", "Reverse": "ST_Reverse", "Scale": "ScaleCoords", "Translate": "ST_Translate", "Union": "ST_Union", } @cached_property def unsupported_functions(self): unsupported = {"BoundingCircle", "GeometryDistance", "MemSize"} if not self.geom_lib_version(): unsupported |= {"Azimuth", "GeoHash", "MakeValid"} return unsupported @cached_property def spatial_version(self): """Determine the version of the SpatiaLite library.""" try: version = self.spatialite_version_tuple()[1:] except Exception as exc: raise ImproperlyConfigured( 'Cannot determine the SpatiaLite version for the "%s" database. ' "Was the SpatiaLite initialization SQL loaded on this database?" % (self.connection.settings_dict["NAME"],) ) from exc if version < (4, 3, 0): raise ImproperlyConfigured("GeoDjango supports SpatiaLite 4.3.0 and above.") return version def convert_extent(self, box): """ Convert the polygon data received from SpatiaLite to min/max values. """ if box is None: return None shell = GEOSGeometry(box).shell xmin, ymin = shell[0][:2] xmax, ymax = shell[2][:2] return (xmin, ymin, xmax, ymax) def geo_db_type(self, f): """ Return None because geometry columns are added via the `AddGeometryColumn` stored procedure on SpatiaLite. """ return None def get_distance(self, f, value, lookup_type): """ Return the distance parameters for the given geometry field, lookup value, and lookup type. """ if not value: return [] value = value[0] if isinstance(value, Distance): if f.geodetic(self.connection): if lookup_type == "dwithin": raise ValueError( "Only numeric values of degree units are allowed on " "geographic DWithin queries." ) dist_param = value.m else: dist_param = getattr( value, Distance.unit_attname(f.units_name(self.connection)) ) else: dist_param = value return [dist_param] def _get_spatialite_func(self, func): """ Helper routine for calling SpatiaLite functions and returning their result. Any error occurring in this method should be handled by the caller. """ cursor = self.connection._cursor() try: cursor.execute("SELECT %s" % func) row = cursor.fetchone() finally: cursor.close() return row[0] def geos_version(self): "Return the version of GEOS used by SpatiaLite as a string." return self._get_spatialite_func("geos_version()") def proj_version(self): """Return the version of the PROJ library used by SpatiaLite.""" return self._get_spatialite_func("proj4_version()") def lwgeom_version(self): """Return the version of LWGEOM library used by SpatiaLite.""" return self._get_spatialite_func("lwgeom_version()") def rttopo_version(self): """Return the version of RTTOPO library used by SpatiaLite.""" return self._get_spatialite_func("rttopo_version()") def geom_lib_version(self): """ Return the version of the version-dependant geom library used by SpatiaLite. """ if self.spatial_version >= (5,): return self.rttopo_version() else: return self.lwgeom_version() def spatialite_version(self): "Return the SpatiaLite library version as a string." return self._get_spatialite_func("spatialite_version()") def spatialite_version_tuple(self): """ Return the SpatiaLite version as a tuple (version string, major, minor, subminor). """ version = self.spatialite_version() return (version,) + get_version_tuple(version) def spatial_aggregate_name(self, agg_name): """ Return the spatial aggregate SQL template and function for the given Aggregate instance. """ agg_name = "unionagg" if agg_name.lower() == "union" else agg_name.lower() return getattr(self, agg_name) # Routines for getting the OGC-compliant models. def geometry_columns(self): from django.contrib.gis.db.backends.spatialite.models import ( SpatialiteGeometryColumns, ) return SpatialiteGeometryColumns def spatial_ref_sys(self): from django.contrib.gis.db.backends.spatialite.models import ( SpatialiteSpatialRefSys, ) return SpatialiteSpatialRefSys def get_geometry_converter(self, expression): geom_class = expression.output_field.geom_class read = wkb_r().read def converter(value, expression, connection): return None if value is None else GEOSGeometryBase(read(value), geom_class) return converter
52aa38669deafc79667634d65ef300567e3fa79a622b7e6227b5065f3a90d077
from django.db import DatabaseError from django.db.backends.sqlite3.schema import DatabaseSchemaEditor class SpatialiteSchemaEditor(DatabaseSchemaEditor): sql_add_geometry_column = ( "SELECT AddGeometryColumn(%(table)s, %(column)s, %(srid)s, " "%(geom_type)s, %(dim)s, %(null)s)" ) sql_add_spatial_index = "SELECT CreateSpatialIndex(%(table)s, %(column)s)" sql_drop_spatial_index = "DROP TABLE idx_%(table)s_%(column)s" sql_recover_geometry_metadata = ( "SELECT RecoverGeometryColumn(%(table)s, %(column)s, %(srid)s, " "%(geom_type)s, %(dim)s)" ) sql_remove_geometry_metadata = "SELECT DiscardGeometryColumn(%(table)s, %(column)s)" sql_discard_geometry_columns = ( "DELETE FROM %(geom_table)s WHERE f_table_name = %(table)s" ) sql_update_geometry_columns = ( "UPDATE %(geom_table)s SET f_table_name = %(new_table)s " "WHERE f_table_name = %(old_table)s" ) geometry_tables = [ "geometry_columns", "geometry_columns_auth", "geometry_columns_time", "geometry_columns_statistics", ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.geometry_sql = [] def geo_quote_name(self, name): return self.connection.ops.geo_quote_name(name) def column_sql(self, model, field, include_default=False): from django.contrib.gis.db.models import GeometryField if not isinstance(field, GeometryField): return super().column_sql(model, field, include_default) # Geometry columns are created by the `AddGeometryColumn` function self.geometry_sql.append( self.sql_add_geometry_column % { "table": self.geo_quote_name(model._meta.db_table), "column": self.geo_quote_name(field.column), "srid": field.srid, "geom_type": self.geo_quote_name(field.geom_type), "dim": field.dim, "null": int(not field.null), } ) if field.spatial_index: self.geometry_sql.append( self.sql_add_spatial_index % { "table": self.quote_name(model._meta.db_table), "column": self.quote_name(field.column), } ) return None, None def remove_geometry_metadata(self, model, field): self.execute( self.sql_remove_geometry_metadata % { "table": self.quote_name(model._meta.db_table), "column": self.quote_name(field.column), } ) self.execute( self.sql_drop_spatial_index % { "table": model._meta.db_table, "column": field.column, } ) def create_model(self, model): super().create_model(model) # Create geometry columns for sql in self.geometry_sql: self.execute(sql) self.geometry_sql = [] def delete_model(self, model, **kwargs): from django.contrib.gis.db.models import GeometryField # Drop spatial metadata (dropping the table does not automatically remove them) for field in model._meta.local_fields: if isinstance(field, GeometryField): self.remove_geometry_metadata(model, field) # Make sure all geom stuff is gone for geom_table in self.geometry_tables: try: self.execute( self.sql_discard_geometry_columns % { "geom_table": geom_table, "table": self.quote_name(model._meta.db_table), } ) except DatabaseError: pass super().delete_model(model, **kwargs) def add_field(self, model, field): from django.contrib.gis.db.models import GeometryField if isinstance(field, GeometryField): # Populate self.geometry_sql self.column_sql(model, field) for sql in self.geometry_sql: self.execute(sql) self.geometry_sql = [] else: super().add_field(model, field) def remove_field(self, model, field): from django.contrib.gis.db.models import GeometryField # NOTE: If the field is a geometry field, the table is just recreated, # the parent's remove_field can't be used cause it will skip the # recreation if the field does not have a database type. Geometry fields # do not have a db type cause they are added and removed via stored # procedures. if isinstance(field, GeometryField): self._remake_table(model, delete_field=field) else: super().remove_field(model, field) def alter_db_table( self, model, old_db_table, new_db_table, disable_constraints=True ): from django.contrib.gis.db.models import GeometryField # Remove geometry-ness from temp table for field in model._meta.local_fields: if isinstance(field, GeometryField): self.execute( self.sql_remove_geometry_metadata % { "table": self.quote_name(old_db_table), "column": self.quote_name(field.column), } ) # Alter table super().alter_db_table(model, old_db_table, new_db_table, disable_constraints) # Repoint any straggler names for geom_table in self.geometry_tables: try: self.execute( self.sql_update_geometry_columns % { "geom_table": geom_table, "old_table": self.quote_name(old_db_table), "new_table": self.quote_name(new_db_table), } ) except DatabaseError: pass # Re-add geometry-ness and rename spatial index tables for field in model._meta.local_fields: if isinstance(field, GeometryField): self.execute( self.sql_recover_geometry_metadata % { "table": self.geo_quote_name(new_db_table), "column": self.geo_quote_name(field.column), "srid": field.srid, "geom_type": self.geo_quote_name(field.geom_type), "dim": field.dim, } ) if getattr(field, "spatial_index", False): self.execute( self.sql_rename_table % { "old_table": self.quote_name( "idx_%s_%s" % (old_db_table, field.column) ), "new_table": self.quote_name( "idx_%s_%s" % (new_db_table, field.column) ), } )
74d33b9aa0f24f31658104755e1a9921fb6747d5511fb01f712befcb8bee704b
from django.db.backends.sqlite3.client import DatabaseClient class SpatiaLiteClient(DatabaseClient): executable_name = "spatialite"
a93880e41046505343dc3ef118affce68a3ffc749ec531f7d97178ba29f7655d
from django.contrib.gis.db.backends.base.adapter import WKTAdapter from django.db.backends.sqlite3.base import Database class SpatiaLiteAdapter(WKTAdapter): "SQLite adapter for geometry objects." def __conform__(self, protocol): if protocol is Database.PrepareProtocol: return str(self)
8a1acd77fa8743ae03463a1a3e3f7ed5ad32dc7f0aa388166cad8de5f0c0dff8
from django.contrib.gis.gdal import OGRGeomType from django.db.backends.postgresql.introspection import DatabaseIntrospection class PostGISIntrospection(DatabaseIntrospection): postgis_oid_lookup = {} # Populated when introspection is performed. ignored_tables = DatabaseIntrospection.ignored_tables + [ "geography_columns", "geometry_columns", "raster_columns", "spatial_ref_sys", "raster_overviews", ] def get_field_type(self, data_type, description): if not self.postgis_oid_lookup: # Query PostgreSQL's pg_type table to determine the OID integers # for the PostGIS data types used in reverse lookup (the integers # may be different across versions). To prevent unnecessary # requests upon connection initialization, the `data_types_reverse` # dictionary isn't updated until introspection is performed here. with self.connection.cursor() as cursor: cursor.execute( "SELECT oid, typname " "FROM pg_type " "WHERE typname IN ('geometry', 'geography')" ) self.postgis_oid_lookup = dict(cursor.fetchall()) self.data_types_reverse.update( (oid, "GeometryField") for oid in self.postgis_oid_lookup ) return super().get_field_type(data_type, description) def get_geometry_type(self, table_name, description): """ The geometry type OID used by PostGIS does not indicate the particular type of field that a geometry column is (e.g., whether it's a PointField or a PolygonField). Thus, this routine queries the PostGIS metadata tables to determine the geometry type. """ with self.connection.cursor() as cursor: cursor.execute( """ SELECT t.coord_dimension, t.srid, t.type FROM ( SELECT * FROM geometry_columns UNION ALL SELECT * FROM geography_columns ) AS t WHERE t.f_table_name = %s AND t.f_geometry_column = %s """, (table_name, description.name), ) row = cursor.fetchone() if not row: raise Exception( 'Could not find a geometry or geography column for "%s"."%s"' % (table_name, description.name) ) dim, srid, field_type = row # OGRGeomType does not require GDAL and makes it easy to convert # from OGC geom type name to Django field. field_type = OGRGeomType(field_type).django # Getting any GeometryField keyword arguments that are not the default. field_params = {} if self.postgis_oid_lookup.get(description.type_code) == "geography": field_params["geography"] = True if srid != 4326: field_params["srid"] = srid if dim != 2: field_params["dim"] = dim return field_type, field_params
fdcc53e323d3e35db761d22ce4cf3f815e1e95af9874677e0777c6212483fb93
import struct from django.core.exceptions import ValidationError from .const import ( BANDTYPE_FLAG_HASNODATA, BANDTYPE_PIXTYPE_MASK, GDAL_TO_POSTGIS, GDAL_TO_STRUCT, POSTGIS_HEADER_STRUCTURE, POSTGIS_TO_GDAL, STRUCT_SIZE, ) def pack(structure, data): """ Pack data into hex string with little endian format. """ return struct.pack("<" + structure, *data) def unpack(structure, data): """ Unpack little endian hexlified binary string into a list. """ return struct.unpack("<" + structure, bytes.fromhex(data)) def chunk(data, index): """ Split a string into two parts at the input index. """ return data[:index], data[index:] def from_pgraster(data): """ Convert a PostGIS HEX String into a dictionary. """ if data is None: return # Split raster header from data header, data = chunk(data, 122) header = unpack(POSTGIS_HEADER_STRUCTURE, header) # Parse band data bands = [] pixeltypes = [] while data: # Get pixel type for this band pixeltype_with_flags, data = chunk(data, 2) pixeltype_with_flags = unpack("B", pixeltype_with_flags)[0] pixeltype = pixeltype_with_flags & BANDTYPE_PIXTYPE_MASK # Convert datatype from PostGIS to GDAL & get pack type and size pixeltype = POSTGIS_TO_GDAL[pixeltype] pack_type = GDAL_TO_STRUCT[pixeltype] pack_size = 2 * STRUCT_SIZE[pack_type] # Parse band nodata value. The nodata value is part of the # PGRaster string even if the nodata flag is True, so it always # has to be chunked off the data string. nodata, data = chunk(data, pack_size) nodata = unpack(pack_type, nodata)[0] # Chunk and unpack band data (pack size times nr of pixels) band, data = chunk(data, pack_size * header[10] * header[11]) band_result = {"data": bytes.fromhex(band)} # Set the nodata value if the nodata flag is set. if pixeltype_with_flags & BANDTYPE_FLAG_HASNODATA: band_result["nodata_value"] = nodata # Append band data to band list bands.append(band_result) # Store pixeltype of this band in pixeltypes array pixeltypes.append(pixeltype) # Check that all bands have the same pixeltype. # This is required by GDAL. PostGIS rasters could have different pixeltypes # for bands of the same raster. if len(set(pixeltypes)) != 1: raise ValidationError("Band pixeltypes are not all equal.") return { "srid": int(header[9]), "width": header[10], "height": header[11], "datatype": pixeltypes[0], "origin": (header[5], header[6]), "scale": (header[3], header[4]), "skew": (header[7], header[8]), "bands": bands, } def to_pgraster(rast): """ Convert a GDALRaster into PostGIS Raster format. """ # Prepare the raster header data as a tuple. The first two numbers are # the endianness and the PostGIS Raster Version, both are fixed by # PostGIS at the moment. rasterheader = ( 1, 0, len(rast.bands), rast.scale.x, rast.scale.y, rast.origin.x, rast.origin.y, rast.skew.x, rast.skew.y, rast.srs.srid, rast.width, rast.height, ) # Pack raster header. result = pack(POSTGIS_HEADER_STRUCTURE, rasterheader) for band in rast.bands: # The PostGIS raster band header has exactly two elements, a 8BUI byte # and the nodata value. # # The 8BUI stores both the PostGIS pixel data type and a nodata flag. # It is composed as the datatype with BANDTYPE_FLAG_HASNODATA (1 << 6) # for existing nodata values: # 8BUI_VALUE = PG_PIXEL_TYPE (0-11) | BANDTYPE_FLAG_HASNODATA # # For example, if the byte value is 71, then the datatype is # 71 & ~BANDTYPE_FLAG_HASNODATA = 7 (32BSI) # and the nodata value is True. structure = "B" + GDAL_TO_STRUCT[band.datatype()] # Get band pixel type in PostGIS notation pixeltype = GDAL_TO_POSTGIS[band.datatype()] # Set the nodata flag if band.nodata_value is not None: pixeltype |= BANDTYPE_FLAG_HASNODATA # Pack band header bandheader = pack(structure, (pixeltype, band.nodata_value or 0)) # Add packed header and band data to result result += bandheader + band.data(as_memoryview=True) # Convert raster to hex string before passing it to the DB. return result.hex()
9c516c869092e00cf88ecf39dccb99c5db29fd238e2258218eebb65d911e07e6
""" The GeometryColumns and SpatialRefSys models for the PostGIS backend. """ from django.contrib.gis.db.backends.base.models import SpatialRefSysMixin from django.db import models class PostGISGeometryColumns(models.Model): """ The 'geometry_columns' view from PostGIS. See the PostGIS documentation at Ch. 4.3.2. """ f_table_catalog = models.CharField(max_length=256) f_table_schema = models.CharField(max_length=256) f_table_name = models.CharField(max_length=256) f_geometry_column = models.CharField(max_length=256) coord_dimension = models.IntegerField() srid = models.IntegerField(primary_key=True) type = models.CharField(max_length=30) class Meta: app_label = "gis" db_table = "geometry_columns" managed = False def __str__(self): return "%s.%s - %dD %s field (SRID: %d)" % ( self.f_table_name, self.f_geometry_column, self.coord_dimension, self.type, self.srid, ) @classmethod def table_name_col(cls): """ Return the name of the metadata column used to store the feature table name. """ return "f_table_name" @classmethod def geom_col_name(cls): """ Return the name of the metadata column used to store the feature geometry column. """ return "f_geometry_column" class PostGISSpatialRefSys(models.Model, SpatialRefSysMixin): """ The 'spatial_ref_sys' table from PostGIS. See the PostGIS documentation at Ch. 4.2.1. """ srid = models.IntegerField(primary_key=True) auth_name = models.CharField(max_length=256) auth_srid = models.IntegerField() srtext = models.CharField(max_length=2048) proj4text = models.CharField(max_length=2048) class Meta: app_label = "gis" db_table = "spatial_ref_sys" managed = False @property def wkt(self): return self.srtext
fce0eaef58b1846a688f36ced43016b393b8444160cebb88a5090d84fc3d3be1
""" PostGIS to GDAL conversion constant definitions """ # Lookup to convert pixel type values from GDAL to PostGIS GDAL_TO_POSTGIS = [None, 4, 6, 5, 8, 7, 10, 11, None, None, None, None] # Lookup to convert pixel type values from PostGIS to GDAL POSTGIS_TO_GDAL = [1, 1, 1, 3, 1, 3, 2, 5, 4, None, 6, 7, None, None] # Struct pack structure for raster header, the raster header has the # following structure: # # Endianness, PostGIS raster version, number of bands, scale, origin, # skew, srid, width, and height. # # Scale, origin, and skew have x and y values. PostGIS currently uses # a fixed endianness (1) and there is only one version (0). POSTGIS_HEADER_STRUCTURE = "B H H d d d d d d i H H" # Lookup values to convert GDAL pixel types to struct characters. This is # used to pack and unpack the pixel values of PostGIS raster bands. GDAL_TO_STRUCT = [ None, "B", "H", "h", "L", "l", "f", "d", None, None, None, None, ] # Size of the packed value in bytes for different numerical types. # This is needed to cut chunks of band data out of PostGIS raster strings # when decomposing them into GDALRasters. # See https://docs.python.org/library/struct.html#format-characters STRUCT_SIZE = { "b": 1, # Signed char "B": 1, # Unsigned char "?": 1, # _Bool "h": 2, # Short "H": 2, # Unsigned short "i": 4, # Integer "I": 4, # Unsigned Integer "l": 4, # Long "L": 4, # Unsigned Long "f": 4, # Float "d": 8, # Double } # Pixel type specifies type of pixel values in a band. Storage flag specifies # whether the band data is stored as part of the datum or is to be found on the # server's filesystem. There are currently 11 supported pixel value types, so 4 # bits are enough to account for all. Reserve the upper 4 bits for generic # flags. See # https://trac.osgeo.org/postgis/wiki/WKTRaster/RFC/RFC1_V0SerialFormat#Pixeltypeandstorageflag BANDTYPE_PIXTYPE_MASK = 0x0F BANDTYPE_FLAG_HASNODATA = 1 << 6
022de4bf3e89a87d47a891bf5ea8df9d9397dba528eea9b06d43dabee7427132
from django.db.backends.base.base import NO_DB_ALIAS from django.db.backends.postgresql.base import ( DatabaseWrapper as Psycopg2DatabaseWrapper, ) from .features import DatabaseFeatures from .introspection import PostGISIntrospection from .operations import PostGISOperations from .schema import PostGISSchemaEditor class DatabaseWrapper(Psycopg2DatabaseWrapper): SchemaEditorClass = PostGISSchemaEditor def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if kwargs.get("alias", "") != NO_DB_ALIAS: self.features = DatabaseFeatures(self) self.ops = PostGISOperations(self) self.introspection = PostGISIntrospection(self) def prepare_database(self): super().prepare_database() # Check that postgis extension is installed. with self.cursor() as cursor: cursor.execute("CREATE EXTENSION IF NOT EXISTS postgis")
042a7cec2e5273ac53dbdc5d6e2d4396361743e8ea84d968abeb2c1e090a6cd5
import re from django.conf import settings from django.contrib.gis.db.backends.base.operations import BaseSpatialOperations from django.contrib.gis.db.backends.utils import SpatialOperator from django.contrib.gis.db.models import GeometryField, RasterField from django.contrib.gis.gdal import GDALRaster from django.contrib.gis.geos.geometry import GEOSGeometryBase from django.contrib.gis.geos.prototypes.io import wkb_r from django.contrib.gis.measure import Distance from django.core.exceptions import ImproperlyConfigured from django.db import NotSupportedError, ProgrammingError from django.db.backends.postgresql.operations import DatabaseOperations from django.db.models import Func, Value from django.utils.functional import cached_property from django.utils.version import get_version_tuple from .adapter import PostGISAdapter from .models import PostGISGeometryColumns, PostGISSpatialRefSys from .pgraster import from_pgraster # Identifier to mark raster lookups as bilateral. BILATERAL = "bilateral" class PostGISOperator(SpatialOperator): def __init__(self, geography=False, raster=False, **kwargs): # Only a subset of the operators and functions are available for the # geography type. self.geography = geography # Only a subset of the operators and functions are available for the # raster type. Lookups that don't support raster will be converted to # polygons. If the raster argument is set to BILATERAL, then the # operator cannot handle mixed geom-raster lookups. self.raster = raster super().__init__(**kwargs) def as_sql(self, connection, lookup, template_params, *args): if lookup.lhs.output_field.geography and not self.geography: raise ValueError( 'PostGIS geography does not support the "%s" ' "function/operator." % (self.func or self.op,) ) template_params = self.check_raster(lookup, template_params) return super().as_sql(connection, lookup, template_params, *args) def check_raster(self, lookup, template_params): spheroid = lookup.rhs_params and lookup.rhs_params[-1] == "spheroid" # Check which input is a raster. lhs_is_raster = lookup.lhs.field.geom_type == "RASTER" rhs_is_raster = isinstance(lookup.rhs, GDALRaster) # Look for band indices and inject them if provided. if lookup.band_lhs is not None and lhs_is_raster: if not self.func: raise ValueError( "Band indices are not allowed for this operator, it works on bbox " "only." ) template_params["lhs"] = "%s, %s" % ( template_params["lhs"], lookup.band_lhs, ) if lookup.band_rhs is not None and rhs_is_raster: if not self.func: raise ValueError( "Band indices are not allowed for this operator, it works on bbox " "only." ) template_params["rhs"] = "%s, %s" % ( template_params["rhs"], lookup.band_rhs, ) # Convert rasters to polygons if necessary. if not self.raster or spheroid: # Operators without raster support. if lhs_is_raster: template_params["lhs"] = "ST_Polygon(%s)" % template_params["lhs"] if rhs_is_raster: template_params["rhs"] = "ST_Polygon(%s)" % template_params["rhs"] elif self.raster == BILATERAL: # Operators with raster support but don't support mixed (rast-geom) # lookups. if lhs_is_raster and not rhs_is_raster: template_params["lhs"] = "ST_Polygon(%s)" % template_params["lhs"] elif rhs_is_raster and not lhs_is_raster: template_params["rhs"] = "ST_Polygon(%s)" % template_params["rhs"] return template_params class ST_Polygon(Func): function = "ST_Polygon" def __init__(self, expr): super().__init__(expr) expr = self.source_expressions[0] if isinstance(expr, Value) and not expr._output_field_or_none: self.source_expressions[0] = Value( expr.value, output_field=RasterField(srid=expr.value.srid) ) @cached_property def output_field(self): return GeometryField(srid=self.source_expressions[0].field.srid) class PostGISOperations(BaseSpatialOperations, DatabaseOperations): name = "postgis" postgis = True geom_func_prefix = "ST_" Adapter = PostGISAdapter collect = geom_func_prefix + "Collect" extent = geom_func_prefix + "Extent" extent3d = geom_func_prefix + "3DExtent" length3d = geom_func_prefix + "3DLength" makeline = geom_func_prefix + "MakeLine" perimeter3d = geom_func_prefix + "3DPerimeter" unionagg = geom_func_prefix + "Union" gis_operators = { "bbcontains": PostGISOperator(op="~", raster=True), "bboverlaps": PostGISOperator(op="&&", geography=True, raster=True), "contained": PostGISOperator(op="@", raster=True), "overlaps_left": PostGISOperator(op="&<", raster=BILATERAL), "overlaps_right": PostGISOperator(op="&>", raster=BILATERAL), "overlaps_below": PostGISOperator(op="&<|"), "overlaps_above": PostGISOperator(op="|&>"), "left": PostGISOperator(op="<<"), "right": PostGISOperator(op=">>"), "strictly_below": PostGISOperator(op="<<|"), "strictly_above": PostGISOperator(op="|>>"), "same_as": PostGISOperator(op="~=", raster=BILATERAL), "exact": PostGISOperator(op="~=", raster=BILATERAL), # alias of same_as "contains": PostGISOperator(func="ST_Contains", raster=BILATERAL), "contains_properly": PostGISOperator( func="ST_ContainsProperly", raster=BILATERAL ), "coveredby": PostGISOperator( func="ST_CoveredBy", geography=True, raster=BILATERAL ), "covers": PostGISOperator(func="ST_Covers", geography=True, raster=BILATERAL), "crosses": PostGISOperator(func="ST_Crosses"), "disjoint": PostGISOperator(func="ST_Disjoint", raster=BILATERAL), "equals": PostGISOperator(func="ST_Equals"), "intersects": PostGISOperator( func="ST_Intersects", geography=True, raster=BILATERAL ), "overlaps": PostGISOperator(func="ST_Overlaps", raster=BILATERAL), "relate": PostGISOperator(func="ST_Relate"), "touches": PostGISOperator(func="ST_Touches", raster=BILATERAL), "within": PostGISOperator(func="ST_Within", raster=BILATERAL), "dwithin": PostGISOperator(func="ST_DWithin", geography=True, raster=BILATERAL), } unsupported_functions = set() select = "%s::bytea" select_extent = None @cached_property def function_names(self): function_names = { "AsWKB": "ST_AsBinary", "AsWKT": "ST_AsText", "BoundingCircle": "ST_MinimumBoundingCircle", "NumPoints": "ST_NPoints", } if self.spatial_version < (2, 4, 0): function_names["ForcePolygonCW"] = "ST_ForceRHR" return function_names @cached_property def spatial_version(self): """Determine the version of the PostGIS library.""" # Trying to get the PostGIS version because the function # signatures will depend on the version used. The cost # here is a database query to determine the version, which # can be mitigated by setting `POSTGIS_VERSION` with a 3-tuple # comprising user-supplied values for the major, minor, and # subminor revision of PostGIS. if hasattr(settings, "POSTGIS_VERSION"): version = settings.POSTGIS_VERSION else: # Run a basic query to check the status of the connection so we're # sure we only raise the error below if the problem comes from # PostGIS and not from PostgreSQL itself (see #24862). self._get_postgis_func("version") try: vtup = self.postgis_version_tuple() except ProgrammingError: raise ImproperlyConfigured( 'Cannot determine PostGIS version for database "%s" ' 'using command "SELECT postgis_lib_version()". ' "GeoDjango requires at least PostGIS version 2.4. " "Was the database created from a spatial database " "template?" % self.connection.settings_dict["NAME"] ) version = vtup[1:] return version def convert_extent(self, box): """ Return a 4-tuple extent for the `Extent` aggregate by converting the bounding box text returned by PostGIS (`box` argument), for example: "BOX(-90.0 30.0, -85.0 40.0)". """ if box is None: return None ll, ur = box[4:-1].split(",") xmin, ymin = map(float, ll.split()) xmax, ymax = map(float, ur.split()) return (xmin, ymin, xmax, ymax) def convert_extent3d(self, box3d): """ Return a 6-tuple extent for the `Extent3D` aggregate by converting the 3d bounding-box text returned by PostGIS (`box3d` argument), for example: "BOX3D(-90.0 30.0 1, -85.0 40.0 2)". """ if box3d is None: return None ll, ur = box3d[6:-1].split(",") xmin, ymin, zmin = map(float, ll.split()) xmax, ymax, zmax = map(float, ur.split()) return (xmin, ymin, zmin, xmax, ymax, zmax) def geo_db_type(self, f): """ Return the database field type for the given spatial field. """ if f.geom_type == "RASTER": return "raster" # Type-based geometries. # TODO: Support 'M' extension. if f.dim == 3: geom_type = f.geom_type + "Z" else: geom_type = f.geom_type if f.geography: if f.srid != 4326: raise NotSupportedError( "PostGIS only supports geography columns with an SRID of 4326." ) return "geography(%s,%d)" % (geom_type, f.srid) else: return "geometry(%s,%d)" % (geom_type, f.srid) def get_distance(self, f, dist_val, lookup_type): """ Retrieve the distance parameters for the given geometry field, distance lookup value, and the distance lookup type. This is the most complex implementation of the spatial backends due to what is supported on geodetic geometry columns vs. what's available on projected geometry columns. In addition, it has to take into account the geography column type. """ # Getting the distance parameter value = dist_val[0] # Shorthand boolean flags. geodetic = f.geodetic(self.connection) geography = f.geography if isinstance(value, Distance): if geography: dist_param = value.m elif geodetic: if lookup_type == "dwithin": raise ValueError( "Only numeric values of degree units are " "allowed on geographic DWithin queries." ) dist_param = value.m else: dist_param = getattr( value, Distance.unit_attname(f.units_name(self.connection)) ) else: # Assuming the distance is in the units of the field. dist_param = value return [dist_param] def get_geom_placeholder(self, f, value, compiler): """ Provide a proper substitution value for Geometries or rasters that are not in the SRID of the field. Specifically, this routine will substitute in the ST_Transform() function call. """ transform_func = self.spatial_function_name("Transform") if hasattr(value, "as_sql"): if value.field.srid == f.srid: placeholder = "%s" else: placeholder = "%s(%%s, %s)" % (transform_func, f.srid) return placeholder # Get the srid for this object if value is None: value_srid = None else: value_srid = value.srid # Adding Transform() to the SQL placeholder if the value srid # is not equal to the field srid. if value_srid is None or value_srid == f.srid: placeholder = "%s" else: placeholder = "%s(%%s, %s)" % (transform_func, f.srid) return placeholder def _get_postgis_func(self, func): """ Helper routine for calling PostGIS functions and returning their result. """ # Close out the connection. See #9437. with self.connection.temporary_connection() as cursor: cursor.execute("SELECT %s()" % func) return cursor.fetchone()[0] def postgis_geos_version(self): "Return the version of the GEOS library used with PostGIS." return self._get_postgis_func("postgis_geos_version") def postgis_lib_version(self): "Return the version number of the PostGIS library used with PostgreSQL." return self._get_postgis_func("postgis_lib_version") def postgis_proj_version(self): """Return the version of the PROJ library used with PostGIS.""" return self._get_postgis_func("postgis_proj_version") def postgis_version(self): "Return PostGIS version number and compile-time options." return self._get_postgis_func("postgis_version") def postgis_full_version(self): "Return PostGIS version number and compile-time options." return self._get_postgis_func("postgis_full_version") def postgis_version_tuple(self): """ Return the PostGIS version as a tuple (version string, major, minor, subminor). """ version = self.postgis_lib_version() return (version,) + get_version_tuple(version) def proj_version_tuple(self): """ Return the version of PROJ used by PostGIS as a tuple of the major, minor, and subminor release numbers. """ proj_regex = re.compile(r"(\d+)\.(\d+)\.(\d+)") proj_ver_str = self.postgis_proj_version() m = proj_regex.search(proj_ver_str) if m: return tuple(map(int, m.groups())) else: raise Exception("Could not determine PROJ version from PostGIS.") def spatial_aggregate_name(self, agg_name): if agg_name == "Extent3D": return self.extent3d else: return self.geom_func_prefix + agg_name # Routines for getting the OGC-compliant models. def geometry_columns(self): return PostGISGeometryColumns def spatial_ref_sys(self): return PostGISSpatialRefSys def parse_raster(self, value): """Convert a PostGIS HEX String into a dict readable by GDALRaster.""" return from_pgraster(value) def distance_expr_for_lookup(self, lhs, rhs, **kwargs): return super().distance_expr_for_lookup( self._normalize_distance_lookup_arg(lhs), self._normalize_distance_lookup_arg(rhs), **kwargs, ) @staticmethod def _normalize_distance_lookup_arg(arg): is_raster = ( arg.field.geom_type == "RASTER" if hasattr(arg, "field") else isinstance(arg, GDALRaster) ) return ST_Polygon(arg) if is_raster else arg def get_geometry_converter(self, expression): read = wkb_r().read geom_class = expression.output_field.geom_class def converter(value, expression, connection): return None if value is None else GEOSGeometryBase(read(value), geom_class) return converter def get_area_att_for_field(self, field): return "sq_m"
800e70e1f1302aa3fe4b9d8e1180cb5d2143f0c58204a9c00170fafb248c7c4f
from django.db.backends.postgresql.schema import DatabaseSchemaEditor from django.db.models.expressions import Col, Func class PostGISSchemaEditor(DatabaseSchemaEditor): geom_index_type = "GIST" geom_index_ops_nd = "GIST_GEOMETRY_OPS_ND" rast_index_template = "ST_ConvexHull(%(expressions)s)" sql_alter_column_to_3d = ( "ALTER COLUMN %(column)s TYPE %(type)s USING ST_Force3D(%(column)s)::%(type)s" ) sql_alter_column_to_2d = ( "ALTER COLUMN %(column)s TYPE %(type)s USING ST_Force2D(%(column)s)::%(type)s" ) def geo_quote_name(self, name): return self.connection.ops.geo_quote_name(name) def _field_should_be_indexed(self, model, field): if getattr(field, "spatial_index", False): return True return super()._field_should_be_indexed(model, field) def _create_index_sql(self, model, *, fields=None, **kwargs): if fields is None or len(fields) != 1 or not hasattr(fields[0], "geodetic"): return super()._create_index_sql(model, fields=fields, **kwargs) field = fields[0] expressions = None opclasses = None if field.geom_type == "RASTER": # For raster fields, wrap index creation SQL statement with ST_ConvexHull. # Indexes on raster columns are based on the convex hull of the raster. expressions = Func(Col(None, field), template=self.rast_index_template) fields = None elif field.dim > 2 and not field.geography: # Use "nd" ops which are fast on multidimensional cases opclasses = [self.geom_index_ops_nd] name = kwargs.get("name") if not name: name = self._create_index_name(model._meta.db_table, [field.column], "_id") return super()._create_index_sql( model, fields=fields, name=name, using=" USING %s" % self.geom_index_type, opclasses=opclasses, expressions=expressions, ) def _alter_column_type_sql(self, table, old_field, new_field, new_type): """ Special case when dimension changed. """ if not hasattr(old_field, "dim") or not hasattr(new_field, "dim"): return super()._alter_column_type_sql(table, old_field, new_field, new_type) if old_field.dim == 2 and new_field.dim == 3: sql_alter = self.sql_alter_column_to_3d elif old_field.dim == 3 and new_field.dim == 2: sql_alter = self.sql_alter_column_to_2d else: sql_alter = self.sql_alter_column_type return ( ( sql_alter % { "column": self.quote_name(new_field.column), "type": new_type, }, [], ), [], )
4dde3ba39473da8b769ed55e8951e5ec4f374def344772978fd3db1ac075f122
""" This object provides quoting for GEOS geometries into PostgreSQL/PostGIS. """ from psycopg2 import Binary from psycopg2.extensions import ISQLQuote from django.contrib.gis.db.backends.postgis.pgraster import to_pgraster from django.contrib.gis.geos import GEOSGeometry class PostGISAdapter: def __init__(self, obj, geography=False): """ Initialize on the spatial object. """ self.is_geometry = isinstance(obj, (GEOSGeometry, PostGISAdapter)) # Getting the WKB (in string form, to allow easy pickling of # the adaptor) and the SRID from the geometry or raster. if self.is_geometry: self.ewkb = bytes(obj.ewkb) self._adapter = Binary(self.ewkb) else: self.ewkb = to_pgraster(obj) self.srid = obj.srid self.geography = geography def __conform__(self, proto): """Does the given protocol conform to what Psycopg2 expects?""" if proto == ISQLQuote: return self else: raise Exception( "Error implementing psycopg2 protocol. Is psycopg2 installed?" ) def __eq__(self, other): return isinstance(other, PostGISAdapter) and self.ewkb == other.ewkb def __hash__(self): return hash(self.ewkb) def __str__(self): return self.getquoted() @classmethod def _fix_polygon(cls, poly): return poly def prepare(self, conn): """ This method allows escaping the binary in the style required by the server's `standard_conforming_string` setting. """ if self.is_geometry: self._adapter.prepare(conn) def getquoted(self): """ Return a properly quoted string for use in PostgreSQL/PostGIS. """ if self.is_geometry: # Psycopg will figure out whether to use E'\\000' or '\000'. return b"%s(%s)" % ( b"ST_GeogFromWKB" if self.geography else b"ST_GeomFromEWKB", self._adapter.getquoted(), ) else: # For rasters, add explicit type cast to WKB string. return b"'%s'::raster" % self.ewkb.encode()
5e75806cbc51c534af6ca4af8e078f37b0f5a3f129e2a5a4bccc15ac6d53a586
import argparse from django.contrib.gis import gdal from django.core.management.base import BaseCommand, CommandError from django.utils.inspect import get_func_args class LayerOptionAction(argparse.Action): """ Custom argparse action for the `ogrinspect` `layer_key` keyword option which may be an integer or a string. """ def __call__(self, parser, namespace, value, option_string=None): try: setattr(namespace, self.dest, int(value)) except ValueError: setattr(namespace, self.dest, value) class ListOptionAction(argparse.Action): """ Custom argparse action for `ogrinspect` keywords that require a string list. If the string is 'True'/'true' then the option value will be a boolean instead. """ def __call__(self, parser, namespace, value, option_string=None): if value.lower() == "true": setattr(namespace, self.dest, True) else: setattr(namespace, self.dest, value.split(",")) class Command(BaseCommand): help = ( "Inspects the given OGR-compatible data source (e.g., a shapefile) and " "outputs\na GeoDjango model with the given model name. For example:\n" " ./manage.py ogrinspect zipcode.shp Zipcode" ) requires_system_checks = [] def add_arguments(self, parser): parser.add_argument("data_source", help="Path to the data source.") parser.add_argument("model_name", help="Name of the model to create.") parser.add_argument( "--blank", action=ListOptionAction, default=False, help="Use a comma separated list of OGR field names to add " "the `blank=True` option to the field definition. Set to `true` " "to apply to all applicable fields.", ) parser.add_argument( "--decimal", action=ListOptionAction, default=False, help="Use a comma separated list of OGR float fields to " "generate `DecimalField` instead of the default " "`FloatField`. Set to `true` to apply to all OGR float fields.", ) parser.add_argument( "--geom-name", default="geom", help="Specifies the model name for the Geometry Field (defaults to `geom`)", ) parser.add_argument( "--layer", dest="layer_key", action=LayerOptionAction, default=0, help="The key for specifying which layer in the OGR data " "source to use. Defaults to 0 (the first layer). May be " "an integer or a string identifier for the layer.", ) parser.add_argument( "--multi-geom", action="store_true", help="Treat the geometry in the data source as a geometry collection.", ) parser.add_argument( "--name-field", help="Specifies a field name to return for the __str__() method.", ) parser.add_argument( "--no-imports", action="store_false", dest="imports", help="Do not include `from django.contrib.gis.db import models` statement.", ) parser.add_argument( "--null", action=ListOptionAction, default=False, help="Use a comma separated list of OGR field names to add " "the `null=True` option to the field definition. Set to `true` " "to apply to all applicable fields.", ) parser.add_argument( "--srid", help="The SRID to use for the Geometry Field. If it can be " "determined, the SRID of the data source is used.", ) parser.add_argument( "--mapping", action="store_true", help="Generate mapping dictionary for use with `LayerMapping`.", ) def handle(self, *args, **options): data_source, model_name = options.pop("data_source"), options.pop("model_name") # Getting the OGR DataSource from the string parameter. try: ds = gdal.DataSource(data_source) except gdal.GDALException as msg: raise CommandError(msg) # Returning the output of ogrinspect with the given arguments # and options. from django.contrib.gis.utils.ogrinspect import _ogrinspect, mapping # Filter options to params accepted by `_ogrinspect` ogr_options = { k: v for k, v in options.items() if k in get_func_args(_ogrinspect) and v is not None } output = [s for s in _ogrinspect(ds, model_name, **ogr_options)] if options["mapping"]: # Constructing the keyword arguments for `mapping`, and # calling it on the data source. kwargs = { "geom_name": options["geom_name"], "layer_key": options["layer_key"], "multi_geom": options["multi_geom"], } mapping_dict = mapping(ds, **kwargs) # This extra legwork is so that the dictionary definition comes # out in the same order as the fields in the model definition. rev_mapping = {v: k for k, v in mapping_dict.items()} output.extend( [ "", "", "# Auto-generated `LayerMapping` dictionary for %s model" % model_name, "%s_mapping = {" % model_name.lower(), ] ) output.extend( " '%s': '%s'," % (rev_mapping[ogr_fld], ogr_fld) for ogr_fld in ds[options["layer_key"]].fields ) output.extend( [ " '%s': '%s'," % (options["geom_name"], mapping_dict[options["geom_name"]]), "}", ] ) return "\n".join(output)
f168433812021406cb16eee4c00012e08e6936cfe9d41ac2bfc189608dd2e3d9
from django.core.management.commands.inspectdb import Command as InspectDBCommand class Command(InspectDBCommand): db_module = "django.contrib.gis.db" def get_field_type(self, connection, table_name, row): field_type, field_params, field_notes = super().get_field_type( connection, table_name, row ) if field_type == "GeometryField": # Getting a more specific field type and any additional parameters # from the `get_geometry_type` routine for the spatial backend. field_type, geo_params = connection.introspection.get_geometry_type( table_name, row ) field_params.update(geo_params) return field_type, field_params, field_notes