desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Attempt to link ``path``'
| def link_file(self, path, prefixed_path, source_storage, **options):
| if (prefixed_path in self.symlinked_files):
return self.log((u"Skipping '%s' (already linked earlier)" % path))
if (not self.delete_file(path, prefixed_path, source_storage, **options)):
return
source_path = source_storage.path(path)
if options['dry_run']:
self.log((u... |
'Attempt to copy ``path`` with storage'
| def copy_file(self, path, prefixed_path, source_storage, **options):
| if (prefixed_path in self.copied_files):
return self.log((u"Skipping '%s' (already copied earlier)" % path))
if (not self.delete_file(path, prefixed_path, source_storage, **options)):
return
source_path = source_storage.path(path)
if options['dry_run']:
self.log((u"Pr... |
'Checks if the path should be handled. Ignores the path if:
* the host is provided as part of the base_url
* the request\'s path isn\'t under the media path (or equal)'
| def _should_handle(self, path):
| return ((self.base_url[2] != path) and path.startswith(self.base_url[2]) and (not self.base_url[1]))
|
'Returns the relative path to the media file on disk for the given URL.'
| def file_path(self, url):
| relative_url = url[len(self.base_url[2]):]
return urllib.url2pathname(relative_url)
|
'Actually serves the request path.'
| def serve(self, request):
| return serve(request, self.file_path(request.path), insecure=True)
|
'Returns a static file storage if available in the given app.'
| def __init__(self, app, *args, **kwargs):
| self.app_module = app
if (self.app_module == 'django.contrib.admin'):
self.prefix = 'admin'
self.source_dir = 'media'
mod = import_module(self.app_module)
mod_path = os.path.dirname(mod.__file__)
location = os.path.join(mod_path, self.source_dir)
super(AppStaticStorage, self).__i... |
'Given a relative file path this ought to find an
absolute file path.
If the ``all`` parameter is ``False`` (default) only
the first found file path will be returned; if set
to ``True`` a list of all found files paths is returned.'
| def find(self, path, all=False):
| raise NotImplementedError()
|
'Given an optional list of paths to ignore, this should return
a two item iterable consisting of the relative path and storage
instance.'
| def list(self, ignore_patterns=[]):
| raise NotImplementedError()
|
'Looks for files in the extra locations
as defined in ``STATICFILES_DIRS``.'
| def find(self, path, all=False):
| matches = []
for (prefix, root) in self.locations:
matched_path = self.find_location(root, path, prefix)
if matched_path:
if (not all):
return matched_path
matches.append(matched_path)
return matches
|
'Finds a requested static file in a location, returning the found
absolute path (or ``None`` if no match).'
| def find_location(self, root, path, prefix=None):
| if prefix:
prefix = ('%s%s' % (prefix, os.sep))
if (not path.startswith(prefix)):
return None
path = path[len(prefix):]
path = safe_join(root, path)
if os.path.exists(path):
return path
|
'List all files in all locations.'
| def list(self, ignore_patterns):
| for (prefix, root) in self.locations:
storage = self.storages[root]
for path in utils.get_files(storage, ignore_patterns):
(yield (path, storage))
|
'List all files in all app storages.'
| def list(self, ignore_patterns):
| for storage in self.storages.itervalues():
if storage.exists(''):
for path in utils.get_files(storage, ignore_patterns):
(yield (path, storage))
|
'Looks for files in the app directories.'
| def find(self, path, all=False):
| matches = []
for app in self.apps:
match = self.find_in_app(app, path)
if match:
if (not all):
return match
matches.append(match)
return matches
|
'Find a requested static file in an app\'s static locations.'
| def find_in_app(self, app, path):
| storage = self.storages.get(app, None)
if storage:
if storage.prefix:
prefix = ('%s%s' % (storage.prefix, os.sep))
if (not path.startswith(prefix)):
return None
path = path[len(prefix):]
if storage.exists(path):
matched_path = stora... |
'Looks for files in the default file storage, if it\'s local.'
| def find(self, path, all=False):
| try:
self.storage.path('')
except NotImplementedError:
pass
else:
if self.storage.exists(path):
match = self.storage.path(path)
if all:
match = [match]
return match
return []
|
'List all files of the storage.'
| def list(self, ignore_patterns):
| for path in utils.get_files(self.storage, ignore_patterns):
(yield (path, self.storage))
|
'Returns a feedgenerator.DefaultFeed object, fully populated, for
this feed. Raises FeedDoesNotExist for invalid parameters.'
| def get_feed(self, url=None):
| if url:
bits = url.split('/')
else:
bits = []
try:
obj = self.get_object(bits)
except ObjectDoesNotExist:
raise FeedDoesNotExist
return super(Feed, self).get_feed(obj, self.request)
|
'Returns an extra keyword arguments dictionary that is used when
initializing the feed generator.'
| def feed_extra_kwargs(self, obj):
| return {}
|
'Returns an extra keyword arguments dictionary that is used with
the `add_item` call of the feed generator.'
| def item_extra_kwargs(self, item):
| return {}
|
'Returns a feedgenerator.DefaultFeed object, fully populated, for
this feed. Raises FeedDoesNotExist for invalid parameters.'
| def get_feed(self, obj, request):
| current_site = get_current_site(request)
link = self.__get_dynamic_attr('link', obj)
link = add_domain(current_site.domain, link, request.is_secure())
feed = self.feed_type(title=self.__get_dynamic_attr('title', obj), subtitle=self.__get_dynamic_attr('subtitle', obj), link=link, description=self.__get_d... |
'Class method to parse get_comment_list/count/form and return a Node.'
| def handle_token(cls, parser, token):
| tokens = token.contents.split()
if (tokens[1] != 'for'):
raise template.TemplateSyntaxError(("Second argument in %r tag must be 'for'" % tokens[0]))
if (len(tokens) == 5):
if (tokens[3] != 'as'):
raise template.TemplateSyntaxError(("Third argument in ... |
'Subclasses should override this.'
| def get_context_value_from_queryset(self, context, qs):
| raise NotImplementedError
|
'Class method to parse render_comment_form and return a Node.'
| def handle_token(cls, parser, token):
| tokens = token.contents.split()
if (tokens[1] != 'for'):
raise template.TemplateSyntaxError(("Second argument in %r tag must be 'for'" % tokens[0]))
if (len(tokens) == 3):
return cls(object_expr=parser.compile_filter(tokens[2]))
elif (len(tokens) == 4):
retur... |
'Class method to parse render_comment_list and return a Node.'
| def handle_token(cls, parser, token):
| tokens = token.contents.split()
if (tokens[1] != 'for'):
raise template.TemplateSyntaxError(("Second argument in %r tag must be 'for'" % tokens[0]))
if (len(tokens) == 3):
return cls(object_expr=parser.compile_filter(tokens[2]))
elif (len(tokens) == 4):
retur... |
'Get a URL suitable for redirecting to the content object.'
| def get_content_object_url(self):
| return urlresolvers.reverse('comments-url-redirect', args=(self.content_type_id, self.object_pk))
|
'Get a dictionary that pulls together information about the poster
safely for both authenticated and non-authenticated comments.
This dict will have ``name``, ``email``, and ``url`` fields.'
| def _get_userinfo(self):
| if (not hasattr(self, '_userinfo')):
self._userinfo = {'name': self.user_name, 'email': self.user_email, 'url': self.user_url}
if self.user_id:
u = self.user
if u.email:
self._userinfo['email'] = u.email
if u.get_full_name():
self._... |
'Return this comment as plain text. Useful for emails.'
| def get_as_text(self):
| d = {'user': (self.user or self.name), 'date': self.submit_date, 'comment': self.comment, 'domain': self.site.domain, 'url': self.get_absolute_url()}
return (_('Posted by %(user)s at %(date)s\n\n%(comment)s\n\nhttp://%(domain)s%(url)s') % d)
|
'QuerySet for all comments currently in the moderation queue.'
| def in_moderation(self):
| return self.get_query_set().filter(is_public=False, is_removed=False)
|
'QuerySet for all comments for a particular model (either an instance or
a class).'
| def for_model(self, model):
| ct = ContentType.objects.get_for_model(model)
qs = self.get_query_set().filter(content_type=ct)
if isinstance(model, models.Model):
qs = qs.filter(object_pk=force_unicode(model._get_pk_val()))
return qs
|
'Flag, approve, or remove some comments from an admin action. Actually
calls the `action` argument to perform the heavy lifting.'
| def _bulk_flag(self, request, queryset, action, done_message):
| n_comments = 0
for comment in queryset:
action(request, comment)
n_comments += 1
msg = ungettext(u'1 comment was successfully %(action)s.', u'%(count)s comments were successfully %(action)s.', n_comments)
self.message_user(request, (msg % {'count': n_comments, 'ac... |
'Return just those errors associated with security'
| def security_errors(self):
| errors = ErrorDict()
for f in ['honeypot', 'timestamp', 'security_hash']:
if (f in self.errors):
errors[f] = self.errors[f]
return errors
|
'Check the security hash.'
| def clean_security_hash(self):
| security_hash_dict = {'content_type': self.data.get('content_type', ''), 'object_pk': self.data.get('object_pk', ''), 'timestamp': self.data.get('timestamp', '')}
expected_hash = self.generate_security_hash(**security_hash_dict)
actual_hash = self.cleaned_data['security_hash']
if (not constant_time_comp... |
'Make sure the timestamp isn\'t too far (> 2 hours) in the past.'
| def clean_timestamp(self):
| ts = self.cleaned_data['timestamp']
if ((time.time() - ts) > ((2 * 60) * 60)):
raise forms.ValidationError('Timestamp check failed')
return ts
|
'Generate a dict of security data for "initial" data.'
| def generate_security_data(self):
| timestamp = int(time.time())
security_dict = {'content_type': str(self.target_object._meta), 'object_pk': str(self.target_object._get_pk_val()), 'timestamp': str(timestamp), 'security_hash': self.initial_security_hash(timestamp)}
return security_dict
|
'Generate the initial security hash from self.content_object
and a (unix) timestamp.'
| def initial_security_hash(self, timestamp):
| initial_security_dict = {'content_type': str(self.target_object._meta), 'object_pk': str(self.target_object._get_pk_val()), 'timestamp': str(timestamp)}
return self.generate_security_hash(**initial_security_dict)
|
'Generate a HMAC security hash from the provided info.'
| def generate_security_hash(self, content_type, object_pk, timestamp):
| info = (content_type, object_pk, timestamp)
key_salt = 'django.contrib.forms.CommentSecurityForm'
value = '-'.join(info)
return salted_hmac(key_salt, value).hexdigest()
|
'Generate a (SHA1) security hash from the provided info.'
| def _generate_security_hash_old(self, content_type, object_pk, timestamp):
| info = (content_type, object_pk, timestamp, settings.SECRET_KEY)
return sha_constructor(''.join(info)).hexdigest()
|
'Return a new (unsaved) comment object based on the information in this
form. Assumes that the form is already validated and will throw a
ValueError if not.
Does not set any of the fields that would come from a Request object
(i.e. ``user`` or ``ip_address``).'
| def get_comment_object(self):
| if (not self.is_valid()):
raise ValueError('get_comment_object may only be called on valid forms')
CommentModel = self.get_comment_model()
new = CommentModel(**self.get_comment_create_data())
new = self.check_for_duplicate_comment(new)
return new
|
'Get the comment model to create with this form. Subclasses in custom
comment apps should override this, get_comment_create_data, and perhaps
check_for_duplicate_comment to provide custom comment models.'
| def get_comment_model(self):
| return Comment
|
'Returns the dict of data to be used to create a comment. Subclasses in
custom comment apps that override get_comment_model can override this
method to add extra fields onto a custom comment model.'
| def get_comment_create_data(self):
| return dict(content_type=ContentType.objects.get_for_model(self.target_object), object_pk=force_unicode(self.target_object._get_pk_val()), user_name=self.cleaned_data['name'], user_email=self.cleaned_data['email'], user_url=self.cleaned_data['url'], comment=self.cleaned_data['comment'], submit_date=datetime.datetim... |
'Check that a submitted comment isn\'t a duplicate. This might be caused
by someone posting a comment twice. If it is a dup, silently return the *previous* comment.'
| def check_for_duplicate_comment(self, new):
| possible_duplicates = self.get_comment_model()._default_manager.using(self.target_object._state.db).filter(content_type=new.content_type, object_pk=new.object_pk, user_name=new.user_name, user_email=new.user_email, user_url=new.user_url)
for old in possible_duplicates:
if ((old.submit_date.date() == new... |
'If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn\'t
contain anything in PROFANITIES_LIST.'
| def clean_comment(self):
| comment = self.cleaned_data['comment']
if (settings.COMMENTS_ALLOW_PROFANITIES == False):
bad_words = [w for w in settings.PROFANITIES_LIST if (w in comment.lower())]
if bad_words:
plural = (len(bad_words) > 1)
raise forms.ValidationError((ungettext('Watch your mout... |
'Check that nothing\'s been entered into the honeypot.'
| def clean_honeypot(self):
| value = self.cleaned_data['honeypot']
if value:
raise forms.ValidationError(self.fields['honeypot'].label)
return value
|
'Internal helper which will return a ``datetime.timedelta``
representing the time between ``now`` and ``then``. Assumes
``now`` is a ``datetime.date`` or ``datetime.datetime`` later
than ``then``.
If ``now`` and ``then`` are not of the same type due to one of
them being a ``datetime.date`` and the other being a
``datet... | def _get_delta(self, now, then):
| if (now.__class__ is not then.__class__):
now = datetime.date(now.year, now.month, now.day)
then = datetime.date(then.year, then.month, then.day)
if (now < then):
raise ValueError('Cannot determine moderation rules because date field is set to a value ... |
'Determine whether a given comment is allowed to be posted on
a given object.
Return ``True`` if the comment should be allowed, ``False
otherwise.'
| def allow(self, comment, content_object, request):
| if self.enable_field:
if (not getattr(content_object, self.enable_field)):
return False
if (self.auto_close_field and (self.close_after is not None)):
close_after_date = getattr(content_object, self.auto_close_field)
if ((close_after_date is not None) and (self._get_delta(dat... |
'Determine whether a given comment on a given object should be
allowed to show up immediately, or should be marked non-public
and await approval.
Return ``True`` if the comment should be moderated (marked
non-public), ``False`` otherwise.'
| def moderate(self, comment, content_object, request):
| if (self.auto_moderate_field and (self.moderate_after is not None)):
moderate_after_date = getattr(content_object, self.auto_moderate_field)
if ((moderate_after_date is not None) and (self._get_delta(datetime.datetime.now(), moderate_after_date).days >= self.moderate_after)):
return True... |
'Send email notification of a new comment to site staff when email
notifications have been requested.'
| def email(self, comment, content_object, request):
| if (not self.email_notification):
return
recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS]
t = loader.get_template('comments/comment_notification_email.txt')
c = Context({'comment': comment, 'content_object': content_object})
subject = ('[%s] New comment pos... |
'Hook up the moderation methods to pre- and post-save signals
from the comment models.'
| def connect(self):
| signals.comment_will_be_posted.connect(self.pre_save_moderation, sender=comments.get_model())
signals.comment_was_posted.connect(self.post_save_moderation, sender=comments.get_model())
|
'Register a model or a list of models for comment moderation,
using a particular moderation class.
Raise ``AlreadyModerated`` if any of the models are already
registered.'
| def register(self, model_or_iterable, moderation_class):
| if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if (model in self._registry):
raise AlreadyModerated(("The model '%s' is already being moderated" % model._meta.module_name))
self._registry[... |
'Remove a model or a list of models from the list of models
whose comments will be moderated.
Raise ``NotModerated`` if any of the models are not currently
registered for moderation.'
| 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 NotModerated(("The model '%s' is not currently being moderated" % model._meta.module_name))
del se... |
'Apply any necessary pre-save moderation steps to new
comments.'
| def pre_save_moderation(self, sender, comment, request, **kwargs):
| model = comment.content_type.model_class()
if (model not in self._registry):
return
content_object = comment.content_object
moderation_class = self._registry[model]
if (not moderation_class.allow(comment, content_object, request)):
return False
if moderation_class.moderate(commen... |
'Apply any necessary post-save moderation steps to new
comments.'
| def post_save_moderation(self, sender, comment, request, **kwargs):
| model = comment.content_type.model_class()
if (model not in self._registry):
return
self._registry[model].email(comment, comment.content_object, request)
|
'Returns the ModelDatabrowse class for this model.'
| def model_databrowse(self):
| return self.site.registry[self.model]
|
'Generator that yields EasyInstanceFields for each field in this
EasyInstance\'s model.'
| def fields(self):
| for f in (self.model.model._meta.fields + self.model.model._meta.many_to_many):
(yield EasyInstanceField(self.model, self, f))
|
'Generator that yields dictionaries of all models that have this
EasyInstance\'s model as a ForeignKey or ManyToManyField, along with
lists of related objects.'
| def related_objects(self):
| for rel_object in (self.model.model._meta.get_all_related_objects() + self.model.model._meta.get_all_related_many_to_many_objects()):
if (rel_object.model not in self.model.model_list):
continue
em = EasyModel(self.model.site, rel_object.model)
(yield {'model': em, 'related_field... |
'Returns a list of values for this field for this instance. It\'s a list
so we can accomodate many-to-many fields.'
| def values(self):
| if self.field.rel:
if isinstance(self.field.rel, models.ManyToOneRel):
objs = getattr(self.instance.instance, self.field.name)
elif isinstance(self.field.rel, models.ManyToManyRel):
return list(getattr(self.instance.instance, self.field.name).all())
elif self.field.choice... |
'Returns a list of (value, URL) tuples.'
| def urls(self):
| plugin_urls = []
for (plugin_name, plugin) in self.model.model_databrowse().plugins.items():
urls = plugin.urls(plugin_name, self)
if (urls is not None):
values = self.values()
return zip(self.values(), urls)
if self.field.rel:
m = EasyModel(self.model.site, s... |
'Given an EasyInstanceField object, returns a list of URLs for this
plugin\'s views of this object. These URLs should be absolute.
Returns None if the EasyInstanceField object doesn\'t get a
list of plugin-specific URLs.'
| def urls(self, plugin_name, easy_instance_field):
| return None
|
'Returns a snippet of HTML to include on the model index page.'
| def model_index_html(self, request, model, site):
| return ''
|
'Handles main URL routing for a plugin\'s model-specific pages.'
| def model_view(self, request, model_databrowse, url):
| raise NotImplementedError
|
'Handles main URL routing for the databrowse app.
`url` is the remainder of the URL -- e.g. \'objects/3\'.'
| def root(self, request, url):
| if (url is None):
return self.main_view(request)
try:
(plugin_name, rest_of_url) = url.split('/', 1)
except ValueError:
(plugin_name, rest_of_url) = (url, None)
try:
plugin = self.plugins[plugin_name]
except KeyError:
raise http.Http404('A plugin with ... |
'Registers the given model(s) with the given databrowse site.
The model(s) should be Model classes, not instances.
If a databrowse class isn\'t given, it will use DefaultModelDatabrowse
(the default databrowse options).
If a model is already registered, this will raise AlreadyRegistered.'
| def register(self, model_or_iterable, databrowse_class=None, **options):
| databrowse_class = (databrowse_class or DefaultModelDatabrowse)
if issubclass(model_or_iterable, models.Model):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if (model in self.registry):
raise AlreadyRegistered(('The model %s is already re... |
'Unregisters the given model(s).
If a model isn\'t already registered, this will raise NotRegistered.'
| def unregister(self, model_or_iterable):
| if issubclass(model_or_iterable, models.Model):
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]
|
'Handles main URL routing for the databrowse app.
`url` is the remainder of the URL -- e.g. \'comments/comment/\'.'
| def root(self, request, url):
| self.root_url = request.path[:(len(request.path) - len(url))]
url = url.rstrip('/')
if (url == ''):
return self.index(request)
elif ('/' in url):
return self.model_page(request, *url.split('/', 2))
raise http.Http404('The requested databrowse page does not exist.')
|
'Handles the model-specific functionality of the databrowse site, delegating
to the appropriate ModelDatabrowse class.'
| def model_page(self, request, app_label, model_name, rest_of_url=None):
| model = models.get_model(app_label, model_name)
if (model is None):
raise http.Http404(('App %r, model %r, not found.' % (app_label, model_name)))
try:
databrowse_class = self.registry[model]
except KeyError:
raise http.Http404('This model exists but ha... |
'Helper function that returns a dictionary of all DateFields or
DateTimeFields in the given model. If self.field_names is set, it takes
take that into account when building the dictionary.'
| def field_dict(self, model):
| if (self.field_names is None):
return dict([(f.name, f) for f in model._meta.fields if isinstance(f, models.DateField)])
else:
return dict([(f.name, f) for f in model._meta.fields if (isinstance(f, models.DateField) and (f.name in self.field_names))])
|
'Helper function that returns a dictionary of all fields in the given
model. If self.field_filter is set, it only includes the fields that
match the filter.'
| def field_dict(self, model):
| if self.field_filter:
return dict([(f.name, f) for f in model._meta.fields if self.field_filter(f)])
else:
return dict([(f.name, f) for f in model._meta.fields if ((not f.rel) and (not f.primary_key) and (not f.unique) and (not isinstance(f, (models.AutoField, models.TextField))))])
|
'Proxy initializes on the given Geometry class (not an instance) and
the GeometryField.'
| def __init__(self, klass, field):
| self._field = field
self._klass = klass
|
'This accessor retrieves the geometry, initializing it using the geometry
class specified during initialization and the HEXEWKB value of the field.
Currently, only GEOS or OGR geometries are supported.'
| def __get__(self, obj, type=None):
| if (obj is None):
return self
geom_value = obj.__dict__[self._field.attname]
if isinstance(geom_value, self._klass):
geom = geom_value
elif ((geom_value is None) or (geom_value == '')):
geom = None
else:
geom = self._klass(geom_value)
setattr(obj, self._field.... |
'This accessor sets the proxied geometry with the geometry class
specified during initialization. Values of None, HEXEWKB, or WKT may
be used to set the geometry as well.'
| def __set__(self, obj, value):
| gtype = self._field.geom_type
if (isinstance(value, self._klass) and ((str(value.geom_type).upper() == gtype) or (gtype == 'GEOMETRY'))):
if (value.srid is None):
value.srid = self._field.srid
elif ((value is None) or isinstance(value, (basestring, buffer))):
pass
else:
... |
'The initialization function for geometry fields. Takes the following
as keyword arguments:
srid:
The spatial reference system identifier, an OGC standard.
Defaults to 4326 (WGS84).
spatial_index:
Indicates whether to create a spatial index. Defaults to True.
Set this instead of \'db_index\' for geographic fields sin... | def __init__(self, verbose_name=None, srid=4326, spatial_index=True, dim=2, geography=False, **kwargs):
| self.spatial_index = spatial_index
self.srid = srid
self.dim = dim
kwargs['verbose_name'] = verbose_name
self.geography = geography
self._extent = kwargs.pop('extent', ((-180.0), (-90.0), 180.0, 90.0))
self._tolerance = kwargs.pop('tolerance', 0.05)
super(GeometryField, self).__init__(**... |
'Returns true if this field\'s SRID corresponds with a coordinate
system that uses non-projected units (e.g., latitude/longitude).'
| def geodetic(self, connection):
| return (self.units_name(connection) in self.geodetic_units)
|
'Returns a distance number in units of the field. For example, if
`D(km=1)` was passed in and the units of the field were in meters,
then 1000 would be returned.'
| def get_distance(self, value, lookup_type, connection):
| return connection.ops.get_distance(self, value, lookup_type)
|
'Spatial lookup values are either a parameter that is (or may be
converted to) a geometry, or a sequence of lookup values that
begins with a geometry. This routine will setup the geometry
value properly, and preserve any other lookup parameters before
returning to the caller.'
| def get_prep_value(self, value):
| if isinstance(value, SQLEvaluator):
return value
elif isinstance(value, (tuple, list)):
geom = value[0]
seq_value = True
else:
geom = value
seq_value = False
if isinstance(geom, Geometry):
pass
elif (isinstance(geom, basestring) or hasattr(geom, '__geo... |
'Returns the default SRID for the given geometry, taking into account
the SRID set for the field. For example, if the input geometry
has no SRID, then that of the field will be returned.'
| def get_srid(self, geom):
| gsrid = geom.srid
if ((gsrid is None) or (self.srid == (-1)) or ((gsrid == (-1)) and (self.srid != (-1)))):
return self.srid
else:
return gsrid
|
'Prepare for the database lookup, and return any spatial parameters
necessary for the query. This includes wrapping any geometry
parameters with a backend-specific adapter and formatting any distance
parameters into the correct units for the coordinate system of the
field.'
| def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False):
| if (lookup_type in connection.ops.gis_terms):
if (lookup_type == 'isnull'):
return []
if isinstance(value, (tuple, list)):
params = [connection.ops.Adapter(value[0])]
if (lookup_type in connection.ops.distance_functions):
params += self.get_distanc... |
'Prepares the value for saving in the database.'
| def get_db_prep_save(self, value, connection):
| if (value is None):
return None
else:
return connection.ops.Adapter(self.get_prep_value(value))
|
'Returns the placeholder for the geometry column for the
given value.'
| def get_placeholder(self, value, connection):
| return connection.ops.get_geom_placeholder(self, value)
|
'Returns the area of the geographic field in an `area` attribute on
each element of this GeoQuerySet.'
| def area(self, tolerance=0.05, **kwargs):
| (procedure_args, geo_field) = self._spatial_setup('area', field_name=kwargs.get('field_name', None))
s = {'procedure_args': procedure_args, 'geo_field': geo_field, 'setup': False}
connection = connections[self.db]
backend = connection.ops
if backend.oracle:
s['procedure_fmt'] = '%(geo_col)s,... |
'Returns the centroid of the geographic field in a `centroid`
attribute on each element of this GeoQuerySet.'
| def centroid(self, **kwargs):
| return self._geom_attribute('centroid', **kwargs)
|
'Performs an aggregate collect operation on the given geometry field.
This is analagous to a union operation, but much faster because
boundaries are not dissolved.'
| def collect(self, **kwargs):
| return self._spatial_aggregate(aggregates.Collect, **kwargs)
|
'Returns the spatial difference of the geographic field in a `difference`
attribute on each element of this GeoQuerySet.'
| def difference(self, geom, **kwargs):
| return self._geomset_attribute('difference', geom, **kwargs)
|
'Returns the distance from the given geographic field name to the
given geometry in a `distance` attribute on each element of the
GeoQuerySet.
Keyword Arguments:
`spheroid` => If the geometry field is geodetic and PostGIS is
the spatial database, then the more accurate
spheroid calculation will be used instead of the
... | def distance(self, geom, **kwargs):
| return self._distance_attribute('distance', geom, **kwargs)
|
'Returns a Geometry representing the bounding box of the
Geometry field in an `envelope` attribute on each element of
the GeoQuerySet.'
| def envelope(self, **kwargs):
| return self._geom_attribute('envelope', **kwargs)
|
'Returns the extent (aggregate) of the features in the GeoQuerySet. The
extent will be returned as a 4-tuple, consisting of (xmin, ymin, xmax, ymax).'
| def extent(self, **kwargs):
| return self._spatial_aggregate(aggregates.Extent, **kwargs)
|
'Returns the aggregate extent, in 3D, of the features in the
GeoQuerySet. It is returned as a 6-tuple, comprising:
(xmin, ymin, zmin, xmax, ymax, zmax).'
| def extent3d(self, **kwargs):
| return self._spatial_aggregate(aggregates.Extent3D, **kwargs)
|
'Returns a modified version of the Polygon/MultiPolygon in which
all of the vertices follow the Right-Hand-Rule. By default,
this is attached as the `force_rhr` attribute on each element
of the GeoQuerySet.'
| def force_rhr(self, **kwargs):
| return self._geom_attribute('force_rhr', **kwargs)
|
'Returns a GeoJSON representation of the geomtry field in a `geojson`
attribute on each element of the GeoQuerySet.
The `crs` and `bbox` keywords may be set to True if the users wants
the coordinate reference system and the bounding box to be included
in the GeoJSON representation of the geometry.'
| def geojson(self, precision=8, crs=False, bbox=False, **kwargs):
| backend = connections[self.db].ops
if (not backend.geojson):
raise NotImplementedError('Only PostGIS 1.3.4+ supports GeoJSON serialization.')
if (not isinstance(precision, (int, long))):
raise TypeError('Precision keyword must be set with an integer.')
... |
'Returns a GeoHash representation of the given field in a `geohash`
attribute on each element of the GeoQuerySet.
The `precision` keyword may be used to custom the number of
_characters_ used in the output GeoHash, the default is 20.'
| def geohash(self, precision=20, **kwargs):
| s = {'desc': 'GeoHash', 'procedure_args': {'precision': precision}, 'procedure_fmt': '%(geo_col)s,%(precision)s'}
return self._spatial_attribute('geohash', s, **kwargs)
|
'Returns GML representation of the given field in a `gml` attribute
on each element of the GeoQuerySet.'
| def gml(self, precision=8, version=2, **kwargs):
| backend = connections[self.db].ops
s = {'desc': 'GML', 'procedure_args': {'precision': precision}}
if backend.postgis:
if (backend.spatial_version > (1, 3, 1)):
procedure_fmt = '%(version)s,%(geo_col)s,%(precision)s'
else:
procedure_fmt = '%(geo_col)s,%(precision)s,%(... |
'Returns the spatial intersection of the Geometry field in
an `intersection` attribute on each element of this
GeoQuerySet.'
| def intersection(self, geom, **kwargs):
| return self._geomset_attribute('intersection', geom, **kwargs)
|
'Returns KML representation of the geometry field in a `kml`
attribute on each element of this GeoQuerySet.'
| def kml(self, **kwargs):
| s = {'desc': 'KML', 'procedure_fmt': '%(geo_col)s,%(precision)s', 'procedure_args': {'precision': kwargs.pop('precision', 8)}}
return self._spatial_attribute('kml', s, **kwargs)
|
'Returns the length of the geometry field as a `Distance` object
stored in a `length` attribute on each element of this GeoQuerySet.'
| def length(self, **kwargs):
| return self._distance_attribute('length', None, **kwargs)
|
'Creates a linestring from all of the PointField geometries in the
this GeoQuerySet and returns it. This is a spatial aggregate
method, and thus returns a geometry rather than a GeoQuerySet.'
| def make_line(self, **kwargs):
| return self._spatial_aggregate(aggregates.MakeLine, geo_field_type=PointField, **kwargs)
|
'Returns the memory size (number of bytes) that the geometry field takes
in a `mem_size` attribute on each element of this GeoQuerySet.'
| def mem_size(self, **kwargs):
| return self._spatial_attribute('mem_size', {}, **kwargs)
|
'Returns the number of geometries if the field is a
GeometryCollection or Multi* Field in a `num_geom`
attribute on each element of this GeoQuerySet; otherwise
the sets with None.'
| def num_geom(self, **kwargs):
| return self._spatial_attribute('num_geom', {}, **kwargs)
|
'Returns the number of points in the first linestring in the
Geometry field in a `num_points` attribute on each element of
this GeoQuerySet; otherwise sets with None.'
| def num_points(self, **kwargs):
| return self._spatial_attribute('num_points', {}, **kwargs)
|
'Returns the perimeter of the geometry field as a `Distance` object
stored in a `perimeter` attribute on each element of this GeoQuerySet.'
| def perimeter(self, **kwargs):
| return self._distance_attribute('perimeter', None, **kwargs)
|
'Returns a Point geometry guaranteed to lie on the surface of the
Geometry field in a `point_on_surface` attribute on each element
of this GeoQuerySet; otherwise sets with None.'
| def point_on_surface(self, **kwargs):
| return self._geom_attribute('point_on_surface', **kwargs)
|
'Reverses the coordinate order of the geometry, and attaches as a
`reverse` attribute on each element of this GeoQuerySet.'
| def reverse_geom(self, **kwargs):
| s = {'select_field': GeomField()}
kwargs.setdefault('model_att', 'reverse_geom')
if connections[self.db].ops.oracle:
s['geo_field_type'] = LineStringField
return self._spatial_attribute('reverse', s, **kwargs)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.