Python database WITHOUT using Django (for Heroku)

前端 未结 4 466
误落风尘
误落风尘 2021-02-02 15:54

To my surprise, I haven\'t found this question asked elsewhere. Short version, I\'m writing an app that I plan to deploy to the cloud (probably using Heroku), which will do var

4条回答
  •  既然无缘
    2021-02-02 16:43

    You can get a database provided from Heroku without requiring your app to use Django. To do so:

    heroku addons:add heroku-postgresql:dev
    

    If you need a larger more dedicated database, you can examine the plans at Heroku Postgres

    Within your requirements.txt you'll want to add:

    psycopg2
    

    Then you can connect/interact with it similar to the following:

    import psycopg2
    import os
    import urlparse
    
    urlparse.uses_netloc.append('postgres')
    url = urlparse.urlparse(os.environ['DATABASE_URL'])
    
    conn = psycopg2.connect("dbname=%s user=%s password=%s host=%s " % (url.path[1:], url.username, url.password, url.hostname))
    cur = conn.cursor()
    
    query = "SELECT ...."
    cur.execute(query)
    

提交回复
热议问题