def test01_init(self): "Testing LayerMapping initialization." # Model field that does not exist. bad1 = copy(city_mapping) bad1['foobar'] = 'FooField' # Shapefile field that does not exist. bad2 = copy(city_mapping) bad2['name'] = 'Nombre' # Nonexistent geographic field type. bad3 = copy(city_mapping) bad3['point'] = 'CURVE' # Incrementing through the bad mapping dictionaries and # ensuring that a LayerMapError is raised. for bad_map in (bad1, bad2, bad3): try: lm = LayerMapping(City, city_shp, bad_map) except LayerMapError: pass else: self.fail('Expected a LayerMapError.') # A LookupError should be thrown for bogus encodings. try: lm = LayerMapping(City, city_shp, city_mapping, encoding='foobar') except LookupError: pass else: self.fail('Expected a LookupError')
def __deepcopy__(self, memodict): # We don't have to deepcopy very much here, since most things are not # intended to be altered after initial creation. obj = copy.copy(self) if self.rel: obj.rel = copy.copy(self.rel) memodict[id(self)] = obj return obj
def __getitem__(self, key): if isinstance(key, slice): new_set = copy(self) new_set.slice = key return new_set else: return self.build_representation(self.data[key])
def account(request): """ View which displays `frontend.account.forms.AccountChangeForm` form for users to change their account. If the user changes her e-mail address her account is inactivated and she gets an activation e-mail. """ assert request.user.is_authenticated() if request.method == 'POST': stored_user = copy.copy(request.user) form = forms.AccountChangeForm( request.POST, instance=[request.user, request.user.get_profile()]) if form.is_valid(): objs = form.save() messages.success(request, _("Your account has been successfully updated."), fail_silently=True) old_email = stored_user.email new_email = request.user.email if old_email == new_email: return shortcuts.redirect( objs[-1]) # The last element is user profile object else: site = sites_models.Site.objects.get_current( ) if sites_models.Site._meta.installed else sites_models.RequestSite( request) request.user.is_active = False request.user.save() # Creates a new activation key registration_models.RegistrationProfile.objects.filter( user=request.user).delete() registration_profile = registration_models.RegistrationProfile.objects.create_profile( request.user) registration_profile.send_activation_email(site, email_change=True) url = urlresolvers.reverse('email_change_complete') return logout_redirect(request, next_page=url) else: # Restore user request object as it is changed by form.is_valid request.user = stored_user if hasattr(request.user, '_profile_cache'): # Invalidates profile cache delattr(request.user, '_profile_cache') else: form = forms.AccountChangeForm( instance=[request.user, request.user.get_profile()]) return shortcuts.render_to_response( "users/account.html", { 'form': form, }, context_instance=template.RequestContext(request))
def test22_copy(self): "Testing use with the Python `copy` module." import django.utils.copycompat as copy poly = GEOSGeometry('POLYGON((0 0, 0 23, 23 23, 23 0, 0 0), (5 5, 5 10, 10 10, 10 5, 5 5))') cpy1 = copy.copy(poly) cpy2 = copy.deepcopy(poly) self.assertNotEqual(poly._ptr, cpy1._ptr) self.assertNotEqual(poly._ptr, cpy2._ptr)
def benchmark_dict(): #instantiate a new dict and call same methods as above - to be fair, get unlistify in this method where required caseDict = dict(case) caseDict['a'][0] caseDict['b'][1] caseDict['c'][2] caseDict.items() caseDict.values() for i in caseDict: i caseDict.update(update) copy.copy(caseDict) copy.deepcopy(caseDict) caseDict['a'] = ['A'] caseDict['b'] = ['B'] caseDict['c'] = ['C']
def benchmark_multi(): #instantiate a new MultiValueDict and call key method (i.e. that do something diff than dict) caseDict = MultiValueDict(case) caseDict['a'] caseDict['b'] caseDict['c'] caseDict.update(update) copy.copy(caseDict) copy.deepcopy(caseDict) caseDict.items() caseDict.lists() for i in caseDict: i caseDict['a'] = 'A' caseDict['b'] = 'B' caseDict['c'] = 'C'
def _copy_to_model(self, model): """ Makes a copy of the manager and assigns it to 'model', which should be a child of the existing model (used when inheriting a manager from an abstract base class). """ assert issubclass(model, self.model) mgr = copy.copy(self) mgr._set_creation_counter() mgr.model = model mgr._inherited = True return mgr
def account(request): """ View which displays `frontend.account.forms.AccountChangeForm` form for users to change their account. If the user changes her e-mail address her account is inactivated and she gets an activation e-mail. """ assert request.user.is_authenticated() if request.method == 'POST': stored_user = copy.copy(request.user) form = forms.AccountChangeForm(request.POST, instance=[request.user, request.user.get_profile()]) if form.is_valid(): objs = form.save() messages.success(request, _("Your account has been successfully updated."), fail_silently=True) old_email = stored_user.email new_email = request.user.email if old_email == new_email: return shortcuts.redirect(objs[-1]) # The last element is user profile object else: site = sites_models.Site.objects.get_current() if sites_models.Site._meta.installed else sites_models.RequestSite(request) request.user.is_active = False request.user.save() # Creates a new activation key registration_models.RegistrationProfile.objects.filter(user=request.user).delete() registration_profile = registration_models.RegistrationProfile.objects.create_profile(request.user) registration_profile.send_activation_email(site, email_change=True) url = urlresolvers.reverse('email_change_complete') return logout_redirect(request, next_page=url) else: # Restore user request object as it is changed by form.is_valid request.user = stored_user if hasattr(request.user, '_profile_cache'): # Invalidates profile cache delattr(request.user, '_profile_cache') else: form = forms.AccountChangeForm(instance=[request.user, request.user.get_profile()]) return shortcuts.render_to_response("users/account.html", { 'form': form, }, context_instance=template.RequestContext(request))
def __deepcopy__(self, memo): obj = copy.copy(self) obj.widget = copy.deepcopy(self.widget, memo) obj.attrs = self.widget.attrs memo[id(self)] = obj return obj
def test04_layermap_unique_multigeometry_fk(self): "Testing the `unique`, and `transform`, geometry collection conversion, and ForeignKey mappings." # All the following should work. try: # Telling LayerMapping that we want no transformations performed on the data. lm = LayerMapping(County, co_shp, co_mapping, transform=False) # Specifying the source spatial reference system via the `source_srs` keyword. lm = LayerMapping(County, co_shp, co_mapping, source_srs=4269) lm = LayerMapping(County, co_shp, co_mapping, source_srs='NAD83') # Unique may take tuple or string parameters. for arg in ('name', ('name', 'mpoly')): lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique=arg) except: self.fail( 'No exception should be raised for proper use of keywords.') # Testing invalid params for the `unique` keyword. for e, arg in ((TypeError, 5.0), (ValueError, 'foobar'), (ValueError, ('name', 'mpolygon'))): self.assertRaises(e, LayerMapping, County, co_shp, co_mapping, transform=False, unique=arg) # No source reference system defined in the shapefile, should raise an error. if not mysql: self.assertRaises(LayerMapError, LayerMapping, County, co_shp, co_mapping) # Passing in invalid ForeignKey mapping parameters -- must be a dictionary # mapping for the model the ForeignKey points to. bad_fk_map1 = copy(co_mapping) bad_fk_map1['state'] = 'name' bad_fk_map2 = copy(co_mapping) bad_fk_map2['state'] = { 'nombre': 'State' } self.assertRaises(TypeError, LayerMapping, County, co_shp, bad_fk_map1, transform=False) self.assertRaises(LayerMapError, LayerMapping, County, co_shp, bad_fk_map2, transform=False) # There exist no State models for the ForeignKey mapping to work -- should raise # a MissingForeignKey exception (this error would be ignored if the `strict` # keyword is not set). lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name') self.assertRaises(MissingForeignKey, lm.save, silent=True, strict=True) # Now creating the state models so the ForeignKey mapping may work. co, hi, tx = State(name='Colorado'), State(name='Hawaii'), State( name='Texas') co.save(), hi.save(), tx.save() # If a mapping is specified as a collection, all OGR fields that # are not collections will be converted into them. For example, # a Point column would be converted to MultiPoint. Other things being done # w/the keyword args: # `transform=False`: Specifies that no transform is to be done; this # has the effect of ignoring the spatial reference check (because the # county shapefile does not have implicit spatial reference info). # # `unique='name'`: Creates models on the condition that they have # unique county names; geometries from each feature however will be # appended to the geometry collection of the unique model. Thus, # all of the various islands in Honolulu county will be in in one # database record with a MULTIPOLYGON type. lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name') lm.save(silent=True, strict=True) # A reference that doesn't use the unique keyword; a new database record will # created for each polygon. lm = LayerMapping(CountyFeat, co_shp, cofeat_mapping, transform=False) lm.save(silent=True, strict=True) # The county helper is called to ensure integrity of County models. self.county_helper()
def new_revision(self): new_revision = copy.copy(self) new_revision.pk = None return new_revision
def test04_layermap_unique_multigeometry_fk(self): "Testing the `unique`, and `transform`, geometry collection conversion, and ForeignKey mappings." # All the following should work. try: # Telling LayerMapping that we want no transformations performed on the data. lm = LayerMapping(County, co_shp, co_mapping, transform=False) # Specifying the source spatial reference system via the `source_srs` keyword. lm = LayerMapping(County, co_shp, co_mapping, source_srs=4269) lm = LayerMapping(County, co_shp, co_mapping, source_srs='NAD83') # Unique may take tuple or string parameters. for arg in ('name', ('name', 'mpoly')): lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique=arg) except: self.fail('No exception should be raised for proper use of keywords.') # Testing invalid params for the `unique` keyword. for e, arg in ((TypeError, 5.0), (ValueError, 'foobar'), (ValueError, ('name', 'mpolygon'))): self.assertRaises(e, LayerMapping, County, co_shp, co_mapping, transform=False, unique=arg) # No source reference system defined in the shapefile, should raise an error. if not mysql: self.assertRaises(LayerMapError, LayerMapping, County, co_shp, co_mapping) # Passing in invalid ForeignKey mapping parameters -- must be a dictionary # mapping for the model the ForeignKey points to. bad_fk_map1 = copy(co_mapping); bad_fk_map1['state'] = 'name' bad_fk_map2 = copy(co_mapping); bad_fk_map2['state'] = {'nombre' : 'State'} self.assertRaises(TypeError, LayerMapping, County, co_shp, bad_fk_map1, transform=False) self.assertRaises(LayerMapError, LayerMapping, County, co_shp, bad_fk_map2, transform=False) # There exist no State models for the ForeignKey mapping to work -- should raise # a MissingForeignKey exception (this error would be ignored if the `strict` # keyword is not set). lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name') self.assertRaises(MissingForeignKey, lm.save, silent=True, strict=True) # Now creating the state models so the ForeignKey mapping may work. co, hi, tx = State(name='Colorado'), State(name='Hawaii'), State(name='Texas') co.save(), hi.save(), tx.save() # If a mapping is specified as a collection, all OGR fields that # are not collections will be converted into them. For example, # a Point column would be converted to MultiPoint. Other things being done # w/the keyword args: # `transform=False`: Specifies that no transform is to be done; this # has the effect of ignoring the spatial reference check (because the # county shapefile does not have implicit spatial reference info). # # `unique='name'`: Creates models on the condition that they have # unique county names; geometries from each feature however will be # appended to the geometry collection of the unique model. Thus, # all of the various islands in Honolulu county will be in in one # database record with a MULTIPOLYGON type. lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name') lm.save(silent=True, strict=True) # A reference that doesn't use the unique keyword; a new database record will # created for each polygon. lm = LayerMapping(CountyFeat, co_shp, cofeat_mapping, transform=False) lm.save(silent=True, strict=True) # The county helper is called to ensure integrity of County models. self.county_helper()
def db_manager(self, using): obj = copy.copy(self) obj._db = using return obj
def __deepcopy__(self, memo): result = copy.copy(self) memo[id(self)] = result result.widget = copy.deepcopy(self.widget, memo) return result
def db_manager(self, alias): obj = copy.copy(self) obj._db = alias return obj
def __deepcopy__(self, memo): obj = copy.copy(self) obj.attrs = self.attrs.copy() memo[id(self)] = obj return obj
def copy(self): """Returns a shallow copy of this object.""" return copy(self)