1

Im writing a dummy website for class and I'm having trouble connecting my Heroku Database to my app that's local for now until I push to Heroku.

I'm not sure what the proper way to do this, and I've searched many videos/forums and I can't seem to get a straight answer from them. Ill post some of my code below. In dbconnect.py where the insert the heroku database credentials, like the URI, host, etc?

#app.py
from flask import Flask, render_template, redirect, url_for, request, session, flash
from functools import wraps


app = Flask(__name__)

app.secret_key = "Gundam"

# login required decorator
def login_required(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        if 'logged_in' in session:
            return f(*args, **kwargs)
        else:
            flash('You need to login first.')
            return redirect(url_for('login_page'))
    return wrap


@app.route('/')    
def homepage():
    return render_template("main.html")

@app.route('/dashboard/')
@login_required
def dashboard():
    return render_template("dashboard.html")    

@app.errorhandler(404)
def page_not_found(e):
    return render_template("404.html")

@app.route('/login/', methods=["GET", "POST"])    
def login_page():    
    error = ''
    try:
        if request.method == "POST":
            attempted_username = request.form['username']
            attempted_password = request.form['password']

            if attempted_username == "admin" and attempted_password == "password":
                session['logged_in'] = True
                flash('You were just logged in!')
                return redirect(url_for('dashboard'))
            else:
                error = "Invalid Username or Password."    
        return render_template("login.html", error=error)        
    except Exception as e:    
        return render_template("login.html", error=error)

@app.route('/logout/')
def logout():
    session.pop("logged_in", None)        
    return redirect(url_for('homepage'))



if __name__ == '__main__':
    app.run(debug = True)


dbconnect.py

import os
import psycopg2
import urlparse

urlparse.uses_netloc.append("postgres")
url = urlparse.urlparse(os.environ[""])

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

2 Answers 2

2

You have to install the postgres database addon in heroku first. Run the heroku toolbelt in your computer and enter the command heroku addons:create heroku-postgresql:hobby-dev. Hobby-dev is the free version.

Once Heroku Postgres has been added a DATABASE_URL setting will be available in the app configuration and will contain the URL used to access the newly provisioned Heroku Postgres service. Use the value as your database uri. The app configuration can be accessed from your dashboard. Under settings, click Reveal config vars. You can also use the toolbelt command. See heroku config -h.

So now you can do:

url = urlparse.urlparse(os.environ["DATABASE_URL"])

For more details see https://devcenter.heroku.com/articles/heroku-postgresql

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the reply. I did all that already. I'm just having trouble figuring out what the code is to link the db to my app
Have you tried url = urlparse.urlparse(os.environ["DATABASE_URL"]). That should get the database url from heroku environment variables.
1

Just use the following code snippet on your python app. That should do the trick.

import os
import psycopg2


DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL, sslmode='require')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.