Adding the PostGIS extension tables to the new database

Just underneath the create_database function, we will need to connect to the database using the engine.connect function to pass an SQL statement directly to the database. This SQL statement, ("CREATE EXTENSION postgis") enables spatial columns and queries within the new database:

    # Create a direct connection to the database using the engine.    # This will allow the new database to use the PostGIS extension.    conn = engine.connect()    conn.execute("commit")    try:         conn.execute("CREATE EXTENSION postgis")     except Exception as e:         print(e)         print("extension postgis already exists")     conn.close()

A try/except block is used here in case the database has already been spatially enabled. Check the output ...

Get Mastering Geospatial Analysis with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.