PostgreSQL PL/Python: call stored procedure in virtualenv

早过忘川 提交于 2019-12-03 17:31:40

There is a way to do it, as it turns out. Since version 1.6 or there abouts, virtualenv comes with a script activate_this.py, which can be used to set up an existing interpreter to access that particular virtualenv.

exec(open('/Some/VirtualEnv/Directory/myvirtualenv/bin/activate_this.py').read(), 
dict(__file__='/Some/VirtualEnv/Directory/myvirtualenv/bin/activate_this.py'))

And as a fully-realized plpython function:

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

(The extra PATH mungery is needed since by default PATH isn't available in plpython os.environ - activate_this.py has a fix checked in that should roll w/ the next point release (which should be 1.11.7 or 1.12)

( taken mostly from https://gist.github.com/dmckeone/69334e2d8b27f586414a )

Karlson

Normally I'd say it's not really a good idea but you may be able to follow this question.

What you could do is run multiple instances of PostgreSQL with different environments to allow for various PYTHONPATH settings.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!