SQLAlchemy cannot connect to Postgresql on localhost

。_饼干妹妹 提交于 2021-02-19 04:24:45

问题


I'm sure this is such an easy error to fix, if I could only find where it is. This is the error from the Flask app:

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'

From what I've been able to find online, it seems like the problem is that I might not be connecting correctly to the database. The app works fine in Heroku, but not when I run on localhost.

which psql:

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

which postgres:

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

Postgres.app is running on 5432.

I don't know what else to check.

If it's supposed to connect to the same postgres DB on heroku regardless, why would it work on heroku, but not from localhost?

Maybe the app on localhost is using a wrong version of Postgres? I've tried uninstalling them (and only leaving Postgres.app), but I'm not sure if there's anything left on my computer that's causing conflicts. How would I check that? I'd appreciate any help.

EDIT: More info
Segment from the alembic.ini file:

[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

I have a short script that produces the same error: I run python cli.py db_create on

#!/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()

and I get:

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'

回答1:


My guess is that you haven't correctly configured Flask-SQLAlchemy. You have a lot of code that seems like it tries to configure it, but without going through all of it, my guess is that it either is setting up your configuration incorrectly, or setting up your configuration too late.

Make sure that before you call anything that will hit the database (like the db.create_all()) that your app.config["SQLALCHEMY_DATABASE_URI"] is set to the correct URI. It is probably set to None, and that is causing your issue.




回答2:


agree with Mark Hildreth whose answer is 7 years old, took me two days to get here - I was getting such errors:

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'

traceback shows smth like:

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

Finaly with tihs answer i remembered that Flask sometimes need to have set config variables in place. helped a lot thanks - app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get('mysql://root:1234@127.0.0.1/kvadrat?charset=utf8')



来源:https://stackoverflow.com/questions/19690119/sqlalchemy-cannot-connect-to-postgresql-on-localhost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!