【发布时间】:2022-11-07 19:06:39
【问题描述】:
我正在尝试使用psycopg2 执行来自扩展(postgis)的函数。
import psycopg2
AFRICA = "africa"
ANTARCTICA = "antarctica"
ASIA = "asia"
AUSTRALIA_OCEANIA = "australia-oceania"
CENTRAL_AMERICA = "central-america"
EUROPE = "europe"
NORTH_AMERICA = "north-america"
SOUTH_AMERICA = "south-america"
SCHEMAS = [AFRICA, ANTARCTICA, ASIA, AUSTRALIA_OCEANIA,
CENTRAL_AMERICA, EUROPE, NORTH_AMERICA, SOUTH_AMERICA]
def createCentroidTableFromPolygon(fromTable, toTable):
return f"""
CREATE TABLE IF NOT EXISTS {toTable} AS
SELECT ST_Centroid(geom) AS geom, way_id, osm_type, name FROM {fromTable};
"""
for schema in SCHEMAS:
conn = psycopg2.connect(
host='localhost',
database='world',
user="postgres",
password="postgres",
port=5432,
options=f"-c search_path={schema}"
)
for i, table in enumerate(TABLES):
# https://stackoverflow.com/questions/57116846/run-postgresql-functions-in-python-and-gets-error
with conn:
with conn.cursor() as cursor:
# this works!
cursor.execute(f"""SELECT * FROM {table} LIMIT 10""")
print(cursor.fetchall())
# this throws an error
cursor.execute(createCentroidTableFromPolygon(
table, FROM_POLY_TABLES[i]))
这给了我
psycopg2.errors.UndefinedFunction:函数 st_centroid(public.geometry) 不存在 第 3 行:选择 ST_Centroid(geom) 作为 geom、way_id、osm_type、名称...
提示:没有函数匹配给定的名称和参数类型。您可能需要添加显式类型转换。扩展名
postgis安装在database world上。SELECT * FROM pg_extension;当我尝试在
pgAdmin中运行此功能时,它可以正常工作...
【问题讨论】:
-
@GuillermoGarcia 不,因为如您所见,我在数据库上安装了
postgis扩展...
标签: python postgresql postgis psycopg2