Search code examples
pythonpostgresqlherokuflaskinternal-server-error

How to fix internal server error when loading my database page (Flask/Heroku)?


I have a very basic Heroku web app where you can click on links (on the main page) to be redirected to other pages. I have done this to test the database page. All the pages work apart from when I click to view the database page. when I try I get an error message:

Internal Server Error
The server encountered an internal error and was unable to complete your request.
Either the server is overloaded or there is an error in the application.

I did try to play around with the procfile but in the end nothig worked. My current proctfile looks like this:

web: gunicorn flask-sqlalchemy-test-02.wsgi:application --log-file=-

To be honest I'm not too sure if its the procfile or the sytax in app.py which is causing me problems.

My app.py file:

import os
import psycopg2
from flask import Flask, render_template, g, url_for

app = Flask(__name__)
DATABASE_URL = os.environ.get('postgres://fikwczdiymxhwf:73bf42c2c8a15fa59b77e93654b6383e1cf4f85bdf0156818d1cf39a77815f13@ec2-54-243-47-196.compute-1.amazonaws.com:5432/d3uburco4fea1b'

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

@app.route('/page2')
def page_2():
    return render_template("random_page_2.html")

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

@app.route('/view_database')
def view_db():
    conn = psycopg2.connect(DATABASE_URL)
    db = conn.cursor()
    data = db.execute("SELECT * FROM example").fetchall()
    db.close()
    conn.close()
    return render_template('view_database.html', data=data)

I expected to view the database in a form of an unordered list but recieved an error message instead:

Internal Server Error
The server encountered an internal error and was unable to complete your request.
Either the server is overloaded or there is an error in the application.


Solution

  • The way you are using os.environ.get() is wrong.

    os.environ.get() is used to obtain environment variables that are exported by your OS, so DATABASE_URL returns None, you cannot connect to None URL, so internal server error.

    **Correct Way : ** First, export the environment variable, if using Linux :

    export DATABASE_URL=postgres://fikwczdiymxhwf:73bf42c2c8a15fa59b77e93654b6383e1cf4f85bdf0156818d1cf39a77815f13@ec2-54-243-47-196.compute-1.amazonaws.com:5432/d3uburco4fea1b
    

    Then, in your code, replace that line as :

    DATABASE_URL = os.environ.get('DATABASE_URL', '')