SQLAlchemy无法连接本地Postgresql数据库

3

我相信这应该是一个很容易修复的错误,只要我能找到它在哪里。这是来自 Flask 应用程序的错误:

11:58:18 web.1  | ERROR:xxxxxx.core:Exception on / [GET]
11:58:18 web.1  | Traceback (most recent call last):
11:58:18 web.1  |   File "/Library/Python/2.7/site-packages/flask/app.py", line 1817, in wsgi_app
11:58:18 web.1  |     response = self.full_dispatch_request()
11:58:18 web.1  |   File "/Library/Python/2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
11:58:18 web.1  |     rv = self.handle_user_exception(e)
11:58:18 web.1  |   File "/Library/Python/2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
11:58:18 web.1  |     reraise(exc_type, exc_value, tb)
11:58:18 web.1  |   File "/Library/Python/2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
11:58:18 web.1  |     rv = self.dispatch_request()
11:58:18 web.1  |   File "/Library/Python/2.7/site-packages/flask/app.py", line 1461, in dispatch_request
11:58:18 web.1  |     return self.view_functions[rule.endpoint](**req.view_args)
11:58:18 web.1  |   File "xxxxxxx/web.py", line 202, in home
11:58:18 web.1  |     d = {'featured': cached_apps.get_featured_front_page(),
11:58:18 web.1  |   File "/Library/Python/2.7/site-packages/flask_cache/__init__.py", line 245, in decorated_function
11:58:18 web.1  |     rv = f(*args, **kwargs)
11:58:18 web.1  |   File "/Users/xxxxxxx/Desktop/PythonProjects/xxxxxx/xxxxxx2/xxxxxxx/cache/apps.py", line 35, in get_featured_front_page
11:58:18 web.1  |     results = db.engine.execute(sql)
11:58:18 web.1  |   File "/Library/Python/2.7/site-packages/flask_sqlalchemy/__init__.py", line 780, in engine
11:58:18 web.1  |     return self.get_engine(self.get_app())
11:58:18 web.1  |   File "/Library/Python/2.7/site-packages/flask_sqlalchemy/__init__.py", line 797, in get_engine
11:58:18 web.1  |     return connector.get_engine()
11:58:18 web.1  |   File "/Library/Python/2.7/site-packages/flask_sqlalchemy/__init__.py", line 470, in get_engine
11:58:18 web.1  |     self._sa.apply_driver_hacks(self._app, info, options)
11:58:18 web.1  |   File "/Library/Python/2.7/site-packages/flask_sqlalchemy/__init__.py", line 739, in apply_driver_hacks
11:58:18 web.1  |     if info.drivername.startswith('mysql'):
11:58:18 web.1  | AttributeError: 'NoneType' object has no attribute 'drivername'

根据我在网上查到的信息,问题似乎是我可能没有正确连接到数据库。应用在Heroku上运行良好,但在本地主机上运行时出现问题。

which psql

/Applications/Postgres.app/Contents/MacOS/bin/psql

which postgres:

/Applications/Postgres.app/Contents/MacOS/bin/postgres

编辑:更多信息
alembic.ini文件的一部分:

[alembic]
# path to migration scripts
script_location = alembic

# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

# under Heroku, the line below needs to be inferred from
# the environment
sqlalchemy.url = postgres://xxxxxxxxxx:xxxxxxxxxxxx@xxxxxx.compute-1.amazonaws.com:5432/xxxxxxxxx

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

我有一个简短的脚本,会产生相同的错误: 我运行 python cli.py db_create

#!/usr/bin/env python
import os
import sys
import optparse
import inspect

import xxxxxxx.model as model
from xxxxxx.core import db
import xxxxx.web as web

from alembic.config import Config
from alembic import command    
def setup_alembic_config():
    if "DATABASE_URL" not in os.environ:
        alembic_cfg = Config("alembic.ini")
    else:
        dynamic_filename = "alembic-heroku.ini"
        with file("alembic.ini.template") as f:
            with file(dynamic_filename, "w") as conf:
                for line in f.readlines():
                    if line.startswith("sqlalchemy.url"):
                        conf.write("sqlalchemy.url = %s\n" %
                                   os.environ['DATABASE_URL'])
                    else:
                        conf.write(line)
        alembic_cfg = Config(dynamic_filename)

    command.stamp(alembic_cfg, "head")

def db_create():
    '''Create the db'''
    db.create_all()
    # then, load the Alembic configuration and generate the
    # version table, "stamping" it with the most recent rev:
    setup_alembic_config()
    # finally, add a minimum set of categories: Volunteer Thinking, Volunteer Sensing, Published and Draft
    categories = []
    categories.append(model.Category(name="Thinking",
                                     short_name='thinking',
                                     description='Volunteer Thinking apps'))
    categories.append(model.Category(name="Volunteer Sensing",
                                     short_name='sensing',
                                     description='Volunteer Sensing apps'))
    db.session.add_all(categories)
    db.session.commit()

然后我得到:

Traceback (most recent call last):
  File "cli.py", line 111, in <module>
    _main(locals())
  File "cli.py", line 106, in _main
    _methods[method](*args[1:])
  File "cli.py", line 33, in db_create
    db.create_all()
  File "/Library/Python/2.7/site-packages/flask_sqlalchemy/__init__.py", line 856, in create_all
    self._execute_for_all_tables(app, bind, 'create_all')
  File "/Library/Python/2.7/site-packages/flask_sqlalchemy/__init__.py", line 848, in _execute_for_all_tables
    op(bind=self.get_engine(app, bind), tables=tables)
  File "/Library/Python/2.7/site-packages/flask_sqlalchemy/__init__.py", line 797, in get_engine
    return connector.get_engine()
  File "/Library/Python/2.7/site-packages/flask_sqlalchemy/__init__.py", line 470, in get_engine
    self._sa.apply_driver_hacks(self._app, info, options)
  File "/Library/Python/2.7/site-packages/flask_sqlalchemy/__init__.py", line 739, in apply_driver_hacks
    if info.drivername.startswith('mysql'):
AttributeError: 'NoneType' object has no attribute 'drivername'

你能否编辑你的问题并包含你的Flask配置(当然,要过滤掉任何敏感信息)? - Mark Hildreth
2个回答

9
我的猜测是你没有正确地配置Flask-SQLAlchemy。你有很多代码似乎试图去配置它,但没有深入了解所有内容,我猜测要么是设置了不正确的配置,要么是设置了太晚的配置。
在调用任何会访问数据库的东西(比如db.create_all())之前,请确保你的app.config["SQLALCHEMY_DATABASE_URI"]已经设置为正确的URI。它可能被设置成了None,这就是导致你问题的原因。

你说得绝对没错。我发现SQLALCHEMY_DATABASE_URI被设置成了os.environ.get('DATABASE_URL'),但这个URL在任何地方都不存在。于是我创建了一个.env文件来包含这个URL。非常感谢! - luisdaniel

0

同意 Mark Hildreth 的答案,虽然已经是 7 年前的回答了,但我也花了两天时间才找到这里 -

我一直在遇到这样的错误:

FAILED tests/test_models.py::test_endpoint - AttributeError: 'NoneType' object has no attribute 'drivername'

ERROR tests/test_models.py::test_endpoint2 - AttributeError: 'NoneType' object has no attribute 'response_class'

回溯显示类似于:

self = <[AttributeError("'NoneType' object has no attribute 'drivername'") raised in repr()] SQLAlchemy object at 0x1fb8a622848>, app = <Flask 'app'>, sa_url = None, options = {}

最终,通过这个答案,我记起了 Flask 有时需要设置配置变量。 非常感谢帮忙 - app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get('mysql://root:1234@127.0.0.1/kvadrat?charset=utf8')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接