desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Gets the Feature at the specified index.'
def __getitem__(self, index):
if isinstance(index, (int, long)): if (index < 0): raise OGRIndexError('Negative indices are not allowed on OGR Layers.') return self._make_feature(index) elif isinstance(index, slice): (start, stop, stride) = index.indices(self.num_feat) return [...
'Iterates over each Feature in the Layer.'
def __iter__(self):
capi.reset_reading(self._ptr) for i in xrange(self.num_feat): (yield Feature(capi.get_next_feature(self._ptr), self._ldefn))
'The length is the number of features.'
def __len__(self):
return self.num_feat
'The string name of the layer.'
def __str__(self):
return self.name
'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.'
def _make_feature(self, feat_id):
if self._random_read: try: return Feature(capi.get_feature(self.ptr, feat_id), self._ldefn) except OGRException: pass else: for feat in self: if (feat.fid == feat_id): return feat raise OGRIndexError(('Invalid feature id: %...
'Returns the extent (an Envelope) of this layer.'
@property def extent(self):
env = OGREnvelope() capi.get_extent(self.ptr, byref(env), 1) return Envelope(env)
'Returns the name of this layer in the Data Source.'
@property def name(self):
return capi.get_fd_name(self._ldefn)
'Returns the number of features in the Layer.'
@property def num_feat(self, force=1):
return capi.get_feature_count(self.ptr, force)
'Returns the number of fields in the Layer.'
@property def num_fields(self):
return capi.get_field_count(self._ldefn)
'Returns the geometry type (OGRGeomType) of the Layer.'
@property def geom_type(self):
return OGRGeomType(capi.get_fd_geom_type(self._ldefn))
'Returns the Spatial Reference used in this Layer.'
@property def srs(self):
try: ptr = capi.get_layer_srs(self.ptr) return SpatialReference(srs_api.clone_srs(ptr)) except SRSException: return None
'Returns a list of string names corresponding to each of the Fields available in this Layer.'
@property def fields(self):
return [capi.get_field_name(capi.get_field_defn(self._ldefn, i)) for i in xrange(self.num_fields)]
'Returns a list of the types of fields in this Layer. For example, the list [OFTInteger, OFTReal, OFTString] would be returned for an OGR layer that had an integer, a floating-point, and string fields.'
@property def field_types(self):
return [OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))] for i in xrange(self.num_fields)]
'Returns a list of the maximum field widths for the features.'
@property def field_widths(self):
return [capi.get_field_width(capi.get_field_defn(self._ldefn, i)) for i in xrange(self.num_fields)]
'Returns the field precisions for the features.'
@property def field_precisions(self):
return [capi.get_field_precision(capi.get_field_defn(self._ldefn, i)) for i in xrange(self.num_fields)]
'Returns a list containing the given field name for every Feature in the Layer.'
def get_fields(self, field_name):
if (not (field_name in self.fields)): raise OGRException(('invalid field name: %s' % field_name)) return [feat.get(field_name) for feat in self]
'Returns a list containing the OGRGeometry for every Feature in the Layer.'
def get_geoms(self, geos=False):
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]
'Returns 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 \'FastSetNextByIn...
def test_capability(self, capability):
return bool(capi.test_capability(self.ptr, capability))
'Creates 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.4 string, and/or a projection "well known" shorthand string (one of \'WGS84\', \'WGS72\', \'NAD27\', \'NAD83\').'
def __init__(self, srs_input=''):
buf = c_char_p('') srs_type = 'user' if isinstance(srs_input, basestring): if isinstance(srs_input, unicode): srs_input = srs_input.encode('ascii') try: srid = int(srs_input) srs_input = ('EPSG:%d' % srid) except ValueError: pass el...
'Destroys this spatial reference.'
def __del__(self):
if self._ptr: capi.release_srs(self._ptr)
'Returns 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(wk...
def __getitem__(self, target):
if isinstance(target, tuple): return self.attr_value(*target) else: return self.attr_value(target)
'The string representation uses \'pretty\' WKT.'
def __str__(self):
return self.pretty_wkt
'The attribute value for the given target node (e.g. \'PROJCS\'). The index keyword specifies an index of the child node to return.'
def attr_value(self, target, index=0):
if ((not isinstance(target, basestring)) or (not isinstance(index, int))): raise TypeError return capi.get_attr_value(self.ptr, target, index)
'Returns the authority name for the given string target node.'
def auth_name(self, target):
return capi.get_auth_name(self.ptr, target)
'Returns the authority code for the given string target node.'
def auth_code(self, target):
return capi.get_auth_code(self.ptr, target)
'Returns a clone of this SpatialReference object.'
def clone(self):
return SpatialReference(capi.clone_srs(self.ptr))
'Morphs this SpatialReference from ESRI\'s format to EPSG.'
def from_esri(self):
capi.morph_from_esri(self.ptr)
'This method inspects the WKT of this SpatialReference, and will add EPSG authority nodes where an EPSG identifier is applicable.'
def identify_epsg(self):
capi.identify_epsg(self.ptr)
'Morphs this SpatialReference to ESRI\'s format.'
def to_esri(self):
capi.morph_to_esri(self.ptr)
'Checks to see if the given spatial reference is valid.'
def validate(self):
capi.srs_validate(self.ptr)
'Returns the name of this Spatial Reference.'
@property def name(self):
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
'Returns the SRID of top-level authority, or None if undefined.'
@property def srid(self):
try: return int(self.attr_value('AUTHORITY', 1)) except (TypeError, ValueError): return None
'Returns the name of the linear units.'
@property def linear_name(self):
(units, name) = capi.linear_units(self.ptr, byref(c_char_p())) return name
'Returns the value of the linear units.'
@property def linear_units(self):
(units, name) = capi.linear_units(self.ptr, byref(c_char_p())) return units
'Returns the name of the angular units.'
@property def angular_name(self):
(units, name) = capi.angular_units(self.ptr, byref(c_char_p())) return name
'Returns the value of the angular units.'
@property def angular_units(self):
(units, name) = capi.angular_units(self.ptr, byref(c_char_p())) return units
'Returns a 2-tuple of the units value and the units name, and will automatically determines whether to return the linear or angular units.'
@property def units(self):
if (self.projected or self.local): return capi.linear_units(self.ptr, byref(c_char_p())) elif self.geographic: return capi.angular_units(self.ptr, byref(c_char_p())) else: return (None, None)
'Returns a tuple of the ellipsoid parameters: (semimajor axis, semiminor axis, and inverse flattening)'
@property def ellipsoid(self):
return (self.semi_major, self.semi_minor, self.inverse_flattening)
'Returns the Semi Major Axis for this Spatial Reference.'
@property def semi_major(self):
return capi.semi_major(self.ptr, byref(c_int()))
'Returns the Semi Minor Axis for this Spatial Reference.'
@property def semi_minor(self):
return capi.semi_minor(self.ptr, byref(c_int()))
'Returns the Inverse Flattening for this Spatial Reference.'
@property def inverse_flattening(self):
return capi.invflattening(self.ptr, byref(c_int()))
'Returns True if this SpatialReference is geographic (root node is GEOGCS).'
@property def geographic(self):
return bool(capi.isgeographic(self.ptr))
'Returns True if this SpatialReference is local (root node is LOCAL_CS).'
@property def local(self):
return bool(capi.islocal(self.ptr))
'Returns True if this SpatialReference is a projected coordinate system (root node is PROJCS).'
@property def projected(self):
return bool(capi.isprojected(self.ptr))
'Imports the Spatial Reference from the EPSG code (an integer).'
def import_epsg(self, epsg):
capi.from_epsg(self.ptr, epsg)
'Imports the Spatial Reference from a PROJ.4 string.'
def import_proj(self, proj):
capi.from_proj(self.ptr, proj)
'Imports the Spatial Reference from the given user input string.'
def import_user_input(self, user_input):
capi.from_user_input(self.ptr, user_input)
'Imports the Spatial Reference from OGC WKT (string)'
def import_wkt(self, wkt):
capi.from_wkt(self.ptr, byref(c_char_p(wkt)))
'Imports the Spatial Reference from an XML string.'
def import_xml(self, xml):
capi.from_xml(self.ptr, xml)
'Returns the WKT representation of this Spatial Reference.'
@property def wkt(self):
return capi.to_wkt(self.ptr, byref(c_char_p()))
'Returns the \'pretty\' representation of the WKT.'
@property def pretty_wkt(self, simplify=0):
return capi.to_pretty_wkt(self.ptr, byref(c_char_p()), simplify)
'Returns the PROJ.4 representation for this Spatial Reference.'
@property def proj(self):
return capi.to_proj(self.ptr, byref(c_char_p()))
'Alias for proj().'
@property def proj4(self):
return self.proj
'Returns the XML representation of this Spatial Reference.'
@property def xml(self, dialect=''):
return capi.to_xml(self.ptr, byref(c_char_p()), dialect)
'Initializes on a source and target SpatialReference objects.'
def __init__(self, source, target):
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
'Deletes this Coordinate Transformation object.'
def __del__(self):
if self._ptr: capi.destroy_ct(self._ptr)
'Initializes the GeoIP object, no parameters are required to use default settings. Keyword arguments may be passed in to customize the locations of the GeoIP data sets. * path: Base directory to where GeoIP data is located or the full path to where the city or country data files (*.dat) are located. Assumes that both ...
def __init__(self, path=None, cache=0, country=None, city=None):
if (cache in self.cache_options): self._cache = self.cache_options[cache] else: raise GeoIPException(('Invalid caching option: %s' % cache)) if (not path): path = GEOIP_SETTINGS.get('GEOIP_PATH', None) if (not path): raise GeoIPException('GeoIP path ...
'Helper routine for checking the query and database availability.'
def _check_query(self, query, country=False, city=False, city_or_country=False):
if (not isinstance(query, basestring)): raise TypeError(('GeoIP query must be a string, not type %s' % type(query).__name__)) if (city_or_country and (not (self._country or self._city))): raise GeoIPException('Invalid GeoIP country and city data files.')...
'Returns 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).'
def city(self, query):
self._check_query(query, city=True) if ipregex.match(query): ptr = rec_by_addr(self._city, c_char_p(query)) else: ptr = rec_by_name(self._city, c_char_p(query)) if bool(ptr): record = ptr.contents return dict(((tup[0], getattr(record, tup[0])) for tup in record._fields_))...
'Returns the country code for the given IP Address or FQDN.'
def country_code(self, query):
self._check_query(query, city_or_country=True) if self._country: if ipregex.match(query): return cntry_code_by_addr(self._country, query) else: return cntry_code_by_name(self._country, query) else: return self.city(query)['country_code']
'Returns the country name for the given IP Address or FQDN.'
def country_name(self, query):
self._check_query(query, city_or_country=True) if self._country: if ipregex.match(query): return cntry_name_by_addr(self._country, query) else: return cntry_name_by_name(self._country, query) else: return self.city(query)['country_name']
'Returns a dictonary with 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.'
def country(self, query):
return {'country_code': self.country_code(query), 'country_name': self.country_name(query)}
'Returns a tuple of the (longitude, latitude) for the given query.'
def lon_lat(self, query):
return self.coords(query)
'Returns a tuple of the (latitude, longitude) for the given query.'
def lat_lon(self, query):
return self.coords(query, ('latitude', 'longitude'))
'Returns a GEOS Point object for the given query.'
def geos(self, query):
ll = self.lon_lat(query) if ll: from django.contrib.gis.geos import Point return Point(ll, srid=4326) else: return None
'Returns information about the GeoIP country database.'
def country_info(self):
if (self._country is None): ci = ('No GeoIP Country data in "%s"' % self._country_file) else: ci = geoip_dbinfo(self._country) return ci
'Retuns information about the GeoIP city database.'
def city_info(self):
if (self._city is None): ci = ('No GeoIP City data in "%s"' % self._city_file) else: ci = geoip_dbinfo(self._city) return ci
'Returns information about all GeoIP databases in use.'
def info(self):
return ('Country:\n DCTB %s\nCity:\n DCTB %s' % (self.country_info, self.city_info))
'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.'
def __init__(self, model, data, mapping, layer=0, source_srs=None, encoding=None, transaction_mode='commit_on_success', transform=True, unique=None, using=DEFAULT_DB_ALIAS):
if isinstance(data, basestring): self.ds = DataSource(data) else: self.ds = data self.layer = self.ds[layer] self.using = using self.spatial_backend = connections[using].ops self.mapping = mapping self.model = model self.check_layer() if self.spatial_backend.mysql: ...
'This checks the `fid_range` keyword.'
def check_fid_range(self, fid_range):
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
'This checks the Layer metadata, and ensures that it is compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer.'
def check_layer(self):
self.geom_field = False self.fields = {} ogr_fields = self.layer.fields ogr_field_types = self.layer.field_types def check_ogr_fld(ogr_map_fld): try: idx = ogr_fields.index(ogr_map_fld) except ValueError: raise LayerMapError(('Given mapping OGR field ...
'Checks the compatibility of the given spatial reference object.'
def check_srs(self, source_srs):
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, basestring)): sr = SpatialReference(source_srs) else: sr = self.layer.srs if (not sr...
'Checks the `unique` keyword parameter -- may be a sequence or string.'
def check_unique(self, unique):
if isinstance(unique, (list, tuple)): for attr in unique: if (not (attr in self.mapping)): raise ValueError elif isinstance(unique, basestring): if (unique not in self.mapping): raise ValueError else: raise TypeError('Unique keyword argum...
'Given an OGR Feature, this will return a dictionary of keyword arguments for constructing the mapped model.'
def feature_kwargs(self, feat):
kwargs = {} for (field_name, ogr_name) in self.mapping.items(): model_field = self.fields[field_name] if isinstance(model_field, GeometryField): try: val = self.verify_geom(feat.geom, model_field) except OGRException: raise LayerMapError('C...
'Given the feature keyword arguments (from `feature_kwargs`) this routine will construct and return the uniqueness keyword arguments -- a subset of the feature kwargs.'
def unique_kwargs(self, kwargs):
if isinstance(self.unique, basestring): return {self.unique: kwargs[self.unique]} else: return dict(((fld, kwargs[fld]) for fld in self.unique))
'Verifies if the OGR Field contents are acceptable to the Django model field. If they are, the verified value is returned, otherwise the proper exception is raised.'
def verify_ogr_field(self, ogr_field, model_field):
if (isinstance(ogr_field, OFTString) and isinstance(model_field, (models.CharField, models.TextField))): if self.encoding: val = unicode(ogr_field.value, self.encoding) else: val = ogr_field.value if (len(val) > model_field.max_length): raise Inval...
'Given an OGR Feature, the related model and its dictionary mapping, this routine will retrieve the related model for the ForeignKey mapping.'
def verify_fk(self, feat, rel_model, rel_mapping):
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)) try: return rel_model.objects.get(**fk_kwargs) except ObjectDoesNotExist: raise MissingForeignKey(('No Foreign...
'Verifies the geometry -- will construct and return a GeometryCollection if necessary (for example if the model field is MultiPolygonField while the mapped shapefile only contains Polygons).'
def verify_geom(self, geom, model_field):
if (self.coord_dim != geom.coord_dim): geom.coord_dim = self.coord_dim if self.make_multi(geom.geom_type, model_field): multi_type = self.MULTI_TYPES[geom.geom_type.num] g = OGRGeometry(multi_type) g.add(geom) else: g = geom if self.transform: g.transform(...
'Returns the coordinate transformation object.'
def coord_transform(self):
SpatialRefSys = self.spatial_backend.spatial_ref_sys() try: target_srs = SpatialRefSys.objects.get(srid=self.geo_field.srid).srs return CoordTransform(self.source_srs, target_srs) except Exception as msg: raise LayerMapError(('Could not translate between the data so...
'Returns the GeometryField instance associated with the geographic column.'
def geometry_field(self):
opts = self.model._meta (fld, model, direct, m2m) = opts.get_field_by_name(self.geom_field) return fld
'Given the OGRGeomType for a geometry and its associated GeometryField, determine whether the geometry should be turned into a GeometryCollection.'
def make_multi(self, geom_type, model_field):
return ((geom_type.num in self.MULTI_TYPES) and (model_field.__class__.__name__ == ('Multi%s' % geom_type.django)))
'Saves 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...
def save(self, verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False):
default_range = self.check_fid_range(fid_range) if progress: if ((progress is True) or (not isinstance(progress, int))): progress_interval = 1000 else: progress_interval = progress @self.transaction_decorator def _save(feat_range=default_range, num_feat=0, num_sav...
'Return the graph as a nested list.'
def nested(self, format_callback=None):
seen = set() roots = [] for root in self.edges.get(None, ()): roots.extend(self._nested(root, seen, format_callback)) return roots
'Returns the edited object represented by this log entry'
def get_edited_object(self):
return self.content_type.get_object_for_this_type(pk=self.object_id)
'Returns the admin URL to edit the object represented by this log entry. This is relative to the Django admin index page.'
def get_admin_url(self):
if (self.content_type and self.object_id): return mark_safe((u'%s/%s/%s/' % (self.content_type.app_label, self.content_type.model, quote(self.object_id)))) return None
'Outputs a <ul> for this set of radio fields.'
def render(self):
return mark_safe((u'<ul%s>\n%s\n</ul>' % (flatatt(self.attrs), u'\n'.join([(u'<li>%s</li>' % force_unicode(w)) for w in self]))))
'Helper function for building an attribute dictionary.'
def build_attrs(self, extra_attrs=None, **kwargs):
self.attrs = self.widget.build_attrs(extra_attrs=None, **kwargs) return self.attrs
'Registers the given model(s) with the given admin class. The model(s) should be Model classes, not instances. If an admin class isn\'t given, it will use ModelAdmin (the default admin options). If keyword arguments are given -- e.g., list_display -- they\'ll be applied as options to the admin class. If a model is alre...
def register(self, model_or_iterable, admin_class=None, **options):
if (not admin_class): admin_class = ModelAdmin if (admin_class and settings.DEBUG): from django.contrib.admin.validation import validate else: validate = (lambda model, adminclass: None) if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] ...
'Unregisters the given model(s). If a model isn\'t already registered, this will raise NotRegistered.'
def unregister(self, model_or_iterable):
if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if (model not in self._registry): raise NotRegistered(('The model %s is not registered' % model.__name__)) del self._registry[model]
'Register an action to be available globally.'
def add_action(self, action, name=None):
name = (name or action.__name__) self._actions[name] = action self._global_actions[name] = action
'Disable a globally-registered action. Raises KeyError for invalid names.'
def disable_action(self, name):
del self._actions[name]
'Explicitally get a registered global action wheather it\'s enabled or not. Raises KeyError for invalid names.'
def get_action(self, name):
return self._global_actions[name]
'Get all the enabled actions as an iterable of (name, func).'
@property def actions(self):
return self._actions.iteritems()
'Returns True if the given HttpRequest has permission to view *at least one* page in the admin site.'
def has_permission(self, request):
return (request.user.is_active and request.user.is_staff)
'Check that all things needed to run the admin have been correctly installed. The default implementation checks that LogEntry, ContentType and the auth context processor are installed.'
def check_dependencies(self):
from django.contrib.admin.models import LogEntry from django.contrib.contenttypes.models import ContentType if (not LogEntry._meta.installed): raise ImproperlyConfigured("Put 'django.contrib.admin' in your INSTALLED_APPS setting in order to use the admin applicati...
'Decorator to create an admin view attached to this ``AdminSite``. This wraps the view and provides permission checking by calling ``self.has_permission``. You\'ll want to use this from within ``AdminSite.get_urls()``: class MyAdminSite(AdminSite): def get_urls(self): from django.conf.urls.defaults import patterns, url...
def admin_view(self, view, cacheable=False):
def inner(request, *args, **kwargs): if (not self.has_permission(request)): return self.login(request) return view(request, *args, **kwargs) if (not cacheable): inner = never_cache(inner) if (not getattr(view, 'csrf_exempt', False)): inner = csrf_protect(inner) ...
'Handles the "change password" task -- both form display and validation.'
def password_change(self, request):
from django.contrib.auth.views import password_change if (self.root_path is not None): url = ('%spassword_change/done/' % self.root_path) else: url = reverse('admin:password_change_done', current_app=self.name) defaults = {'current_app': self.name, 'post_change_redirect': url} if (se...
'Displays the "success" page after a password change.'
def password_change_done(self, request, extra_context=None):
from django.contrib.auth.views import password_change_done defaults = {'current_app': self.name, 'extra_context': (extra_context or {})} if (self.password_change_done_template is not None): defaults['template_name'] = self.password_change_done_template return password_change_done(request, **defa...
'Displays the i18n JavaScript that the Django admin requires. This takes into account the USE_I18N setting. If it\'s set to False, the generated JavaScript will be leaner and faster.'
def i18n_javascript(self, request):
if settings.USE_I18N: from django.views.i18n import javascript_catalog else: from django.views.i18n import null_javascript_catalog as javascript_catalog return javascript_catalog(request, packages=['django.conf', 'django.contrib.admin'])
'Logs out the user for the given HttpRequest. This should *not* assume the user is already logged in.'
@never_cache def logout(self, request, extra_context=None):
from django.contrib.auth.views import logout defaults = {'current_app': self.name, 'extra_context': (extra_context or {})} if (self.logout_template is not None): defaults['template_name'] = self.logout_template return logout(request, **defaults)