Thursday, May 12, 2016

Deal with OpenShift

http://www.indjango.com/deploying-django-app-on-openshift/


Deploying Django application on Openshift online for free

Recently Heroku has changed their terms that every free application should be inactive for 6 hours a day. This will not work out if we are going to depend on heroku to host a application which we run without any break. Luckily I came to know about Openshift in one of my recent projects and checked their pricing. I was surpised to see that they are also offering some free plans.

Openshift

Openshift is a service provided by Redhat. They are offering various plans and it includes a free plan which lets us host upto three applications for free. Lets see how we can host a django application for free in openshift online.
I'm explaining the steps for deployment from using an Ubuntu system. But most of the methods will remain same irrespective of the operating system.

Versions Used

  • Django - 1.9.2
  • Git - 1.9.1
  • Ubuntu - 14.04
  • Openshift client tools - 1.38.4

Step 1: Setup Openshift account

Go to Openshift site and create an account using your email address. This is free. No credit card or any other payment information required.

Step 2: Setup Openshift client tools

Install Openshift client tools in your system. The tool is available for all the most popular platforms. Instructions for those operating systems can be found in openshift documentation. In case of Ubuntu, use the command
sudo apt-get install rhc
To start the setup, run the command
rhc setup
When asked for server hostname, enter
openshift.redhat.com
You can leave it blank, if it is the default value. Then enter your openshift username and password when prompted.

Step 3: Setup Git

If you are not using git, download and install git from Git SCM. You can learn more about git from the presentation on Slideshare.

Step 4: Create your openshift app

Method 1: Login to your openshift account and create an application. After creating the application, clone it to your system using the SSH URL shown under the heading source code.
Method 2: You can also create openshift application using the command
rhc create-app -a <app-name> -t python-2.7
You can use any of these methods to create openshift application. You can select other available python versions also while creating the app. When you create app using the command line you will see output similar to the one given below.
Project Name

Step 5: Configure your django project

Create (or move) your django in the root folder of the cloned openshift repo.

Step 5.1: Add database related settings

Add PostgreSQL database cartridge to your app using command
rhc cartridge add -c postgresql-9.2 -a <app-name>
Adding the cartridge will give a output similar to the one given below.
Project Name
After adding the cartridge, change your database settings as given below.
import urlparse
db_url = urlparse.urlparse(os.environ.get('OPENSHIFT_POSTGRESQL_DB_URL'))

DATABASES = {'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': os.environ['OPENSHIFT_APP_NAME'],
    'USER': db_url.username,
    'PASSWORD': db_url.password,
    'HOST': db_url.hostname,
    'PORT': db_url.port,
    }
}

Step 5.2: Configure wsgi.py

Update the content of the file wsgi.py found in the root folder of the repo.
#!/usr/bin/python
import os, sys

sys.path.append(os.path.join(os.environ['OPENSHIFT_REPO_DIR']))

os.environ['DJANGO_SETTINGS_MODULE'] = '<app-name>.settings'

virtenv = os.environ['OPENSHIFT_PYTHON_DIR'] + '/virtenv/'

os.environ['PYTHON_EGG_CACHE'] = os.path.join(virtenv, 'lib/python2.7/site-packages')

virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
try:
    execfile(virtualenv, dict(__file__=virtualenv))
except IOError:
    pass

#
# IMPORTANT: Put any additional includes below this line.  If placed above this
# line, it's possible required libraries won't be in your searchable path
#

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
Replace the <app-name> with your app name.

Step 5.3: Create requirements.txt

Create requirements.txt using the command
pip freeze > requirements.txt
in the root folder of your application, if you haven't done this already. This will be used to install the dependencies for your application.

Step 5.4: Configure post deployment action hook

Post deployment action hook can be used to place the commands that should be run in server deployment of the product. There will be a hidden folder named .openshift in the root folder of the app. Inside that folder create a file named post_deploy if it doesn't exist.
The file should contain the following content
source ${OPENSHIFT_HOMEDIR}python-2.7/virtenv/bin/activate

export PYTHON_EGG_CACHE=${OPENSHIFT_HOME_DIR}python-2.7/virtenv/lib/python-2.7/site-packages

echo "Executing 'python ${OPENSHIFT_REPO_DIR}mywebsite/manage.py syncdb --noinput'"
python "$OPENSHIFT_REPO_DIR"manage.py migrate --noinput

echo "Executing 'python ${OPENSHIFT_REPO_DIR}mywebsite/manage.py collectstatic --noinput -v0'"
python "$OPENSHIFT_REPO_DIR"manage.py collectstatic --noinput -v0
Here we are running the commands for database migrations and collecting static files. If you need to run more commands, you can add them here.

Step 6: Deploy to openshift

Commit your changes using the commands
git add .
git commit -am "Initial commit"
You can give a commit message of your choice. After committing, push the application to heroku using the command
git push origin master
After pushing the code, you will be access your django app using the openshift app's URL which you get while creating the app.

Step 7: Viewing app details

You can view app details using the command
rhc show-app <app-name>
It will give an output similar to the one given below.
Project Name
You can view your app's state using the command
rhc show-app <app-name> --state
It will give an output similar to the one given below.
Project Name

Step 8: Adding custom domain (optional)

If you like to use custom domain for your openshift application, you can do so by adding the domain to your openshift app and configuring CNAME in your domain DNS editor. Add the domain to your openshift app using the following command.
rhc alias add <app-name> <custom domain name>
Configure CNAME in your domain DNS editor with host as www and Points to as your app's openshift URL. Now you should be able to access your app in your custom domain.
Now we have successfully deployed a django application on openshift. Feel free to post your feedback and questions as comments.

https://developers.openshift.com/managing-your-applications/backing-up-applications.html


rhc snapshot save <app_name>


https://appsembler.readthedocs.io/en/latest/static_assets.html

Serving Django static assets on from OpenShift

  1. Create a collected_static folder during build
    Add the following to your .openshift/action_hooks/build script:
    if [ ! -d $OPENSHIFT_REPO_DIR/wsgi/static/collected_static ]; then
        mkdir $OPENSHIFT_REPO_DIR/wsgi/static/collected_static
    fi
    
  2. Correctly set up Django settings
    Make sure your STATIC_ROOTSTATIC_URL and STATICFILES_DIR settings are correctly set. They should look something like this:
    STATIC_ROOT = os.path.join(get_env_variable('OPENSHIFT_REPO_DIR'), 'wsgi', 'static', 'collected_static')
    STATIC_URL = '/static/'
    STATICFILES_DIRS = (
        os.path.join(PROJECT_ROOT, 'static'),
    )
    
  3. Set up apache mod_rewrite
    Add the following lines to your wsgi/.htaccess file:
    RewriteEngine on
    RewriteRule ^application/site_media/(.+)$ /static/collected_static/$1 [L]
    
  4. Run collectstatic in deploy script
    Add the following somewhere at the end of your .openshift/action_hooks/deploy script:
    export DJANGO_SETTINGS_MODULE=your.settings.module
    echo "Executing 'django-admin.py collectstatic'"
    django-admin.py collectstatic --noinput --settings=$DJANGO_SETTINGS_MODULE
    
Note that the get_env_variable mentioned above is defined in the settings.py as:
from django.core.exceptions import ImproperlyConfigured


def get_env_variable(var_name):
    """ Get the environment variable or return exception """
    try:
        return os.environ[var_name]
    except KeyError:
        error_msg = "Set the %s environment variable" % var_name
        raise ImproperlyConfigured(error_msg)



http://stackoverflow.com/questions/24572276/install-python-packages-on-openshift

http://subinsb.com/how-to-use-filezillasftp-to-update-site-in-openshift

http://stackoverflow.com/questions/19749599/openshift-how-to-remote-access-mysql

http://stackoverflow.com/questions/24595223/static-files-on-openshift-django




3 comments:

  1. http://serverfault.com/questions/628884/configuring-wsgi-application-to-serve-a-static-html

    ReplyDelete
  2. https://developers.openshift.com/languages/python/flask.html
    http://www1.cmc.edu/pages/faculty/alee/cs135/penv/deployOnOpenShift.html

    ReplyDelete
  3. http://stackoverflow.com/questions/17764156/cannot-show-image-from-static-folder-in-flask-template

    ReplyDelete