当我在我的Python应用程序中调用Postgresql PL / Python存储过程时,它似乎在作为用户postgres运行的单独进程中执行.到目前为止,这只会产生副作用,我必须使我的日志文件对我自己和数据库用户都可写,因此应用程序和存储过程都可以写入它.
然而,现在我开始使用virtualenv
并在我的〜/ .virtualenvs / virt_env / lib / python2.7 / site-packages /文件夹中添加了许多.pth文件,这些文件将我的模块的路径添加到Python路径中.
执行存储过程时,用户postgres与我不在同一个虚拟环境中,因此存储过程找不到我的模块.我可以在global PostgreSQL environment中修改PYTHONPATH,但每次切换虚拟环境时我都要改变它 – 这有点违背了virtualenv的目的……
如何扩展存储过程的Python路径?
更新:
已经询问了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'))
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,因为默认情况下,plpy在plpython os.environ中不可用 –
activate_this.py有一个fix checked in应该下一个点发布(应该是1.11.7或1.12)