gpt4 book ai didi

django - sites_query = connection.execute ("SELECT domain FROM django_site") psycopg2 没有属性 execute

转载 作者:行者123 更新时间:2023-12-05 02:56:38 24 4
gpt4 key购买 nike

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

File "/home/django-project/projectfolder/settings.py", line 270, in ALLOWED_HOSTS = get_allowed_hosts(DATABASES['default']) File "/home/django-project/projectfolder/allowed_hosts.py", line 16, in get_allowed_hosts sites_query = connection.execute("SELECT domain FROM django_site") AttributeError: 'psycopg2.extensions.connection' object has no attribute 'execute

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

最佳答案

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

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

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

cursor.close()
connection.close()

关于django - sites_query = connection.execute ("SELECT domain FROM django_site") psycopg2 没有属性 execute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60241842/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com