Django + Heroku - To avoid error when deploying

As the previous blog post, I posted a setting snippet to let Django know where the db is (local and in Heroku): http://iambusychangingtheworld.blogspot.com/2013/10/django-heroku-local-and-heroku-database.html

Today, I found someone has create another snippet which is much more clever and useful:

Deploying Django to Heroku (Psycopg2 Error)
heroku run python manage.py syncdb
 
psycopg2.OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" and accepting
TCP/IP connections on port 5432?
 
heroku addons:add shared-database:5mb
 
import sys
import urlparse
import os


# Register database schemes in URLs.
urlparse.uses_netloc.append('postgres')
urlparse.uses_netloc.append('mysql')

try:

    # Check to make sure DATABASES is set in settings.py file.
    # If not default to {}

    if 'DATABASES' not in locals():
        DATABASES = {}

    if 'DATABASE_URL' in os.environ:
        url = urlparse.urlparse(os.environ['DATABASE_URL'])

        # Ensure default database exists.
        DATABASES['default'] = DATABASES.get('default', {})

        # Update with environment configuration.
        DATABASES['default'].update({
            'NAME': url.path[1:],
            'USER': url.username,
            'PASSWORD': url.password,
            'HOST': url.hostname,
            'PORT': url.port,
        })
        if url.scheme == 'postgres':
            DATABASES['default']['ENGINE'] = 'django.db.backends.postgresql_psycopg2'

        if url.scheme == 'mysql':
            DATABASES['default']['ENGINE'] = 'django.db.backends.mysql'
except Exception:
    print 'Unexpected error:', sys.exc_info()
 
psycopg2
 
toplevel
  requirements.txt
  myapp
    manage.py
    all other django stuff

(Source: http://pastebin.com/NGUbiKb3)


Here are some more useful resource:
[0] http://www.blogosfera.co.uk/tag/heroku-django/
[1] http://stackoverflow.com/questions/16418171/heroku-django-db-postgres-error

Comments

Post a Comment