def get_state(): try: state = State.objects.get() except State.DoesNotExist: state = State() state.save() return state
def create_state_nodes(df): n_nodes = 0 for _, row in df.drop_duplicates(subset=["state"]).iterrows(): state = State(name=row["state"]) state.save() n_nodes += 1 print("created {} nodes".format(n_nodes))
def state_add(): data = request.get_json() if data is None: return 'Not a JSON', 400 if 'name' not in data.keys(): return 'Missing name', 400 state = State(**data) state.save() return jsonify(state.to_json()), 201
def check_servers(id, host, port, timeout, server): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(float(timeout)) if sock.connect_ex((host, int(port))) == 0: b = State(id=id, active=True, server=server) b.save() else: b = State(id=id, active=False, server=server) b.save()
def states_post(): """Add a state to storage with given dictionary""" obj = request.get_json(silent=True) if obj is None: return "Not a JSON", 400 if "name" not in obj: return "Missing name", 400 obj = State(**obj) obj.save() return jsonify(obj.to_dict()), 201
def process(self, commit, *args, **kwargs): data = commit.data try: state = State.objects.get(id=data.get("id")) except State.DoesNotExist: state = State() state.id = data.get("id") state.interest = data.get("interest") # state.commits.append(commit) commit.save() state.save()
def post_states(): content = request.get_json() if content is None: return (jsonify({"error": "Not a JSON"}), 400) name = content.get("name") if name is None: return (jsonify({"error": "Missing name"}), 400) new_state = State(**content) new_state.save() return (jsonify(new_state.to_dict()), 201)
def process(self, commit, *args, **kwargs): data = commit.data try: state = State.objects.get(id=data.get("id")) except State.DoesNotExist: state = State() state.id = data.get("id") state.last_payment = data.get("state_last_payment") state.paid = data.get("paid") # state.commits.append(commit) commit.save() state.save()
def post_state(): """ Adds a new state to State """ try: if request.json: if 'name' not in request.json: return jsonify({'error': 'Missing name'}), 400 news = request.get_json().get('name') newo = State(name=news) newo.save() return jsonify(newo.to_dict()), 201 else: return jsonify({'error': 'Not a JSON'}), 400 except: abort(404)
def add_state(): """Creates a State object""" req = request.get_json() if req is None: return (jsonify("Not a JSON"), 400) try: req['name'] except: return (jsonify("Missing name"), 400) data = State(**req) # unpack dictionary data.save() return (jsonify(data.to_json()), 201)
def post_states(states_id): """ Post to states """ state = request.get_json() if not state: return ("Not a JSON", 400) elif state.get("name") is None: return (abort(400, "Missing name")) else: add_state = State(name=state['name']) storage.new(add_state) state_tojson = storage.get("State", add_state.id).to_json() add_state.save() return (jsonify(state_tojson))
def get_states(): """ Retrieves list of all State objects """ if request.method == 'GET': return jsonify( [obj.to_dict() for obj in storage.all("State").values()]) if request.method == 'POST': if not request.json: abort(400, 'Not a JSON') if 'name' not in request.json: abort(400, 'Missing name') data = request.get_json().get('name') new_state = State(name=data) new_state.save() return make_response(jsonify(new_state.to_dict()), 201)
def post_states(): """ function to add states """ content = request.get_json() if content is None: return (jsonify({"error": "Not a JSON"}), 400) name = content.get("name") if name is None: return (jsonify({"error": "Missing name"}), 400) add_state = State() add_state.name = name add_state.save() return (jsonify(add_state.to_dict()), 201)
def all_states(): ''' GET: list all states POST: create a new state ''' if request.method == 'POST': state_dict = request.get_json() if state_dict is None: return 'Not a JSON', 400 if 'name' not in state_dict.keys(): return 'Missing name', 400 my_state = State(**state_dict) my_state.save() return jsonify(my_state.to_dict()), 201 my_states = [state.to_dict() for state in storage.all('State').values()] return jsonify(my_states)
def posting_states(): """ Creating a new state object Return: jsonified dicitonary of the new object or error 400 and 404 """ try: if not request.json: return jsonify({"error": "Not a JSON"}), 400 data = request.get_json() if "name" not in data: return jsonify({"error": "Missing name"}), 400 new_obj = State(name=data["name"]) new_obj.save() return jsonify(new_obj.to_dict()), 201 except Exception: abort(404)
def create_state(): ''' Creates a new State object and saves it to storage ''' if not request.json: abort(400) return jsonify({"error": "Not a JSON"}) else: state_dict = request.get_json() if "name" in state_dict: state_name = state_dict["name"] state = State(name=state_name) for k, v in state_dict.items(): setattr(state, k, v) state.save() else: abort(400) return jsonify({"error": "Missing name"}) return jsonify(state.to_dict()), 201
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 test02_proxy(self): "Testing Lazy-Geometry support (using the GeometryProxy)." if DISABLE: return ## Testing on a Point pnt = Point(0, 0) nullcity = City(name='NullCity', point=pnt) nullcity.save() # Making sure TypeError is thrown when trying to set with an # incompatible type. for bad in [5, 2.0, LineString((0, 0), (1, 1))]: try: nullcity.point = bad except TypeError: pass else: self.fail('Should throw a TypeError') # Now setting with a compatible GEOS Geometry, saving, and ensuring # the save took, notice no SRID is explicitly set. new = Point(5, 23) nullcity.point = new # Ensuring that the SRID is automatically set to that of the # field after assignment, but before saving. self.assertEqual(4326, nullcity.point.srid) nullcity.save() # Ensuring the point was saved correctly after saving self.assertEqual(new, City.objects.get(name='NullCity').point) # Setting the X and Y of the Point nullcity.point.x = 23 nullcity.point.y = 5 # Checking assignments pre & post-save. self.assertNotEqual(Point(23, 5), City.objects.get(name='NullCity').point) nullcity.save() self.assertEqual(Point(23, 5), City.objects.get(name='NullCity').point) nullcity.delete() ## Testing on a Polygon shell = LinearRing((0, 0), (0, 100), (100, 100), (100, 0), (0, 0)) inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40)) # Creating a State object using a built Polygon ply = Polygon(shell, inner) nullstate = State(name='NullState', poly=ply) self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None nullstate.save() ns = State.objects.get(name='NullState') self.assertEqual(ply, ns.poly) # Testing the `ogr` and `srs` lazy-geometry properties. if gdal.HAS_GDAL: self.assertEqual(True, isinstance(ns.poly.ogr, gdal.OGRGeometry)) self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb) self.assertEqual(True, isinstance(ns.poly.srs, gdal.SpatialReference)) self.assertEqual('WGS 84', ns.poly.srs.name) # Changing the interior ring on the poly attribute. new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30)) ns.poly[1] = new_inner ply[1] = new_inner self.assertEqual(4326, ns.poly.srid) ns.save() self.assertEqual(ply, State.objects.get(name='NullState').poly) ns.delete()
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 test02_proxy(self): "Testing Lazy-Geometry support (using the GeometryProxy)." #### Testing on a Point pnt = Point(0, 0) nullcity = City(name='NullCity', point=pnt) nullcity.save() # Making sure TypeError is thrown when trying to set with an # incompatible type. for bad in [5, 2.0, LineString((0, 0), (1, 1))]: try: nullcity.point = bad except TypeError: pass else: self.fail('Should throw a TypeError') # Now setting with a compatible GEOS Geometry, saving, and ensuring # the save took, notice no SRID is explicitly set. new = Point(5, 23) nullcity.point = new # Ensuring that the SRID is automatically set to that of the # field after assignment, but before saving. self.assertEqual(4326, nullcity.point.srid) nullcity.save() # Ensuring the point was saved correctly after saving self.assertEqual(new, City.objects.get(name='NullCity').point) # Setting the X and Y of the Point nullcity.point.x = 23 nullcity.point.y = 5 # Checking assignments pre & post-save. self.assertNotEqual(Point(23, 5), City.objects.get(name='NullCity').point) nullcity.save() self.assertEqual(Point(23, 5), City.objects.get(name='NullCity').point) nullcity.delete() #### Testing on a Polygon shell = LinearRing((0, 0), (0, 100), (100, 100), (100, 0), (0, 0)) inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40)) # Creating a State object using a built Polygon ply = Polygon(shell, inner) nullstate = State(name='NullState', poly=ply) self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None nullstate.save() ns = State.objects.get(name='NullState') self.assertEqual(ply, ns.poly) # Testing the `ogr` and `srs` lazy-geometry properties. if gdal.HAS_GDAL: self.assertEqual(True, isinstance(ns.poly.ogr, gdal.OGRGeometry)) self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb) self.assertEqual(True, isinstance(ns.poly.srs, gdal.SpatialReference)) self.assertEqual('WGS 84', ns.poly.srs.name) # Changing the interior ring on the poly attribute. new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30)) ns.poly[1] = new_inner ply[1] = new_inner self.assertEqual(4326, ns.poly.srid) ns.save() self.assertEqual(ply, State.objects.get(name='NullState').poly) ns.delete()