【问题标题】:sites_query = connection.execute("SELECT domain FROM django_site") psycopg2 has no attribute executesites_query = connection.execute("SELECT domain FROM django_site") psycopg2 没有属性执行
【发布时间】:2020-05-31 04:03:22
【问题描述】:

当我尝试启动 gunicorn 时,出现此错误:

文件“/home/django-project/projectfolder/settings.py”,第 270 行,在 ALLOWED_HOSTS = get_allowed_hosts(DATABASES['default']) 文件“/home/django-project/projectfolder/allowed_hosts.py”,第 16 行,在 get_allowed_hosts sites_query = connection.execute("SELECT domain FROM django_site") AttributeError:“psycopg2.extensions.connection”对象没有属性“执行”

from .settings import *

DEBUG = False


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'projectname_settings',
        'USER': '******',
        'PASSWORD': '******',
        'HOST': 'localhost',
        'PORT': '',
    }
}

ALLOWED_HOSTS = [
    "mydomain.com",
] + get_allowed_hosts(DATABASES['default'])

Allowed_hosts.py

def get_allowed_hosts(db_params):
    connection = None

    if db_params['ENGINE'] == 'django.db.backends.postgresql_psycopg2':
        import psycopg2
        connection = psycopg2.connect(user=db_params['USER'],
                                      password=db_params['PASSWORD'],
                                      host=db_params['HOST'],
                                      port=db_params['PORT'],
                                      database=db_params['NAME'])
    elif db_params['ENGINE'] == 'django.db.backends.sqlite3':
        import sqlite3
        connection = sqlite3.connect(db_params['NAME'])

    if connection is not None:
        sites_query = connection.execute("SELECT domain FROM django_site")
        sites_result = sites_query.fetchall()
        sites = ["." + site[0] for site in sites_result]
        print("Allowed hosts")
        print(sites)
        return sites

【问题讨论】:

  • DOMAIN 是 SQL 中的(非保留)关键字。最好不要将其用作标识符。 postgresql.org/docs/12/sql-keywords-appendix.html
  • @wildplasser 谢谢,你有没有看到任何会导致 502 错误的东西?这种允许主机的机制是否需要特殊的 nginx/wsgi 配置?

标签: django postgresql gunicorn psycopg2 django-settings


【解决方案1】:

您应该使用cursor 对象来执行查询:

cursor = connection.cursor()
sites_query = cursor.execute("SELECT domain FROM django_site")
sites_result = cursor.fetchall()

获取数据后不要忘记关闭连接:

cursor.close()
connection.close()

【讨论】:

  • 我收到一个缩进错误:cursor = connection.cursor() ^ TabError: inconsistent use of tabs and spaces in indentation 甚至认为我已经添加了与 site_query 相同级别的行
  • @MoAlgh 可能您使用的是制表符而不是空格。还要检查所有代码块的意图。
  • 错误已解决,现在我收到 502 Bad Gateway 错误。这是它的一部分吗?
  • 我已经运行了所有这些命令sudo systemctl daemon-reload sudo systemctl restart gunicorn sudo systemctl restart nginx
  • 很难说没有额外的数据。尝试使用 DEBUG=True 设置在本地运行它以查看实际的错误消息。
猜你喜欢
  • 2019-07-22
  • 2019-05-24
  • 1970-01-01
  • 2018-10-24
  • 2014-02-14
  • 1970-01-01
  • 2023-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多