使用Django检查postgres数据库是否存在抛出操作系统错误。

2024-04-19 02:10:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个django应用程序在虚拟环境中运行,使用supervisor。主管由root运行,应用程序由用户ubuntu运行。你知道吗

我想检查postgres中是否有数据库。我下面的函数在普通的pythonshell(Repl)中工作得很好,甚至在我使用python migrate.py runserver运行应用程序时,甚至在djangoshell中也工作得很好。你知道吗

但是,当我使用supervisor启动应用程序并执行该代码块时,会出现以下异常-

Exception Type: OSError Exception Value:[Errno 2] No such file or directory

下面的函数是

def database_exists(database_name):
    try:
         db= "anydbname"
         c1 = "psql -U postgres -lqt"
         c2 = "cut -d | -f 1"
         c3 = "grep -w " + db              

         ps1 = subprocess.Popen(c1.split(),stdout=subprocess.PIPE)
         ps2 = subprocess.Popen(c2.split(),stdin=ps1.stdout, stdout=subprocess.PIPE)
         ps3 = subprocess.Popen(c3.split(),stdin=ps2.stdout , stdout=subprocess.PIPE)
         result = ps3.communicate()[0]  # if empty , db not found 
         result = result.strip()
         if result == "" :
             return False
         else :
             return True 
    except Exception, e:
        raise e
        return False, str(e)

我无法理解它想要的确切目录或文件是什么找到。是吗有什么权限问题吗?但是即使是普通的shell也是使用ubuntu用户运行的,所以看起来并不是权限错误。如何调试它在运行时找不到哪个文件?我在supervisor中添加了日志,但它只显示<request url > HTTP/1.0" 500,所以没有任何线索。你知道吗

这是主管

[program:myprog]
environment=PATH="/home/ubuntu/.virtualenvs/myvirtualenv/bin"
command=python /var/www/myapp/manage.py rungevent 127.0.0.1:8010 250
directory=/var/www/myapp
autostart=true
autorestart=true
redirect_stderr=True
killasgroup=true
stopasgroup=true
user=ubuntu
stdout_logfile = /var/log/supervisor/myapp.log
stderr_logfile = /var/log/supervisor/myapp-err.log

Tags: logtrue应用程序dbvarubuntustdoutexception
2条回答

问题出在管理器配置上。它试图找到psql,却没有找到它的路径。原因是supervisor conf中的路径变量错误。这是正确的设置,效果很好。你知道吗

更改:删除了PATH,并指定了virtualenv的python的完整可执行路径。你知道吗

[program:myprog]
command=/home/ubuntu/.virtualenvs/myvirtualenv/bin/python /var/www/myapp/manage.py rungevent 127.0.0.1:8010 250
directory=/var/www/myapp
autostart=true
autorestart=true
redirect_stderr=True
killasgroup=true
stopasgroup=true
user=ubuntu
stdout_logfile = /var/log/supervisor/myapp.log
stderr_logfile = /var/log/supervisor/myapp-err.log

您不需要如此复杂的方法来测试数据库的存在性。试试这个:

import psycopg2

def database_exists(database_name):
    con = None
    res = None
    try:
        con = psycopg2.connect(database="test", user="test", password="abcd", host="127.0.0.1") #It's better to get the parameters from settings
        cur = con.cursor()
        cur.execute("SELECT exists(SELECT 1 from pg_catalog.pg_database where datname = %s)", (database_name,))
        res = cur.fetchone()[0]
    except psycopg2.DatabaseError as e:
        res = False
    finally:
        if con:
            con.close()
    return res

相关问题 更多 >