Skip to content
Advertisement

Can’t access Postgres DB on Heroku app

I have a Python 2.7 / Flask app running on Heroku that scrapes data and I now want to store that information in a database.

I’ve tried to follow tutorials like this one and apply this to my case but I can’t get it to work. I have created & promoted my postgres database successfully on heroku.

I am fairly new to the Python project architecture and I suspect a simple problem in my setup.

Here is my project structure

/myapplication
    Procfile
    run.py
    requirements.txt
    /app
        __init__.py
        mechanize_boilerplate.py
        views.py
        /static
        /templates

Here is my init.py

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os

app = Flask(__name__)
# DB Configuration
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('postgres://{link I got from heroku}')
db = SQLAlchemy(app)


from app import views

Here is a portion of my views.py

from app import app
import mechanize_boilerplate
import os
from flask import Flask, render_template, request
from app import db

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))
    email = db.Column(db.String(120), unique=True)

    def __init__(self, name, email):
        self.name = name
        self.email = email

    def __repr__(self):
        return '<Name %r>' % self.name

@app.route('/db')
def dbtest():
    try:
        user = User('John', 'Foo@bar.com')
        db.session.add(user)
        db.session.commit()
    except:
        print 'DB error'
    return 'done'

Basically when I visit myapp/db I want to create one record with id, name and email (john, foo@bar.com).

Any thoughts?

Advertisement

Answer

It should be os.environ.get('DATABASE_URL')

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement