AWS Beanstalk Django / Python Running Local Issue

2019-04-02 18:35发布

I've followed through "Deploying a Django Application to AWS Elastic Beanstalk" tutorial provided by Amazon but I am trying to run the project locally and I am getting a KeyValue error that I have been unable to find a solution for.

When running the command: $ ./manage.py help

I get this error returned:

File "/Users/dave/Sites/djangodev/djangodev/settings.py", line 17, in <module>
    'NAME': os.environ['RDS_DB_NAME'],
File "/Users/dave/.virtualenvs/djangodev/bin/../lib/python2.7/UserDict.py", line 23, in __getitem__
    raise KeyError(key)
KeyError: 'RDS_DB_NAME'`

I'm actually trying to run $ ./manage.py runserver but that returns a runserver does not exist error. It is because there is an error in my settings.py file.

settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.environ['RDS_DB_NAME'],
        'USER': os.environ['RDS_USERNAME'],
        'PASSWORD': os.environ['RDS_PASSWORD'],
        'HOST': os.environ['RDS_HOSTNAME'],
        'PORT': os.environ['RDS_PORT'],
    }
}

This runs just fine on AWS. Locally is does not. And I'm not surprised since RDS_DB_NAME is not in my local os.environ dictionary.

There was another stackoverflow question that has not provided a solution yet either. Elastic Beanstalk not creating RDS Parameters

I have it running on AWS, it's just getting a local instance to run that is being difficult.

1条回答
够拽才男人
2楼-- · 2019-04-02 19:26

It took a lot of digging around but I found a solution. You need a local fallback to a different database.

In your settings.py file, replace the DATABASE variable with this:

DATABASES = {}

try:
    from local_settings import *
except ImportError, e:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': os.environ['RDS_DB_NAME'],
            'USER': os.environ['RDS_USERNAME'],
            'PASSWORD': os.environ['
            'HOST': os.environ['RDS_HOSTNAME'],
            'PORT': os.environ['RDS_PORT'],
        }
    }

Now create a local_settings.py in the same directory as your settings.py and enter the following code:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'db.djangodb',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}

MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = ()
TEMPLATE_DIRS = ()

Now add your local_settings.py file to your .gitignore file.

Run $ python manage.py syncdb and now you can run the django server locally.

Most of this is copy pasta from this blog post I found: http://grigory.ca/2012/09/getting-started-with-django-on-aws-elastic-beanstalk/

查看更多
登录 后发表回答