Django测试应用程序错误-创建测试数据库时出错:创建数据库的权限被拒绝

2024-05-18 17:41:42 发布

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

当我尝试使用命令测试任何应用程序时(我注意到当我尝试使用fabric部署我的项目时,fabric使用此命令):

python manage.py test appname

我得到这个错误:

Creating test database for alias 'default'...
Got an error creating the test database: permission denied to create database

Type 'yes' if you would like to try deleting the test database 'test_finance', or 'no' to cancel

syncdb命令似乎有效。settings.py中的“我的数据库设置”:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'finance',                      # Or path to database file if using sqlite3.
        'USER': 'django',                      # Not used with sqlite3.
        'PASSWORD': 'mydb123',                  # Not used with sqlite3.
        'HOST': '127.0.0.1',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

Tags: thetopytest命令defaultforif
3条回答

对于Postgres,用户必须具有createdb权限。

ALTER ROLE miriam CREATEDB;

请参阅此文档:https://docs.djangoproject.com/en/2.0/topics/testing/overview/#the-test-database

我找到了解决你问题的有趣办法。
实际上,对于MySQL,您可以为不存在的数据库授予特权。
因此,您可以在设置中为测试数据库添加名称“test_finance”:

    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'finance',                      # Or path to database file if using sqlite3.
        'USER': 'django',                      # Not used with sqlite3.
        'PASSWORD': 'mydb123',                  # Not used with sqlite3.
        'HOST': '127.0.0.1',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
        'TEST': {
            'NAME': 'test_finance',
        },
    }
}

以根用户身份启动MySQL shell:

mysql -u root -p

现在授予MySQL中这个不存在的数据库的所有权限:

GRANT ALL PRIVILEGES ON test_finance.* TO 'django'@'localhost';

现在Django将开始测试,没有任何问题。

当Django运行测试套件时,它会创建一个新的数据库,在您的情况下是test_finance。用户名为django的postgres用户没有创建数据库的权限,因此出现错误消息。

当您运行migratesyncdb时,Django不会尝试创建finance数据库,因此不会出现任何错误。

您可以将createdb权限添加到django用户,方法是以超级用户身份在postgres shell中运行以下命令(hat tip to this stack overflow answer)。

=> ALTER USER django CREATEDB;

注意:命令中使用的用户名需要与Django设置文件中的数据库用户匹配。在这种情况下,最初的海报,有用户作为django以上的答案。

相关问题 更多 >

    热门问题