SQLAlchemy无法连接到本地主机上的Postgresql [英] SQLAlchemy cannot connect to Postgresql on localhost

查看:78
本文介绍了SQLAlchemy无法连接到本地主机上的Postgresql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我只能找到它的位置,我敢肯定这是一个容易修复的错误.这是Flask应用中的错误:

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'

根据我在网上可以找到的信息,看来问题是我可能未正确连接到数据库.该应用程序在Heroku中可以正常运行,但在本地主机上运行时却无法正常运行.

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.

其中哪个psql :

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

哪个postgres :

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

Postgres.app在5432上运行.

Postgres.app is running on 5432.

我不知道还要检查什么.

I don't know what else to check.

如果无论如何都要连接到heroku上的同一个postgres DB,为什么它可以在heroku上工作,但不能从localhost上工作呢?

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

也许本地主机上的应用使用了错误的Postgres版本?我尝试卸载它们(仅离开Postgres.app),但是我不确定计算机上是否有任何引起冲突的东西.我将如何检查?我将不胜感激.

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.

更多信息
来自alembic.ini文件的分段:

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

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

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()

我得到:

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'

推荐答案

我的猜测是您没有正确

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.

请确保在调用将要访问数据库的任何内容(例如 db.create_all())之前,已设置 app.config ["SQLALCHEMY_DATABASE_URI"] 正确的URI.可能将其设置为 None (无),这是导致您出现问题的原因.

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.

这篇关于SQLAlchemy无法连接到本地主机上的Postgresql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆