prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
from django.core.signals import setting_changed from django.utils._os import safe_join, safe_makedirs from django.utils.deconstruct import deconstructible from django.utils.encoding import filepath_to_uri from django.utils.functional import cached_property from .base import Storage from .mixins import StorageSettingsM...
_base_url = base_url self._file_permissions_mode = file_permissions_mode self._directory_permissions_mode = directory_permissions_mode self._allow_overwrite = allow_overwrite setting_changed.connect(self._clear_cached_proper
nit__( self, location=None, base_url=None, file_permissions_mode=None, directory_permissions_mode=None, allow_overwrite=False, ): self._location = location self.
{ "filepath": "django/core/files/storage/filesystem.py", "language": "python", "file_size": 8510, "cut_index": 716, "middle_length": 229 }
lers-related deprecation warnings and helpers used in multiple places. # (In a separate file to avoid circular import problems.) import warnings from django.conf import DEPRECATED_EMAIL_SETTINGS, settings from django.utils.deprecation import ( RemovedInDjango70Warning, django_file_prefixes, ) FAIL_SILENTLY_AR...
t " "with a MAILERS alias." ) NO_DEFAULT_MAILER_WARNING = ( "Django 7.0 will not have a default mailer. Configure " "settings.MAILERS to avoid errors when sending email." ) def report_using_incompatibility( connection=None, fail_silently=
'auth_user' and 'auth_password' arguments are deprecated. Set " "'username' and 'password' OPTIONS in MAILERS instead." ) CONNECTION_ARG_WARNING = ( "The 'connection' argument is deprecated. Switch to the 'using' argumen
{ "filepath": "django/core/mail/deprecation.py", "language": "python", "file_size": 2225, "cut_index": 563, "middle_length": 229 }
ns import SuspiciousFileOperation def validate_file_name(name, allow_relative_path=False): # Remove potentially dangerous names if os.path.basename(name) in {"", ".", ".."}: raise SuspiciousFileOperation("Could not derive file name from '%s'" % name) if allow_relative_path: # Ensure that ...
me '%s' includes path elements" % name) return name class FileProxyMixin: """ A mixin class used to forward file methods to an underlying file object. The internal file object has to be called "file":: class FileProxy(FileProxyM
".." in path.parts: raise SuspiciousFileOperation( "Detected path traversal attempt in '%s'" % name ) elif name != os.path.basename(name): raise SuspiciousFileOperation("File na
{ "filepath": "django/core/files/utils.py", "language": "python", "file_size": 2601, "cut_index": 563, "middle_length": 229 }
_external_use, ) from django.utils.encoding import force_bytes, force_str, punycode from django.utils.timezone import get_current_timezone from .deprecation import ( CONNECTION_ARG_WARNING, FAIL_SILENTLY_ARG_WARNING, report_using_incompatibility, ) # RemovedInDjango70Warning. # Don't BASE64-encode UTF-8 m...
emovedInDjango70Warning. RFC5322_EMAIL_LINE_LENGTH_LIMIT = 998 # RemovedInDjango70Warning. # BadHeaderError must be ValueError (not subclass it), so that existing code # with `except BadHeaderError` will catch the ValueError that Python's modern # email
harset.Charset("utf-8") utf8_charset_qp.body_encoding = Charset.QP # Default MIME type to use on attachments (if it is not explicitly given # and cannot be guessed). DEFAULT_ATTACHMENT_MIME_TYPE = "application/octet-stream" # R
{ "filepath": "django/core/mail/message.py", "language": "python", "file_size": 25403, "cut_index": 1331, "middle_length": 229 }
Backend for test environment. """ import copy from django.core import mail from django.core.mail.backends.base import BaseEmailBackend class EmailBackend(BaseEmailBackend): """ An email backend for use during test sessions. The test connection stores email messages in a dummy outbox, rather than s...
essages): """Redirect messages to the dummy outbox""" msg_count = 0 for message in messages: message.message() # Trigger header validation. msg_copy = copy.deepcopy(message) msg_copy.sent_using =
removed from BaseEmailBackend in Django 7.0.) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not hasattr(mail, "outbox"): mail.outbox = [] def send_messages(self, m
{ "filepath": "django/core/mail/backends/locmem.py", "language": "python", "file_size": 1105, "cut_index": 515, "middle_length": 229 }
ttings from django.contrib.flatpages.models import FlatPage from django.core.exceptions import ValidationError from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ class FlatpageForm(forms.ModelForm): url = forms.RegexField( label=_("URL"), max_length...
atPage fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self._trailing_slash_required(): self.fields["url"].help_text = _( "Example: “/about/contact”.
ges={ "invalid": _( "This value must contain only letters, numbers, dots, " "underscores, dashes, slashes or tildes." ), }, ) class Meta: model = Fl
{ "filepath": "django/contrib/flatpages/forms.py", "language": "python", "file_size": 2492, "cut_index": 563, "middle_length": 229 }
.models import Site from django.db import models from django.urls import NoReverseMatch, get_script_prefix, reverse from django.utils.encoding import iri_to_uri from django.utils.translation import gettext_lazy as _ class FlatPage(models.Model): url = models.CharField(_("URL"), max_length=100, db_index=True) ...
will use “flatpages/default.html”." ), ) registration_required = models.BooleanField( _("registration required"), help_text=_( "If this is checked, only logged-in users will be able to view the page." ),
template_name = models.CharField( _("template name"), max_length=70, blank=True, help_text=_( "Example: “flatpages/contact_page.html”. If this isn’t provided, " "the system
{ "filepath": "django/contrib/flatpages/models.py", "language": "python", "file_size": 1764, "cut_index": 537, "middle_length": 229 }
gration(migrations.Migration): dependencies = [ ("sites", "0001_initial"), ] operations = [ migrations.CreateModel( name="FlatPage", fields=[ ( "id", models.AutoField( verbose_name="ID", ...
"content", models.TextField(verbose_name="content", blank=True)), ( "enable_comments", models.BooleanField(default=False, verbose_name="enable comments"), ), (
"url", models.CharField(max_length=100, verbose_name="URL", db_index=True), ), ("title", models.CharField(max_length=200, verbose_name="title")), (
{ "filepath": "django/contrib/flatpages/migrations/0001_initial.py", "language": "python", "file_size": 2408, "cut_index": 563, "middle_length": 229 }
for SyndicationFeed subclasses to produce simple GeoRSS or W3C Geo elements. """ def georss_coords(self, coords): """ In GeoRSS coordinate pairs are ordered by lat/lon and separated by a single white space. Given a tuple of coordinates, return a string GeoRSS representation....
handler.addQuickElement("geo:lat", "%f" % lat) handler.addQuickElement("geo:lon", "%f" % lon) else: handler.addQuickElement("georss:point", self.georss_coords((coords,))) def add_georss_element(self, handler, item,
t with the given coords using the given handler. Handles the differences between simple GeoRSS and the more popular W3C Geo specification. """ if w3c_geo: lon, lat = coords[:2]
{ "filepath": "django/contrib/gis/feeds.py", "language": "python", "file_size": 5994, "cut_index": 716, "middle_length": 229 }
(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.mmd...
: # pragma: no cover HAS_GEOIP2 = False else: HAS_GEOIP2 = True __all__ += ["GeoIP2", "GeoIP2Exception"] # These are the values stored in the `database_type` field of the metadata. # See https://maxmind.github.io/MaxMind-DB/#database_type fo
rror from django.core.validators import validate_ipv46_address from django.utils._os import to_path from django.utils.functional import cached_property __all__ = ["HAS_GEOIP2"] try: import geoip2.database except ImportError
{ "filepath": "django/contrib/gis/geoip2.py", "language": "python", "file_size": 8743, "cut_index": 716, "middle_length": 229 }
om django.utils.encoding import filepath_to_uri from django.utils.functional import cached_property from django.utils.timezone import now from .base import Storage from .mixins import StorageSettingsMixin __all__ = ("InMemoryStorage",) class TimingMixin: def _initialize_times(self): self.created_time = ...
d record creation, modification, and access times. """ def __init__(self, content="", name=None): super().__init__(content, name) self._content_type = type(content) self._initialize_times() def open(self, mode):
dified_time(self): self.modified_time = now() class InMemoryFileNode(ContentFile, TimingMixin): """ Helper class representing an in-memory file node. Handle unicode/bytes conversion during I/O operations an
{ "filepath": "django/core/files/storage/memory.py", "language": "python", "file_size": 9875, "cut_index": 921, "middle_length": 229 }
ail import InvalidMailer from django.core.mail.backends.base import BaseEmailBackend from django.core.mail.utils import DNS_NAME from django.utils.deprecation import RemovedInDjango70Warning, warn_about_external_use from django.utils.encoding import force_str, punycode from django.utils.functional import cached_propert...
InDjango70Warning. if "alias" not in kwargs: msg = ( "Directly creating EmailBackend instances is deprecated. " "Use mail.mailers instead." ) warn_about_external_use(msg, RemovedIn
username=None, password=None, use_tls=None, fail_silently=False, use_ssl=None, timeout=None, ssl_keyfile=None, ssl_certfile=None, **kwargs, ): # Removed
{ "filepath": "django/core/mail/backends/smtp.py", "language": "python", "file_size": 9122, "cut_index": 716, "middle_length": 229 }
b.flatpages.models import FlatPage from django.contrib.sites.shortcuts import get_current_site from django.http import Http404, HttpResponse, HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.template import loader from django.utils.safestring import mark_safe from django.views.de...
ng flatpage exists, # or a redirect is required for authentication, the 404 needs to be returned # without any CSRF checks. Therefore, we only # CSRF protect the internal implementation. def flatpage(request, url): """ Public interface to the fla
CsrfViewMiddleware.process_view # has not been called even if CsrfViewMiddleware is installed. So we need # to use @csrf_protect, in case the template needs {% csrf_token %}. # However, we can't just wrap this view; if no matchi
{ "filepath": "django/contrib/flatpages/views.py", "language": "python", "file_size": 2724, "cut_index": 563, "middle_length": 229 }
mport re from django.utils.regex_helper import _lazy_re_compile # Regular expression for recognizing HEXEWKB and WKT. A prophylactic measure # to prevent potentially malicious input from reaching the underlying C # library. Not a substitute for good web security programming practices. hex_regex = _lazy_re_compile(r"^...
TRYCOLLECTION|CIRCULARSTRING|COMPOUNDCURVE|" r"CURVEPOLYGON|MULTICURVE|MULTISURFACE|CURVE|SURFACE|POLYHEDRALSURFACE|TIN|" r"TRIANGLE)" r"[ACEGIMLONPSRUTYZ0-9,.+() -]+)$", re.I, ) json_regex = _lazy_re_compile(r"^(\s+)?\{.*}(\s+)?$", re.DOTA
IPOLYGON|GEOME
{ "filepath": "django/contrib/gis/geometry.py", "language": "python", "file_size": 787, "cut_index": 513, "middle_length": 14 }
ckend that writes messages to console instead of sending them. """ import sys import threading from django.core.mail.backends.base import BaseEmailBackend class EmailBackend(BaseEmailBackend): def __init__(self, fail_silently=False, **kwargs): self.stream = kwargs.pop("stream", sys.stdout) self....
self.stream.write("-" * 79) self.stream.write("\n") def send_messages(self, email_messages): """Write all messages to the stream in a thread-safe way.""" if not email_messages: return msg_count = 0 w
= msg.as_bytes() charset = ( msg.get_charset().get_output_charset() if msg.get_charset() else "utf-8" ) msg_data = msg_data.decode(charset) self.stream.write("%s\n" % msg_data)
{ "filepath": "django/core/mail/backends/console.py", "language": "python", "file_size": 1477, "cut_index": 524, "middle_length": 229 }
from django.conf import settings from django.contrib.flatpages.views import flatpage from django.http import Http404 from django.utils.deprecation import MiddlewareMixin class FlatpageFallbackMiddleware(MiddlewareMixin): def process_response(self, request, response): if response.status_code != 404: ...
ened. Because this # is a middleware, we can't assume the errors will be caught elsewhere. except Http404: return response except Exception: if settings.DEBUG: raise return respons
ny errors happ
{ "filepath": "django/contrib/flatpages/middleware.py", "language": "python", "file_size": 784, "cut_index": 512, "middle_length": 14 }
rt 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...
# 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 u
, 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)
{ "filepath": "django/contrib/flatpages/templatetags/flatpages.py", "language": "python", "file_size": 3552, "cut_index": 614, "middle_length": 229 }
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 tim...
are cached. """ from django.contrib.gis.gdal import SpatialReference try: # The SpatialRefSys model for the spatial backend. SpatialRefSys = connection.ops.spatial_ref_sys() except NotImplementedError: SpatialRefSys
id, 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
{ "filepath": "django/contrib/gis/db/models/fields.py", "language": "python", "file_size": 14314, "cut_index": 921, "middle_length": 229 }
etry 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: "Geom...
rveZ", 1012: "MultiSurfaceZ", 1013: "CurveZ", 1014: "SurfaceZ", 1015: "PolyhedralSurfaceZ", 1016: "TINZ", 1017: "TriangleZ", 2001: "PointM", 2002: "LineStringM", 2003: "PolygonM",
16: "TIN", 17: "Triangle", 100: "None", 101: "LinearRing", 102: "PointZ", 1008: "CircularStringZ", 1009: "CompoundCurveZ", 1010: "CurvePolygonZ", 1011: "MultiCu
{ "filepath": "django/contrib/gis/gdal/geomtype.py", "language": "python", "file_size": 4582, "cut_index": 614, "middle_length": 229 }
ion): """ 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: setat...
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. F
'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)
{ "filepath": "django/contrib/gis/management/commands/ogrinspect.py", "language": "python", "file_size": 6071, "cut_index": 716, "middle_length": 229 }
s.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(re...
s"' % (label, model) ) if field_name: try: field = klass._meta.get_field(field_name) if not isinstance(field, GeometryField): raise FieldDoesNotExist except FieldDoesNotExist:
hat 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.%
{ "filepath": "django/contrib/gis/sitemaps/views.py", "language": "python", "file_size": 2352, "cut_index": 563, "middle_length": 229 }
es import BaseSpatialFeatures from django.db.backends.mysql.features import DatabaseFeatures as MySQLDatabaseFeatures from django.utils.functional import cached_property class DatabaseFeatures(BaseSpatialFeatures, MySQLDatabaseFeatures): empty_intersection_returns_none = False has_spatialrefsys_table = False ...
False unsupported_geojson_options = {"crs"} @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
ll_geometries = False supports_num_points_poly =
{ "filepath": "django/contrib/gis/db/backends/mysql/features.py", "language": "python", "file_size": 876, "cut_index": 559, "middle_length": 52 }
trib.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 c...
efix + "AsBinary(%s)" @cached_property def from_text(self): return self.geom_func_prefix + "GeomFromText" @cached_property def collect(self): if self.connection.features.supports_collect_aggr: return self.geom_
db(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_pr
{ "filepath": "django/contrib/gis/db/backends/mysql/operations.py", "language": "python", "file_size": 5174, "cut_index": 716, "middle_length": 229 }
quoting for GEOS geometries into PostgreSQL/PostGIS. """ from django.contrib.gis.db.backends.postgis.pgraster import to_pgraster from django.contrib.gis.geos import GEOSGeometry from django.db.backends.postgresql.psycopg_any import sql class PostGISAdapter: def __init__(self, obj, geography=False): """ ...
self.geography = geography def __conform__(self, proto): """Does the given protocol conform to what Psycopg2 expects?""" from psycopg2.extensions import ISQLQuote if proto == ISQLQuote: return self else
ng of # the adaptor) and the SRID from the geometry or raster. if self.is_geometry: self.ewkb = bytes(obj.ewkb) else: self.ewkb = to_pgraster(obj) self.srid = obj.srid
{ "filepath": "django/contrib/gis/db/backends/postgis/adapter.py", "language": "python", "file_size": 1980, "cut_index": 537, "middle_length": 229 }
rsion 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 fo...
. 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 dif
d 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
{ "filepath": "django/contrib/gis/db/backends/postgis/const.py", "language": "python", "file_size": 2008, "cut_index": 537, "middle_length": 229 }
import zipfile from io import BytesIO from django.conf import settings from django.http import HttpResponse from django.template import loader # NumPy supported? try: import numpy except ImportError: numpy = False def compress_kml(kml): "Return compressed KMZ from the given KML string." kmz = BytesI...
def render_to_kmz(*args, **kwargs): """ Compress the KML content and return as KMZ (using the correct MIME type). """ return HttpResponse( compress_kml(loader.render_to_string(*args, **kwargs)), content_type="application
ml(*args, **kwargs): "Render the response as KML (using the correct MIME type)." return HttpResponse( loader.render_to_string(*args, **kwargs), content_type="application/vnd.google-earth.kml+xml", )
{ "filepath": "django/contrib/gis/shortcuts.py", "language": "python", "file_size": 1027, "cut_index": 512, "middle_length": 229 }
t DatabaseIntrospection class PostGISIntrospection(DatabaseIntrospection): postgis_oid_lookup = {} # Populated when introspection is performed. ignored_tables = [ *DatabaseIntrospection.ignored_tables, "geography_columns", "geometry_columns", "raster_columns", "spatia...
, the `data_types_reverse` # dictionary isn't updated until introspection is performed here. with self.connection.cursor() as cursor: cursor.execute( "SELECT oid, typname " "FR
etermine 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
{ "filepath": "django/contrib/gis/db/backends/postgis/introspection.py", "language": "python", "file_size": 3185, "cut_index": 614, "middle_length": 229 }
s.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 sp...
ll 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:
""" 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 a
{ "filepath": "django/contrib/gis/sitemaps/kml.py", "language": "python", "file_size": 2573, "cut_index": 563, "middle_length": 229 }
" 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 =...
nection, 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_pa
_sql(self, con
{ "filepath": "django/contrib/gis/db/backends/utils.py", "language": "python", "file_size": 789, "cut_index": 514, "middle_length": 14 }
alError 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)" def quote_value(self, value): if isinstance(va...
patial_index( cursor, model._meta.db_table ) ) sql = self._create_spatial_index_sql(model, field) if supports_spatial_index: return [sql] else:
stance(field, GeometryField) and field.spatial_index and not field.null: with self.connection.cursor() as cursor: supports_spatial_index = ( self.connection.introspection.supports_s
{ "filepath": "django/contrib/gis/db/backends/mysql/schema.py", "language": "python", "file_size": 3607, "cut_index": 614, "middle_length": 229 }
import c_void_p class CPointerBase: """ Base class for objects that have a pointer access property that controls access to the underlying C pointer. """ _ptr = None # Initially the pointer is NULL. ptr_type = c_void_p destructor = None null_ptr_exception_class = AttributeError @...
with pointers of the compatible # type or None (NULL). if not (ptr is None or isinstance(ptr, self.ptr_type)): raise TypeError("Incompatible pointer type: %s." % type(ptr)) self._ptr = ptr def __del__(self):
return self._ptr raise self.null_ptr_exception_class( "NULL %s pointer encountered." % self.__class__.__name__ ) @ptr.setter def ptr(self, ptr): # Only allow the pointer to be set
{ "filepath": "django/contrib/gis/ptr.py", "language": "python", "file_size": 1312, "cut_index": 524, "middle_length": 229 }
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.backends.postgresql.psycopg_any import is_psycopg3 from d...
aphy=False, raster=False, **kwargs): # Only a subset of the operators and functions are available for the # geography type. Lookups that don't support geography will be cast to # geometry. self.geography = geography
rt PostGISGeometryColumns, PostGISSpatialRefSys from .pgraster import from_pgraster # Identifier to mark raster lookups as bilateral. BILATERAL = "bilateral" class PostGISOperator(SpatialOperator): def __init__(self, geogr
{ "filepath": "django/contrib/gis/db/backends/postgis/operations.py", "language": "python", "file_size": 17077, "cut_index": 921, "middle_length": 229 }
nd 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_...
olumns" 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,
eld(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_c
{ "filepath": "django/contrib/gis/db/backends/postgis/models.py", "language": "python", "file_size": 2002, "cut_index": 537, "middle_length": 229 }
resql.features import ( DatabaseFeatures as PsycopgDatabaseFeatures, ) from django.db.backends.postgresql.introspection import ( DatabaseIntrospection as PsycopgDatabaseIntrospection, ) from django.db.backends.postgresql.operations import ( DatabaseOperations as PsycopgDatabaseOperations, ) from django.db.b...
extBinaryLoader, TextLoader class GeometryType: pass class GeographyType: pass class RasterType: pass class BaseTextDumper(Dumper): def dump(self, obj): # Return bytes as hex for text formatti
mport PostGISOperations from .schema import PostGISSchemaEditor if is_psycopg3: from psycopg.adapt import Dumper from psycopg.pq import Format from psycopg.types import TypeInfo from psycopg.types.string import T
{ "filepath": "django/contrib/gis/db/backends/postgis/base.py", "language": "python", "file_size": 5793, "cut_index": 716, "middle_length": 229 }
port 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 = Data...
te_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:
n.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.quo
{ "filepath": "django/contrib/gis/db/backends/mysql/introspection.py", "language": "python", "file_size": 1602, "cut_index": 537, "middle_length": 229 }
t 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 %(colu...
eturn 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,
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 r
{ "filepath": "django/contrib/gis/db/backends/postgis/schema.py", "language": "python", "file_size": 4482, "cut_index": 614, "middle_length": 229 }
g, 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 imp...
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 thi
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.
{ "filepath": "django/contrib/gis/geos/collections.py", "language": "python", "file_size": 3991, "cut_index": 614, "middle_length": 229 }
s.base.adapter import WKTAdapter from django.contrib.gis.geos import GeometryCollection, Polygon class OracleSpatialAdapter(WKTAdapter): input_size = oracledb.CLOB def __init__(self, geom): """ Oracle requires that polygon rings are in proper orientation. This affects spatial operatio...
nd 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
ance(geom, Polygon): if self._polygon_must_be_fixed(geom): geom = self._fix_polygon(geom) elif isinstance(geom, GeometryCollection): if any( isinstance(g, Polygon) a
{ "filepath": "django/contrib/gis/db/backends/oracle/adapter.py", "language": "python", "file_size": 2023, "cut_index": 563, "middle_length": 229 }
ngo.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 ...
# information. try: cursor.execute( 'SELECT "DIMINFO", "SRID" FROM "USER_SDO_GEOM_METADATA" ' 'WHERE "TABLE_NAME"=%s AND "COLUMN_NAME"=%s', (table_name.upp
db.DB_TYPE_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
{ "filepath": "django/contrib/gis/db/backends/oracle/introspection.py", "language": "python", "file_size": 1910, "cut_index": 537, "middle_length": 229 }
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.adapte...
" 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_tem
is.geos.prototypes.io import wkb_r from django.contrib.gis.measure import Distance from django.db.backends.oracle.operations import DatabaseOperations from django.utils.functional import cached_property DEFAULT_TOLERANCE = "0.05
{ "filepath": "django/contrib/gis/db/backends/oracle/operations.py", "language": "python", "file_size": 9132, "cut_index": 716, "middle_length": 229 }
ort 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 SpatialiteSchemaE...
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 th
class = DatabaseFeatures introspection_class = SpatiaLiteIntrospection ops_class = SpatiaLiteOperations def __init__(self, *args, **kwargs): # Trying to find the location of the SpatiaLite library. #
{ "filepath": "django/contrib/gis/db/backends/spatialite/base.py", "language": "python", "file_size": 3218, "cut_index": 614, "middle_length": 229 }
es 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 support...
skips.update( { "SpatiaLite doesn't support distance lookups with Distance objects.": { "gis_tests.geogapp.tests.GeographyTest.test02_distance_lookup", }, } ) retu
): skips = super().django_test_skips
{ "filepath": "django/contrib/gis/db/backends/spatialite/features.py", "language": "python", "file_size": 876, "cut_index": 559, "middle_length": 52 }
SpatialOperations 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.m...
on, lookup, template_params, sql_params) return "%s > 0" % sql, params class SpatiaLiteOperations(BaseSpatialOperations, DatabaseOperations): name = "spatialite" spatialite = True Adapter = SpatiaLiteAdapter collect = "Collect"
roperty 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(connecti
{ "filepath": "django/contrib/gis/db/backends/spatialite/operations.py", "language": "python", "file_size": 8608, "cut_index": 716, "middle_length": 229 }
lass 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...
s = 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
d 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_function
{ "filepath": "django/contrib/gis/db/backends/base/features.py", "language": "python", "file_size": 3748, "cut_index": 614, "middle_length": 229 }
e 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 ...
used in spatial_function_name(). function_names = {} # Set of known unsupported functions of the backend unsupported_functions = { "Area", "AsGeoJSON", "AsGML", "AsKML", "AsSVG", "AsWKB",
ty 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;
{ "filepath": "django/contrib/gis/db/backends/base/operations.py", "language": "python", "file_size": 7136, "cut_index": 716, "middle_length": 229 }
ometryField, LineStringField, ) from django.db.models import Aggregate, Func, 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_fi...
n, 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.
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, connectio
{ "filepath": "django/contrib/gis/db/models/aggregates.py", "language": "python", "file_size": 3100, "cut_index": 614, "middle_length": 229 }
r 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. """ ...
S.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
_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 MDSY
{ "filepath": "django/contrib/gis/db/backends/oracle/models.py", "language": "python", "file_size": 2080, "cut_index": 563, "middle_length": 229 }
chemaEditor(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', %(...
) 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)
"CREATE INDEX %(index)s ON %(table)s(%(column)s) " "INDEXTYPE IS MDSYS.SPATIAL_INDEX" ) sql_clear_geometry_table_metadata = ( "DELETE FROM USER_SDO_GEOM_METADATA WHERE TABLE_NAME = %(table)s"
{ "filepath": "django/contrib/gis/db/backends/oracle/schema.py", "language": "python", "file_size": 5430, "cut_index": 716, "middle_length": 229 }
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 RecoverGeometryC...
ble)s" ) geometry_tables = [ "geometry_columns", "geometry_columns_auth", "geometry_columns_time", "geometry_columns_statistics", ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwa
ry_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_ta
{ "filepath": "django/contrib/gis/db/backends/spatialite/schema.py", "language": "python", "file_size": 7350, "cut_index": 716, "middle_length": 229 }
lRefSysMixin: """ The SpatialRefSysMixin is a class used by the database-dependent SpatialRefSys objects to reduce redundant code. """ @cached_property def srs(self): """ Return a GDAL SpatialReference object. """ try: return gdal.SpatialReference(sel...
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 p
e raise Exception( "Could not get OSR SpatialReference.\n" f"Error for WKT '{self.wkt}': {wkt_error}\n" f"Error for PROJ.4 '{self.proj4text}': {proj4_error}" ) @property
{ "filepath": "django/contrib/gis/db/backends/base/models.py", "language": "python", "file_size": 3694, "cut_index": 614, "middle_length": 229 }
nd 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_leng...
D %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): """ Retur
.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 - %d
{ "filepath": "django/contrib/gis/db/backends/spatialite/models.py", "language": "python", "file_size": 1930, "cut_index": 537, "middle_length": 229 }
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_...
{ "Oracle doesn't support spatial operators in constraints.": { "gis_tests.gis_migrations.test_operations.OperationTests." "test_add_check_constraint", }, }
se supports_tolerance_parameter = True unsupported_geojson_options = {"bbox", "crs", "precision"} @cached_property def django_test_skips(self): skips = super().django_test_skips skips.update(
{ "filepath": "django/contrib/gis/db/backends/oracle/features.py", "language": "python", "file_size": 1021, "cut_index": 512, "middle_length": 229 }
**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: ...
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=Geometry
instance(output_field, GeometryField) ): raise TypeError( "%s function requires a geometric argument in position %d." % (self.name, pos + 1) )
{ "filepath": "django/contrib/gis/db/models/functions.py", "language": "python", "file_size": 21181, "cut_index": 1331, "middle_length": 229 }
tors 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_...
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
ad_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
{ "filepath": "django/contrib/gis/db/models/proxy.py", "language": "python", "file_size": 3174, "cut_index": 614, "middle_length": 229 }
ore.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, ...
"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_
ry value provided."), "invalid_geom": _("Invalid geometry value."), "invalid_geom_type": _("Invalid geometry type."), "transform_error": _( "An error occurred when transforming the geometry "
{ "filepath": "django/contrib/gis/forms/fields.py", "language": "python", "file_size": 4460, "cut_index": 614, "middle_length": 229 }
ypes 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: ...
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.
etry 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
{ "filepath": "django/contrib/gis/gdal/__init__.py", "language": "python", "file_size": 1810, "cut_index": 537, "middle_length": 229 }
.gdal.error import GDALException from django.contrib.gis.gdal.libgdal import GDAL_VERSION from django.contrib.gis.gdal.prototypes import ds as capi 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 d...
Shapefile", # raster "tiff": "GTiff", "tif": "GTiff", "jpeg": "JPEG", "jpg": "JPEG", } if GDAL_VERSION[:2] <= (3, 10): _alias.update( { "tiger": "TIGER",
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
{ "filepath": "django/contrib/gis/gdal/driver.py", "language": "python", "file_size": 3154, "cut_index": 614, "middle_length": 229 }
e 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 OGR...
.html#cpl-error-h CPLERR_DICT = { 1: (GDALException, "AppDefined"), 2: (GDALException, "OutOfMemory"), 3: (GDALException, "FileIO"), 4: (GDALException, "OpenFailed"), 5: (GDALException, "IllegalArg"), 6: (GDALException, "NotSupporte
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
{ "filepath": "django/contrib/gis/gdal/error.py", "language": "python", "file_size": 1575, "cut_index": 537, "middle_length": 229 }
.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 obj...
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): "Re
ting 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:
{ "filepath": "django/contrib/gis/gdal/field.py", "language": "python", "file_size": 6886, "cut_index": 716, "middle_length": 229 }
dels 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 __...
d, RasterField, ) __all__ = models_all + aggregates_all __all__ += [ "GeometryCollectionField", "GeometryField", "LineStringField", "MultiLineStringField", "MultiPointField", "MultiPolygonField", "PointField", "PolygonF
MultiPolygonField, PointField, PolygonFiel
{ "filepath": "django/contrib/gis/db/models/__init__.py", "language": "python", "file_size": 865, "cut_index": 529, "middle_length": 52 }
n 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) ...
r 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
gument. 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 fo
{ "filepath": "django/contrib/gis/db/models/lookups.py", "language": "python", "file_size": 11744, "cut_index": 921, "middle_length": 229 }
from django.contrib.gis.geometry import json_regex from django.contrib.gis.geos import GEOSException, GEOSGeometry from django.forms.widgets import Widget logger = logging.getLogger("django.contrib.gis") class BaseGeometryWidget(Widget): """ The base class for rich geometry widgets. Render a map using th...
date(attrs) def serialize(self, value): return value.wkt if value else "" def deserialize(self, value): try: return GEOSGeometry(value) except (GEOSException, GDALException, ValueError, TypeError) as err:
s def __init__(self, attrs=None): self.attrs = { key: getattr(self, key) for key in ("base_layer", "geom_type", "map_srid", "display_raw") } if attrs: self.attrs.up
{ "filepath": "django/contrib/gis/forms/widgets.py", "language": "python", "file_size": 3639, "cut_index": 614, "middle_length": 229 }
d 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.c...
xY", 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.
al.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), ("Ma
{ "filepath": "django/contrib/gis/gdal/envelope.py", "language": "python", "file_size": 7309, "cut_index": 716, "middle_length": 229 }
, 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=clrk6...
tive >>> # Equivalence works w/non-OGRGeomType objects: >>> print(gt1 == 3, gt1 == 'Polygon') 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
eometry 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-insensi
{ "filepath": "django/contrib/gis/gdal/geometries.py", "language": "python", "file_size": 28848, "cut_index": 1331, "middle_length": 229 }
ordTransform, 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()._i...
= [*self.selected_fields, self.geometry_field] def start_serialization(self): self._init_options() self._cts = {} # cache of CoordTransform's self.stream.write('{"type": "FeatureCollection", "features": [') def end_serial
("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
{ "filepath": "django/contrib/gis/serializers/geojson.py", "language": "python", "file_size": 2876, "cut_index": 563, "middle_length": 229 }
ctor 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, an SHP file. The ds_driver keyword is used internally when a ctypes pointer is passed in directly. Example: ds = DataSource('/home/f...
') 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 ret
. 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
{ "filepath": "django/contrib/gis/gdal/datasource.py", "language": "python", "file_size": 4603, "cut_index": 614, "middle_length": 229 }
ion 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 info...
" 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 ind
eature, 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. ""
{ "filepath": "django/contrib/gis/gdal/feature.py", "language": "python", "file_size": 4014, "cut_index": 614, "middle_length": 229 }
tion, 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...
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` obj
mport 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
{ "filepath": "django/contrib/gis/gdal/layer.py", "language": "python", "file_size": 8820, "cut_index": 716, "middle_length": 229 }
,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.ge...
ass 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
pe from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.error import SRSException from django.contrib.gis.gdal.prototypes import srs as capi from django.utils.encoding import force_bytes, force_str cl
{ "filepath": "django/contrib/gis/gdal/srs.py", "language": "python", "file_size": 12392, "cut_index": 921, "middle_length": 229 }
s import c_void_p, string_at from django.contrib.gis.gdal.error import GDALException, SRSException, check_err from django.contrib.gis.gdal.libgdal import lgdal # Helper routines for retrieving pointers and/or values from # arguments passed in by reference. def arg_byref(args, offset=-1): "Return the pointer argu...
, cpl=cpl) ptr = ptr_byref(cargs, offset) return ptr.value else: return result def check_string(result, func, cargs, offset=-1, str_result=False): """ Check the string output returned from the given function, and free
String checking Routines ### def check_const_string(result, func, cargs, offset=None, cpl=False): """ Similar functionality to `check_string`, but does not free the pointer. """ if offset: check_err(result
{ "filepath": "django/contrib/gis/gdal/prototypes/errcheck.py", "language": "python", "file_size": 4169, "cut_index": 614, "middle_length": 229 }
totypes.errcheck import check_envelope from django.contrib.gis.gdal.prototypes.generation import ( bool_output, const_string_output, double_output, geom_output, int_output, srs_output, string_output, void_output, ) # ### Generation routines specific to this module ### def env_func(f, a...
on prototypes ### # GeoJSON routines. from_json = geom_output(lgdal.OGR_G_CreateGeometryFromJson, [c_char_p]) to_json = string_output( lgdal.OGR_G_ExportToJson, [c_void_p], str_result=True, decoding="ascii" ) to_kml = string_output( lgdal.OGR_G_Ex
return double_output(f, [c_void_p, c_int]) def topology_func(f): f.argtypes = [c_void_p, c_void_p] f.restype = c_int f.errcheck = lambda result, func, cargs: bool(result) return f # ### OGR_G ctypes functi
{ "filepath": "django/contrib/gis/gdal/prototypes/geom.py", "language": "python", "file_size": 5923, "cut_index": 716, "middle_length": 229 }
al, std_call from django.contrib.gis.gdal.prototypes.generation import ( const_string_output, double_output, int_output, srs_output, string_output, void_output, ) # Shortcut generation for routines with known parameters. def srs_double(f): """ Create a function prototype for the OSR ro...
rs_output(std_call("OSRClone"), [c_void_p]) new_srs = srs_output(std_call("OSRNewSpatialReference"), [c_char_p]) release_srs = void_output(lgdal.OSRRelease, [c_void_p], errcheck=False) destroy_srs = void_output( std_call("OSRDestroySpatialReference"),
reate a ctypes function prototype for OSR units functions, e.g., OSRGetAngularUnits, OSRGetLinearUnits. """ return double_output(f, [c_void_p, POINTER(c_char_p)], strarg=True) # Creation & destruction. clone_srs = s
{ "filepath": "django/contrib/gis/gdal/prototypes/srs.py", "language": "python", "file_size": 3677, "cut_index": 614, "middle_length": 229 }
rom django.contrib.gis.gdal.prototypes import raster as capi class GDALRasterBase(GDALBase): """ Attributes that exist on both GDALRaster and GDALBand. """ @property def metadata(self): """ Return the metadata for this raster or band. The return value is a nested dictionar...
ist(self._ptr) if meta_list: # The number of domains is unknown, so retrieve data until there # are no more values in the ctypes array. counter = 0 domain = meta_list[counter] while domain
ontains the default domain. # The default is returned if domain name is None. domain_list = ["DEFAULT"] # Get additional metadata domains from the raster. meta_list = capi.get_ds_metadata_domain_l
{ "filepath": "django/contrib/gis/gdal/raster/base.py", "language": "python", "file_size": 2882, "cut_index": 563, "middle_length": 229 }
rom django.utils.encoding import force_bytes, force_str from django.utils.functional import cached_property class TransformPoint(list): indices = { "origin": (0, 3), "scale": (1, 5), "skew": (2, 4), } def __init__(self, raster, prop): x = raster.geotransform[self.indices[p...
n self[1] @y.setter def y(self, value): gtf = self._raster.geotransform gtf[self.indices[self._prop][1]] = value self._raster.geotransform = gtf class GDALRaster(GDALRasterBase): """ Wrap a raster GDAL Data Source
return self[0] @x.setter def x(self, value): gtf = self._raster.geotransform gtf[self.indices[self._prop][0]] = value self._raster.geotransform = gtf @property def y(self): retur
{ "filepath": "django/contrib/gis/gdal/raster/source.py", "language": "python", "file_size": 18418, "cut_index": 1331, "middle_length": 229 }
spatial 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 ...
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
b_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
{ "filepath": "django/contrib/gis/db/models/sql/conversion.py", "language": "python", "file_size": 2433, "cut_index": 563, "middle_length": 229 }
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_r...
etry_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_t
Field", "multipolygon": "GeometryField", "geometrycollection": "GeometryField", } class SpatiaLiteIntrospection(DatabaseIntrospection): data_types_reverse = GeoFlexibleFieldLookupDict() def get_geom
{ "filepath": "django/contrib/gis/db/backends/spatialite/introspection.py", "language": "python", "file_size": 3132, "cut_index": 614, "middle_length": 229 }
Dr_*, OGR_DS_*, OGR_L_*, OGR_F_*, OGR_Fld_* routines are relevant here. """ from ctypes import POINTER, c_char_p, c_double, c_int, c_long, c_uint, c_void_p from django.contrib.gis.gdal.envelope import OGREnvelope from django.contrib.gis.gdal.libgdal import lgdal from django.contrib.gis.gdal.prototypes.generation impo...
p_all = void_output(lgdal.GDALDestroyDriverManager, [], errcheck=False) get_driver = voidptr_output(lgdal.GDALGetDriver, [c_int]) get_driver_by_name = voidptr_output( lgdal.GDALGetDriverByName, [c_char_p], errcheck=False ) get_driver_count = int_output
_int) # shortcut type GDAL_OF_READONLY = 0x00 GDAL_OF_UPDATE = 0x01 GDAL_OF_ALL = 0x00 GDAL_OF_RASTER = 0x02 GDAL_OF_VECTOR = 0x04 # Driver Routines register_all = void_output(lgdal.GDALAllRegister, [], errcheck=False) cleanu
{ "filepath": "django/contrib/gis/gdal/prototypes/ds.py", "language": "python", "file_size": 4725, "cut_index": 614, "middle_length": 229 }
rt partial from django.contrib.gis.gdal.libgdal import std_call from django.contrib.gis.gdal.prototypes.generation import ( chararray_output, const_string_output, double_output, int_output, void_output, voidptr_output, ) # For more detail about c function names and definitions see # https://gd...
c_char_p, c_int, c_int, c_int, c_int, c_void_p] ) open_ds = voidptr_output(std_call("GDALOpen"), [c_char_p, c_int]) close_ds = void_output(std_call("GDALClose"), [c_void_p], errcheck=False) flush_ds = int_output(std_call("GDALFlushCache"), [c_void_p]) copy
id_output, cpl=True) const_string_output = partial(const_string_output, cpl=True) double_output = partial(double_output, cpl=True) # Raster Data Source Routines create_ds = voidptr_output( std_call("GDALCreate"), [c_void_p,
{ "filepath": "django/contrib/gis/gdal/prototypes/raster.py", "language": "python", "file_size": 5571, "cut_index": 716, "middle_length": 229 }
_int16, c_int32, c_int64, c_ubyte, c_uint16, c_uint32, c_uint64, ) # See https://gdal.org/api/raster_c_api.html#_CPPv412GDALDataType GDAL_PIXEL_TYPES = { 0: "GDT_Unknown", # Unknown or unspecified type 1: "GDT_Byte", # Eight bit unsigned integer 2: "GDT_UInt16", # Sixteen bit uns...
64", # Complex Float64 12: "GDT_UInt64", # 64 bit unsigned integer (GDAL 3.5+). 13: "GDT_Int64", # 64 bit signed integer (GDAL 3.5+). 14: "GDT_Int8", # 8 bit signed integer (GDAL 3.7+). } # A list of gdal datatypes that are integers. GDAL_
", # Thirty-two bit floating point 7: "GDT_Float64", # Sixty-four bit floating point 8: "GDT_CInt16", # Complex Int16 9: "GDT_CInt32", # Complex Int32 10: "GDT_CFloat32", # Complex Float32 11: "GDT_CFloat
{ "filepath": "django/contrib/gis/gdal/raster/const.py", "language": "python", "file_size": 3283, "cut_index": 614, "middle_length": 229 }
l 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...
*NIX library names. lib_names = [ "gdal", "GDAL", "gdal3.13.0", "gdal3.12.0", "gdal3.11.0", "gdal3.10.0", "gdal3.9.0", "gdal3.8.0", "gdal3.7.0", "gdal3.6.0", "gdal
", "gdal312", "gdal311", "gdal310", "gdal309", "gdal308", "gdal307", "gdal306", "gdal305", "gdal304", "gdal303", ] elif os.name == "posix": #
{ "filepath": "django/contrib/gis/gdal/libgdal.py", "language": "python", "file_size": 3660, "cut_index": 614, "middle_length": 229 }
er.base import GDALRasterBase from django.contrib.gis.shortcuts import numpy from django.utils.encoding import force_str from .const import ( GDAL_COLOR_TYPES, GDAL_INTEGER_TYPES, GDAL_PIXEL_TYPES, GDAL_TO_CTYPES, ) class GDALBand(GDALRasterBase): """ Wrap a GDAL raster band, needs to be obta...
True @property def description(self): """ Return the description string of the band. """ return force_str(capi.get_band_description(self._ptr)) @property def width(self): """ Width (X axis)
): """ Call the flush method on the Band's parent raster and force a refresh of the statistics attribute when requested the next time. """ self.source._flush() self._stats_refresh =
{ "filepath": "django/contrib/gis/gdal/raster/band.py", "language": "python", "file_size": 8343, "cut_index": 716, "middle_length": 229 }
ypes import POINTER, c_bool, c_char_p, c_double, c_int, c_int64, c_void_p from functools import partial from django.contrib.gis.gdal.prototypes.errcheck import ( check_arg_errcode, check_const_string, check_errcode, check_geom, check_geom_offset, check_pointer, check_srs, check_str_arg,...
a double value." func.argtypes = argtypes func.restype = c_double if errcheck: func.errcheck = partial(check_arg_errcode, cpl=cpl) if strarg: func.errcheck = check_str_arg return func def geom_output(func, argtypes, o
pes = argtypes func.restype = c_bool if errcheck: func.errcheck = errcheck return func def double_output(func, argtypes, errcheck=False, strarg=False, cpl=False): "Generate a ctypes function that returns
{ "filepath": "django/contrib/gis/gdal/prototypes/generation.py", "language": "python", "file_size": 4888, "cut_index": 614, "middle_length": 229 }
jango.db.models.query_utils import PathInfo from django.db.models.sql import AND from django.db.models.sql.where import WhereNode from django.db.models.utils import AltersData from django.utils.functional import cached_property class GenericForeignKey(FieldCacheMixin, Field): """ Provide a generic many-to-one...
True ): super().__init__(editable=False) self.ct_field = ct_field self.fk_field = fk_field self.for_concrete_model = for_concrete_model self.is_relation = True def contribute_to_class(self, cls, name, **kwar
elf as a model attribute. """ many_to_many = False many_to_one = True one_to_many = False one_to_one = False def __init__( self, ct_field="content_type", fk_field="object_id", for_concrete_model=
{ "filepath": "django/contrib/contenttypes/fields.py", "language": "python", "file_size": 32976, "cut_index": 1331, "middle_length": 229 }
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 GEOSCo...
rdinate 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 __l
inter." # TODO when dropping support for GEOS 3.13 the z argument can be # deprecated in favor of using the GEOS function GEOSCoordSeq_hasZ. if not isinstance(ptr, CS_PTR): raise TypeError("Coo
{ "filepath": "django/contrib/gis/geos/coordseq.py", "language": "python", "file_size": 8812, "cut_index": 716, "middle_length": 229 }
uctible 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._pt...
ring, MultiPoint, MultiPolygon, ) from .linestring import LinearRing, LineString from .point import Point from .polygon import P
e._GEOS_CLASSES is None: # Inner imports avoid import conflicts with GEOSGeometry. from .collections import ( GeometryCollection, MultiLineSt
{ "filepath": "django/contrib/gis/geos/geometry.py", "language": "python", "file_size": 27034, "cut_index": 1331, "middle_length": 229 }
odule 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, _WKBRe...
: "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()
ead(self, wkb)
{ "filepath": "django/contrib/gis/geos/io.py", "language": "python", "file_size": 799, "cut_index": 517, "middle_length": 14 }
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_sin...
le_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 [O
ts, _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_sing
{ "filepath": "django/contrib/gis/geos/mutable_list.py", "language": "python", "file_size": 10122, "cut_index": 921, "middle_length": 229 }
g 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). ...
(10, 10), (10, 0), (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 i
ole1 = 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),
{ "filepath": "django/contrib/gis/geos/polygon.py", "language": "python", "file_size": 6710, "cut_index": 716, "middle_length": 229 }
ule contains all of the GEOS ctypes function prototypes. Each prototype handles the interaction between the GEOS library and Python via ctypes. """ from django.contrib.gis.geos.prototypes.coordseq import ( # NOQA create_cs, cs_clone, cs_getdims, cs_getm, cs_getordinate, cs_getsize, cs_getx...
rmalize, geos_set_srid, geos_type, geos_typeid, get_dims, get_extring, get_geomn, get_intring, get_nrings, get_num_coords, get_num_geoms, ) from django.contrib.gis.geos.prototypes.misc import * # NOQA from django.co
t ( # NOQA create_collection, create_empty_polygon, create_linearring, create_linestring, create_point, create_polygon, destroy_geom, geom_clone, geos_get_srid, geos_makevalid, geos_no
{ "filepath": "django/contrib/gis/geos/prototypes/__init__.py", "language": "python", "file_size": 1489, "cut_index": 524, "middle_length": 229 }
rt ( CS_PTR, GEOM_PTR, GEOSFuncFactory, ) from django.contrib.gis.geos.prototypes.errcheck import ( GEOSException, check_predicate, last_arg_byref, ) # ## Error-checking routines specific to coordinate sequences. ## def check_cs_op(result, func, cargs): "Check the status code of a coordina...
Int(GEOSFuncFactory): "For coordinate sequence routines that return an integer." argtypes = [CS_PTR, POINTER(c_uint)] restype = c_int errcheck = staticmethod(check_cs_get) class CsOperation(GEOSFuncFactory): "For coordinate sequence
"Check the coordinate sequence retrieval." check_cs_op(result, func, cargs) # Object in by reference, return its value. return last_arg_byref(cargs) # ## Coordinate sequence prototype factory classes. ## class Cs
{ "filepath": "django/contrib/gis/geos/prototypes/coordseq.py", "language": "python", "file_size": 3478, "cut_index": 614, "middle_length": 229 }
pes.geom import c_uchar_p, geos_char_p from django.utils.encoding import force_bytes from django.utils.functional import SimpleLazyObject # ### The WKB/WKT Reader/Writer structures and pointers ### class WKTReader_st(Structure): pass class WKTWriter_st(Structure): pass class WKBReader_st(Structure): p...
ry( "GEOSWKTReader_read", argtypes=[WKT_READ_PTR, c_char_p], restype=GEOM_PTR, errcheck=check_geom, ) # WKTWriter routines wkt_writer_create = GEOSFuncFactory("GEOSWKTWriter_create", restype=WKT_WRITE_PTR) wkt_writer_destroy = GEOSFuncFacto
r_st) # WKTReader routines wkt_reader_create = GEOSFuncFactory("GEOSWKTReader_create", restype=WKT_READ_PTR) wkt_reader_destroy = GEOSFuncFactory("GEOSWKTReader_destroy", argtypes=[WKT_READ_PTR]) wkt_reader_read = GEOSFuncFacto
{ "filepath": "django/contrib/gis/geos/prototypes/io.py", "language": "python", "file_size": 11469, "cut_index": 921, "middle_length": 229 }
e GEOS ctypes prototype functions for the unary and binary predicate operations on geometries. """ from ctypes import c_byte, c_char_p, c_double from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOSFuncFactory from django.contrib.gis.geos.prototypes.errcheck import check_predicate # ## Binary & unary predicate...
closed = UnaryPredicate("GEOSisClosed") geos_isempty = UnaryPredicate("GEOSisEmpty") geos_isring = UnaryPredicate("GEOSisRing") geos_issimple = UnaryPredicate("GEOSisSimple") geos_isvalid = UnaryPredicate("GEOSisValid") # ## Binary Predicates ## geos_cont
ass BinaryPredicate(UnaryPredicate): "For GEOS binary predicate functions." argtypes = [GEOM_PTR, GEOM_PTR] # ## Unary Predicates ## geos_hasz = UnaryPredicate("GEOSHasZ") geos_hasm = UnaryPredicate("GEOSHasM") geos_is
{ "filepath": "django/contrib/gis/geos/prototypes/predicates.py", "language": "python", "file_size": 1701, "cut_index": 537, "middle_length": 229 }
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: b...
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, re
odeDecodeError: pass else:
{ "filepath": "django/contrib/gis/geos/factory.py", "language": "python", "file_size": 961, "cut_index": 582, "middle_length": 52 }
ry 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): ...
""" # 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))
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))
{ "filepath": "django/contrib/gis/geos/linestring.py", "language": "python", "file_size": 6367, "cut_index": 716, "middle_length": 229 }
e 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 ...
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
# 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(
{ "filepath": "django/contrib/gis/geos/prepared.py", "language": "python", "file_size": 1577, "cut_index": 537, "middle_length": 229 }
ort CS_PTR, GEOM_PTR, GEOSFuncFactory from django.contrib.gis.geos.prototypes.errcheck import ( check_geom, check_minus_one, check_string, ) # This is the return type used by binary output (WKB, HEX) routines. c_uchar_p = POINTER(c_ubyte) # We create a simple subclass of c_char_p here because when the re...
ss geos_char_p(c_char_p): pass # ### ctypes factory classes ### class GeomOutput(GEOSFuncFactory): "For GEOS routines that return a geometry." restype = GEOM_PTR errcheck = staticmethod(check_geom) class IntFromGeom(GEOSFuncFactory):
allocated inside GEOS. Previously, # the return type would just be omitted and the integer address would be # used -- but this allows us to be specific in the function definition and # keeps the reference so it may be free'd. cla
{ "filepath": "django/contrib/gis/geos/prototypes/geom.py", "language": "python", "file_size": 3400, "cut_index": 614, "middle_length": 229 }
types import c_byte from django.contrib.gis.geos.libgeos import GEOM_PTR, PREPGEOM_PTR, GEOSFuncFactory from django.contrib.gis.geos.prototypes.errcheck import check_predicate # Prepared geometry constructor and destructors. geos_prepare = GEOSFuncFactory("GEOSPrepare", argtypes=[GEOM_PTR], restype=PREPGEOM_PTR) prep...
) prepared_covers = PreparedPredicate("GEOSPreparedCovers") prepared_crosses = PreparedPredicate("GEOSPreparedCrosses") prepared_disjoint = PreparedPredicate("GEOSPreparedDisjoint") prepared_intersects = PreparedPredicate("GEOSPreparedIntersects") prepared
EPGEOM_PTR, GEOM_PTR] restype = c_byte errcheck = staticmethod(check_predicate) prepared_contains = PreparedPredicate("GEOSPreparedContains") prepared_contains_properly = PreparedPredicate("GEOSPreparedContainsProperly"
{ "filepath": "django/contrib/gis/geos/prototypes/prepared.py", "language": "python", "file_size": 1175, "cut_index": 518, "middle_length": 229 }
lities, 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 djang...
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('Unsupp
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:
{ "filepath": "django/contrib/gis/geos/libgeos.py", "language": "python", "file_size": 5186, "cut_index": 716, "middle_length": 229 }
ype functions. """ from ctypes import c_void_p, string_at from django.contrib.gis.geos.error import GEOSException from django.contrib.gis.geos.libgeos import GEOSFuncFactory # Getting the `free` routine used to free the memory allocated for # string pointers returned by GEOS. free = GEOSFuncFactory("GEOSFree") free....
cargs) def check_geom(result, func, cargs): "Error checking on routines that return Geometries." if not result: raise GEOSException( 'Error encountered checking Geometry returned from GEOS C function "%s".' % func.
the status code and returns the double value passed in by reference. """ # Checking the status code if result != 1: return None # Double passed in by reference, return its value. return last_arg_byref(
{ "filepath": "django/contrib/gis/geos/prototypes/errcheck.py", "language": "python", "file_size": 2802, "cut_index": 563, "middle_length": 229 }
totypes 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 i...
ds = 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,
oint, passed as individual parameters """ if x is None: coords = [] elif isinstance(x, (tuple, list)): # Here a tuple or list was passed in under the `x` parameter. coor
{ "filepath": "django/contrib/gis/geos/point.py", "language": "python", "file_size": 4790, "cut_index": 614, "middle_length": 229 }