Linux – adding user with home directory and other settings

Add a new user:

useradd -m automation

The -m option would take care of adding a home directory for the user under /home

After adding a new user, I switched to the user and realized that the command prompt looks different. My own user had the command prompt like varun.verma@server-dev:~$ but for the new user, it only showed a $.

I looked through the changes in the /etc directory and found this different in the passwd file:

varun.verma:x:1002:1002:Varun Verma,,,:/home/varun.verma:/bin/bash
automation:x:1007:1009::/home/automation:/bin/sh

I replaced the sh for user automation with bash and that did the trick.

Copy/Move top 100 files to a directory

I have a large number of files that I need to separate in parts and put in a different directory. I used to copy the files individually and paste them over in a directory. Then I found this cool trick to get the top 100 files from the current directory and copy/move them over to a different one. You can substitute mv/cp based on what you need.

find . -name "*.jpg" -maxdepth 1 -type f | head -100 |  xargs -I{} mv {} Dir-Part1/

Keep repeating this command by replacing the name of the directory at the end. Trust me, saves a lot of time.

GIT – Merge dev to master

I generally like to merge master into the development first so that if there are any conflicts, I can resolve in the development branch itself and my master remains clean.

(on branch development)$ git merge master
(resolve any merge conflicts if there are any)
git checkout master
git merge development (there won't be any conflicts now)
git push

DateTime functions in Python

Some useful date/time functions in Python:

import time
import datetime
from time import gmtime, strftime
from datetime import timedelta, date
from dateutil.relativedelta import relativedelta

def validateApiDate(apiDate):
    '''
    Validates non-standard date string format
    ''' 
    try:
        dt = datetime.datetime.strptime(apiDate, '%Y%m%d').date()
        #print type(dt)
        dt = datetime.datetime.strftime(dt, '%Y-%m-%d')
        print dt
    except ValueError:
        return False

def addDaysToCurrentDate(numDays):
    '''
    Add days to current date
    '''
    d = date.today() + timedelta(days=numDays)
    return int(time.mktime(datetime.datetime.strptime(str(d), '%Y-%m-%d').timetuple()))

def getTimeDelta(numDays):
    '''
    Add days to current date
    '''
    d = date.today() + timedelta(days=numDays)
    return d.timetuple()

def validatePastDate(d):
    '''
    Validate if the date is a past date
    '''
    dt = datetime.datetime.strptime(d, '%Y%m%d').date()
    #print type(dt)
    today = date.today()
    #print type(today)
    diff = (dt-today).days
    #print type(diff)
    print diff

def first_of_last_month():
    '''
    Get 1st of last month. Works with python 2.7 and higher
    '''
    one_month_ago = date.today() + relativedelta(months=-1)
    first_day_last_month = (one_month_ago.year, one_month_ago.month, 1)
    return first_day_last_month

def first_of_last_month_py26():
    '''
    Get 1st of last month. Works with python 2.6 or older
    '''
    first_day_of_current_month = date.today().replace(day=1)
    last_day_of_previous_month = first_day_of_current_month - timedelta(days=1)
    first_date_of_last_month = last_day_of_previous_month.replace(day=1)
    return first_date_of_last_month

Python Django Tutorial 5 – The built in Admin interface

1. Installing the Admin
Open the settings file and make sure that the following item is added to the INSTALLED_APPS set.

INSTALLED_APPS = (
    'django.contrib.admin',
)

2. Enable Admin URL’s in the project’s urls.py file
After importing the admin module, enable/add the following pattern in the list of urlpatterns:

from django.contrib import admin
urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
]

3. Register the App’s models that need to be shown in Admin
Open the admin.py file created under the articles directory and register the models in this file.

from django.contrib import admin
from article.models import Article

# Register your models here.
admin.site.register(Article)

Now you should be able to add/edit/delete your articles from the admin panel. How cool is that!

Python – Ternary operator

Programming languages derived from C usually have following syntax:

(condition) ? (expression1) : (expression2)

The Python BDFL (creator of Python, Guido van Rossum) rejected it as non-Pythonic, since it is hard to understand for people not used to C. Moreover, the colon already has many uses in Python. So, when PEP 308 was approved, Python finally received its own shortcut conditional expression:

(expression1) if (condition) else (expression2)
e.g. reuse_appliances = True if use_existing_systems == 'True' else False

Python Django Tutorial 4(b) – Advanced views and urls

1. Defining URL’s within the App
So far, we had defined all URL’s in the main project’s urls.py file. But the purpose of having an app is that it can be a standalone module that can be plugged into any other project. For the same reason, it is nice to define all the URL’s related to the app contained with the app.

Create a new urls.py within the articles app. This is explained as per Django version 1.8. URL imports works in a different fashion for older Django versions.

from django.conf.urls import patterns, include, url
from article.views import articles, article

urlpatterns = [
	url(r'^all/$', articles, name='articles'),
	url(r'^get/(?P<article_id>\d+)/$', article, name='article'),
]

The part of code (?P<article_id>\d+) denotes a variable/parameter (?P) is named article_id will be of type digit of any length greater than 1 (\d+).

Now modify the urls.py within the project folder so that it is able to include the urls.py file that is created under the articles app.

urlpatterns = [
    url(r'^articles/', include('article.urls')),
}

The above denotes that anything starting with articles will look for the next segment of the URL within the article.urls file.

2. Creating views
Let’s define 2 more views in the views.py file under articles. The first one would take the article_id parameter from the URL and use it to show the article header and body, e.g. view for this URL http://127.0.0.1:8000/articles/get/1/

def article(request, article_id = 1):
	return render_to_response('article.html', {'article' : Article.objects.get(id=article_id)})

This view takes in a new parameter article_id apart form the standard request parameter. If you look back, the name of the parameter is defined within the URL (?P

\d+). The view calls the magical render_to_response by passing in the article object corresponding to the article_id.

The other view would list all the articles in the database, e.g. view for this url http://127.0.0.1:8000/articles/all/

def articles(request):
	return render_to_response('articles.html', {'articles' : Article.objects.all()})

This view passes all article objects to the template articles.html

3. Creating templates
The first template (article.html) takes in a single article object and displays it’s title and body.

<html>
<body>
<h1>{{ article.title }}</h1>
<p>{{ article.body }}</p>
</body>
</html>

The second template (articles.html) lists all the articles in the database with a link to access their individual article page.

<html>
<body>
{% for article in articles %}
<div>
<h2><a href="/articles/get/{{ article.id }}/">{{ article.title }}</a></h2>
<p>{{ article.body }}</p>
</div>
{% endfor %}
</body>
</html>