Declaring the models

For the models, all of the field types (for example, Integer, String, and Float) are defined using SQLAlchemy ORM-column classes, except for the geometry columns, which use the GeoAlchemy2  Geometry class. The Geometry class requires a geometry type and SRID:

# Define the Arena class, which will model the Arena database table
class Arena(Base):
__tablename__ = 'arena'
id = Column(Integer, primary_key=True)
name = Column(String)
longitude = Column(Float)
latitude = Column(Float)
geom = Column(Geometry(geometry_type='POINT', srid=4326))

The County class has a primary key field and a name field, as well as fields that define the many-to-one relationship with the State class. Instead of a POINT geometry type, it uses MULTIPOLYGON:

# Define the County class, which will model the County database table
class County(Base):
__tablename__ = 'county'
id = Column(Integer, primary_key=True)
name = Column(String)
state_id = Column(Integer, ForeignKey('state.id'))
state_ref = relationship("State",backref='county')
geom = Column(Geometry(geometry_type='MULTIPOLYGON', srid=4326))

The District class represents US Congressional Districts. Stored with a MULTIPOLYGON geometry type and an SRID of 4326, it has a many-to-one relationship with the State class. Each district stored is linked to the state in which it resides:

# Define the District class, which will model the District database table
class District(Base):
__tablename__ = 'district'
id = Column(Integer, primary_key=True)
district = Column(String)
name = Column(String)
state_id = Column(Integer, ForeignKey('state.id'))
state_ref = relationship("State",backref='district')
geom = Column(Geometry(geometry_type='MULTIPOLYGON', srid=4326))

The State class has one-to-many relationships with the County and District classes respectively, defined using the relationship function. It also has a MULTIPOLYGON geometry column with an SRID of 4326:

# Define the State class, which will model the State database table
class State(Base):
__tablename__ = 'state'
id = Column(Integer, primary_key=True)
name = Column(String)
statefips = Column(String)
stpostal = Column(String)
counties = relationship('County', backref='state')
districts = relationship('District', backref='state')
geom = Column(Geometry(geometry_type='MULTIPOLYGON', srid=4326))

With the fields and relationships defined, the next step is to create the REST API endpoints and write the views that will query the database and return GeoJSON responses. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset