PostgreSQL PL / Python:在virtualenv中调用存储过程

当我在我的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'))

并作为一个完全实现的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,因为认情况下,plpy在plpython os.environ中不可用 –
activate_this.py有一个fix checked in应该下一个点发布(应该是1.11.7或1.12)

(主要来自https://gist.github.com/dmckeone/69334e2d8b27f586414a)

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...