当我在我的 Python 应用程序中调用 PostgreSQL PL/Python 存储过程时,它似乎是在以用户 postgres
身份运行的单独进程中执行的。到目前为止,这只有副作用,我必须让我的日志文件对我自己和数据库用户都可写,这样应用程序和存储过程都可以写入它。
但是现在,我开始使用 virtualenv
并将一些 .pth
文件添加到我的 ~/.virtualenvs/virt_env/lib/python2.7/site-packages/
文件夹中,将我的模块的路径添加到Python 路径。
执行存储过程时,用户postgres
和我不在同一个虚拟环境中,所以存储过程没有找到我的模块。我可以在 global PostgreSQL environment 中修改 PYTHONPATH
,但每次切换虚拟环境时我都必须更改它 - 这有点违背 virtualenv 的目的...
如何扩展存储过程的 Python 路径?
更新:
A similar question已被问及解决方案是修改 Postgres 中的 PYTHONPATH 环境变量;然而,似乎there is no standard way to specify environment variables for PostgreSQL ;至少,它在 Mac OSX 上不是一个可行的解决方案。
最佳答案
事实证明,有一种方法可以做到这一点。从 1.6 或左右版本开始,virtualenv 附带了一个脚本 activate_this.py
,可用于设置现有的解释器以访问特定的 virtualenv。
exec(open('/Some/VirtualEnv/Directory/myvirtualenv/bin/activate_this.py').read(),
dict(__file__='/Some/VirtualEnv/Directory/myvirtualenv/bin/activate_this.py'))
作为一个完全实现的 plpython 函数:
CREATE OR REPLACE FUNCTION workon(venv text)
RETURNS void AS
$BODY$
import os
import sys
if sys.platform in ('win32', 'win64', 'cygwin'):
activate_this = os.path.join(venv, 'Scripts', 'activate_this.py')
else:
if not os.environ.has_key('PATH'):
import subprocess
p=subprocess.Popen('echo -n $PATH', stdout=subprocess.PIPE, shell=True)
(mypath,err) = p.communicate()
os.environ['PATH'] = mypath
activate_this = os.path.join(venv, 'bin', 'activate_this.py')
exec(open(activate_this).read(), dict(__file__=activate_this))
$BODY$
LANGUAGE plpythonu VOLATILE
(需要额外的 PATH mungery,因为默认情况下 PATH 在 plpython os.environ 中不可用 - activate_this.py 有一个 fix checked in应该与下一个点版本一起滚动(应该是 1.11.7 或 1.12)
(主要取自 https://gist.github.com/dmckeone/69334e2d8b27f586414a )
关于python - PostgreSQL PL/Python : call stored procedure in virtualenv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9586331/