在龙卷风中与Heroku的Postgres连接问题

时间:2016-10-21 01:18:54

标签: postgresql python-3.x heroku tornado

我正在Heroku上运行龙卷风应用程序,并且一切都进展顺利,直到这一点,我正在尝试添加一个Heroku Postgres附加组件。此时,我可以使用Heroku's python guide在本地连接,同时导出DATABASE_URL=postgres:///$(whoami),如图所示here。但是,当我使用heroku local提供的DATABASE_URL运行heroku config:get DATABASE_URL时,我会得到以下堆栈跟踪:

[OKAY] Loaded ENV .env File as KEY=VALUE Format
5:48:26 PM web.1 |  Traceback (most recent call last):
5:48:26 PM web.1 |    File "src/myapp/app.py", line 61, in <module>
5:48:26 PM web.1 |      main()
5:48:26 PM web.1 |    File "src/myapp/app.py", line 55, in main
5:48:26 PM web.1 |      app = MyApplication()
5:48:26 PM web.1 |    File "src/myapp/app.py", line 35, in __init__
5:48:26 PM web.1 |      self.db = self.connect_to_db()
5:48:26 PM web.1 |    File "src/myapp/app.py", line 49, in connect_to_db
5:48:26 PM web.1 |      port=url.port
5:48:26 PM web.1 |    File "/usr/lib/python3/dist-packages/psycopg2/__init__.py", line 164, in connect
5:48:26 PM web.1 |      conn = _connect(dsn, connection_factory=connection_factory, async=async)
5:48:26 PM web.1 |  psycopg2.OperationalError: FATAL:  database "heroku_username" does not exist

我运行龙卷风应用程序的代码如下所示:

from os import environ

from psycopg2 import connect

from tornado.ioloop import IOLoop
from tornado.options import define
from tornado.options import options
from tornado.options import parse_command_line
from tornado.web import Application

from urllib.parse import urlparse
from urllib.parse import uses_netloc


define('debug', default=True, help='debug is on or not')
define('port', default=8888, help='run on given port', type=int)


class MyApplication(Application):

    def __init__(self):
        handlers = [
            (r'/health', HealthCheckHandler)
        ]
        settings = dict(debug=options.debug)

        self.db = self.connect_to_db()
        Application.__init__(self, handlers, **settings)

    def connect_to_db(self):
        """Connects to the database instance."""
        uses_netloc.append('postgres')
        url = urlparse(environ['DATABASE_URL'])
        print(url.username)

        conn = connect(
            database=url.path[1:0],
            user=url.username,
            password=url.password,
            host=url.hostname,
            port=url.port
        )


def main():
    parse_command_line()
    app = MyApplication()
    app.listen(options.port)
    IOLoop.current().start()


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

嗯,事实证明我今天想成为一个白痴。如果有人对答案感兴趣,请在connect_to_db函数的connection中,将database=url.path[1:0]代替database=url.path[1:]。实际上,我没有指定数据库。