How to upload a simple web on Heroku, app consisting of Peewee and Postgres?

157 views Asked by At

I have a app.py file. I am trying to upload on HEROKU. I have seen some changes needed to be made while uploading on Heroku like adding Procfile and Requirements.txt. I have also added those two. Its working perfectly on local but on Heroku database is not creating or connecting.

What I am doing on my terminal

  1. heroku create
  2. git push heroku master
  3. heroku addons:add heroku-postgresql
  4. heroku config:set HEROKU=1
  5. heroku ps:scale web=1
  6. heroku open

Now here my web page for user registration is opening but not able to save. Please help

app.py

import os
import urlparse
import psycopg2
from peewee import Model, CharField, SqliteDatabase, CharField, ForeignKeyField, IntegrityError
from peewee import create_model_tables
from flask import Flask, request, render_template, redirect, url_for, session
from passlib.hash import sha256_crypt
from flask_bootstrap import Bootstrap
from flask_peewee.db import Database

if 'HEROKU' in os.environ:
    DEBUG = False
    urlparse.uses_netloc.append('postgres')
    url = urlparse.urlparse(os.environ['DATABASE_URL'])
    DATABASE = {
        'engine': 'peewee.PostgresqlDatabase',
        'name': url.path[1:],
        'user': url.username,
        'password': url.password,
        'host': url.hostname,
        'port': url.port,
    }
else:
    DEBUG = True
    DATABASE = {
        'engine': 'peewee.PostgresqlDatabase',
        'name': 'notes',
        'user': 'scrolldev',
        'password': 'scrolldev',
        'host': 'localhost',
        'port': 5432,
        'threadlocals': True
    }


app = Flask(__name__)
bootstrap = Bootstrap(app)
app.config.from_object(__name__)
db = Database(app)


class User(db.Model):
    ....


class Notepad(db.Model):
    ....

def setup_db():
    create_model_tables([User, Notepad], fail_silently=True)

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

Before putting this question I also took help from here and then I updated my file Stack Question

Update Its working correctly in local but on heroku its not. Please help me.

1

There are 1 answers

1
Chris On

Your code loads url from the DATABASE_URL environment variable if 'HEROKU' is contained in os.environ

if 'HEROKU' in os.environ:
    DEBUG = False
    urlparse.uses_netloc.append('postgres')
    url = urlparse.urlparse(os.environ["DATABASE_URL"])

…but it also loads it outside of your conditional a few lines earlier:

from peewee import Model, PostgresqlDatabase

urlparse.uses_netloc.append('postgres')
url = urlparse.urlparse(os.environ['DATABASE_URL'])  # <--

Based on your comments above it sounds like this is a mistake. Either set DATABASE_URL on your development machine (which I recommend; the fewer changes you have between development and production the better), or remove the code that sets url outside of your if block.