django - sites_query = connection.execute("SELECT domain FROM django_site") psycopg2 没有属性执行
问题描述
当我尝试启动 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' 对象没有属性 '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()
推荐阅读
- python - Django 正则表达式字段查找 - 按查询集中每个项目的匹配数排序
- windowsiot - Windows IoT 中的凭据管理器
- video-capture - Camstudio 仍然是一个活跃的项目吗?
- php - 检查版本字符串是否更新的函数(例如 1.2.5 > 1.1.10)
- python - 在 Python 3.6 中使用 json 加载会产生“ascii 编解码器无法编码字符”错误
- ruby-on-rails-3 - Select2 I18n 占位符导轨
- docker - 在ups中使用docker部署生产服务器是个好主意吗?
- node.js - 将多个 Nodejs 应用程序配置到 nginx conf
- ruby-on-rails - 如何将类添加到 Rails 中的 simple_form 输入包装器?
- mysql - SQL使用下一个序列值创建表格式:'for'附近的语法不正确