2016-10-21 60 views
0

我在Heroku上運行一個龍捲風應用程序,並且所有操作都已經完成,直到這一點,我試圖添加一個Heroku Postgres插件。在這一點上,我可以使用Heroku's python guide本地連接,而導出DATABASE_URL=postgres:///$(whoami),如here所示。然而,當我從heroku config:get DATABASE_URL給出的DATABASE_URL運行heroku local,我得到了如下的堆棧跟蹤:在Tornado中Heroku的Postgres連接問題

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

回答

0

嗯,事實證明我今天想成爲一個白癡。如果有人對這個答案感興趣,請在connect_to_dbconnection函數中,我把database=url.path[1:0]而不是database=url.path[1:]。實際上,我沒有指定數據庫。