0

I am really new to Python and Heroku. I am currently running the following build:

  1. Windows 10
  2. A postgre SQL database created on Heroku remotely. This is a free plan.

I want to create a table in the remote database. The code I am trying to execute is:

import os
import psycopg2


DATABASE_URL = os.environ['DATABASE_URL']

conn = psycopg2.connect(
    DATABASE_URL,
    sslmode="require",
    host="xxx",
    port="xxx",
    user="xxx",
    password="xxx",
    database="xxx")

def main():

 sql = """CREATE TABLE books

 (
  id SERIAL PRIMARY KEY,
  ISBN Varchar NOT NULL,
  Title Varchar NOT NULL,
  Author Varchar NOT NULL,
  Year Integer NOT NULL

);"""

conn.close()

if __name__ == '__main__':
    main()

The error that I get is

 Traceback (most recent call last):
  File "import.py", line 12, in <module>
    DATABASE_URL = os.environ['Database_URL']
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python37-32\lib\os.py", line 678, in __getitem__
    raise KeyError(key) from None
KeyError: 'Database_URL

' pip freeze output

Click==7.0
Flask==1.0.2
Flask-Session==0.3.1
itsdangerous==1.1.0
Jinja2==2.10
MarkupSafe==1.1.0
numpy==1.16.1
pandas==0.24.1
psycopg2==2.7.7
psycopg2-binary==2.7.7
python-dateutil==2.8.0
pytz==2018.9
six==1.12.0
SQLAlchemy==1.2.17
Werkzeug==0.14.1
Hector M
  • 47
  • 4
  • I wonder why you bleeped out `os.environ['XXX']` but you kept the stack trace, which clearly show's what's wrong `os.environ['Database_URL']`. Where `Database_URL` is missing from your environment variable. – Torxed Feb 14 '19 at 16:06
  • Thanks for your reply. Replaced xxx. How do I fix it? – Hector M Feb 14 '19 at 16:10
  • Well, on Windows you would need to call [SET Database_URL=string](https://ss64.com/nt/set.html) before running your command. Or make a permanent variable in your environment variables (for instance, where you find the `PATH` variable). Or switch to [argparse](https://stackoverflow.com/questions/7427101/simple-argparse-example-wanted-1-argument-3-results) and give your script some arguments that it can use. Then call your script with `python.exe script.py --Database_URL="some url"`. – Torxed Feb 14 '19 at 16:24
  • In the Heroku dashboard under the settings tab, you can set the *Config Vars* for the app. If you created the database on Heroku, then you just copy it's url to the config var section. – ryentzer Feb 14 '19 at 18:48
  • Thanks Torxed and ryentzer. I got this resolved by looking at psycopg documentation. It was an issue with code syntax. – Hector M Feb 16 '19 at 10:05

0 Answers0