运行 Python 来自 PostgreSQL 函数的脚本

Run Python script from PostgreSQL function

关于每次执行 Python 脚本的“小”问题是在 PostgreSQL table.

上执行更新或插入操作

此脚本将提取更新或插入的数据并将其写入文件。

环境数据:Ubuntu 18.04 (Bionic Beaver)、PostgreSQL 10 和 Python 3.6

SELECT * FROM pg_available_extensions
WHERE name LIKE '%python%' ORDER BY name;

并输出

姓名 default_version installed_version 评论
hstore_plpython2u 1.0 hstore 和 plpython2u 之间的转换
hstore_plpythonu 1.0 hstore 和 plpythonu 之间的转换
ltree_plpython2u 1.0 ltree 和 plpython2u 之间的转换
ltree_plpythonu 1.0 ltree 和 plpythonu 之间的转换
plpython2u 1.0 PL/Python2U 不受信任的程序语言
plpythonu 1.0 1.0 PL/PythonU 不受信任的程序语言

我创建了一个 PostgreSQL 函数(我希望在阅读所有文档后一切正常)

CREATE FUNCTION getSomeData()
RETURNS trigger
AS $$
begin
import subprocess
subprocess.call(['/usr/bin/python3', '/some_folder/some_sub_folder/get_data.py'])
end;
$$
LANGUAGE plpythonu;

之后,创建触发器

CREATE TRIGGER executePython
AFTER INSERT ON mytable
EXECUTE PROCEDURE getSomeData();

如果我进行任何插入或更新,则不会发生任何事情。

作为额外的预防措施,我做了以下测试

sudo -u postgres python3 /some_folder/some_sub_folder/get_data.py

得到这个输出:

Traceback (most recent call last):
File "/some_folder/some_sub_folder/get_data.py", line 4, in <module>
from sqlalchemy import create_engine
ImportError: No module named sqlalchemy

我已经全局安装了 SQLAlchemy,现在我的脚本在 postgres 用户下按预期运行,但它不会触发。

apt install python3-sqlalchemy

指向bathman提供的解决方案的指针:

when you execute this as your usual user, do you execute it with the global python3, or is there a chance, you have venv or other environment loaded and your usual user python3 executable is an alias to your venv, where you locally installed SQLAlchemy? you could try to execute by /path/to/your/environment/with/sqlalchemy/installed/bin/python3 or installing SQLAlchemy globally so your /usr/bin/python3 has access to it.

解决方法:

CREATE FUNCTION getSomeData()
RETURNS trigger
AS $$
begin
import subprocess
subprocess.call(['/path/to/your/virtual/environment/bin/python3', '/some_folder/some_sub_folder/get_data.py'])
end;
$$ 
LANGUAGE plpythonu;