Search code examples
pythonsqlalchemypostgis

Insert point geometry into PostGIS using Flask Python


Have successfully defined and migrated a table into a PostGIS database with the following definition:

from db import db
from geoalchemy2.types import Geometry


class HouseModel(db.Model):
    __tablename__ = 'house'
    __table_args__ = {'schema': 'housing'}
    house_id = db.Column(db.Integer, primary_key=True)
    address1 = db.Column(db.String)
    address2 = db.Column(db.String)
    suburb = db.Column(db.String)
    country = db.Column(db.String)
    state = db.Column(db.String)
    postcode = db.Column(db.String)
    location = db.Column(Geometry(geometry_type='POINT', srid=4326))

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()

but when I try and insert into that table I am struggling to figure out how to. When setting the data type to a shapely Point type or even a string of f'POINT({lat},{long})' I get the following error:

sqlalchemy.exc.InternalError: (psycopg2.errors.InternalError_) parse error - invalid geometry
HINT:  "SRID=4269,P" <-- parse error at position 11 within geometry

[SQL: INSERT INTO housing.house (address1, address2, suburb, country, state, postcode, location) VALUES (%(address1)s, %(address2)s, %(suburb)s, %(country)s, %(state)s, %(postcode)s, ST_GeomFromEWKT(%(location)s
)) RETURNING housing.house.house_id]
[parameters: {'address1': None, 'address2': None, 'suburb': None, 'country': None, 'state': None, 'postcode': None, 'location': 'SRID=4269,POINT(-33.90345045347954, 152.7345762127824)'}]
(Background on this error at: http://sqlalche.me/e/14/2j85)

any idea what data type or what format this function is expecting when I run house.save_to_db() ?


Solution

  • Turns out it was expecting text with the formatting of:

    'SRID=4326;POINT(-33.9034 152.73457)'
    

    Needing a ; between SRID and POINT and no , between the latitude and longitude.