How to Write Clean Code

Introduction Even bad code can function. But if code isn’t clean, it can bring a development organization to its knees. Every year, countless hours and significant resources are lost because of poorly written code[1]. Within this article we will take the key concepts, and points around writing Clean Code – referenced from the amazing book, The … Read more

Python – What are Context Managers?

What are Context Managers? Context managers are constructs that allow you to set something up and tear something down automatically, by using using the statement – with.  For example you may want to open a file, write to the file, and then close the file. Here is an example of a context manager, with open(path, … Read more

Python – What are Abstract Classes?

An abstract class can be considered a blueprint for other classes, allowing you to mandate a set of methods that must be created within any child classes built from your abstract class. Creation Lets first look at how you create an abstract class. First we import abc, we define the class as a metaclass using … Read more

Automate/Gather Statistics for Multiple Websites in BASH

Introduction For one reason or another, Im sure you will find yourself in a position when you need to obtain statistics for a collection of websites. Today, we will show you steps required in building a BASH script that will do just that. Lets go…. Output Format Within our script we will use curl. Curl … Read more

How to Build a RESTful API using the Django REST Framework

The Django REST Framework (DRF) allows you create REST based APIs quickly and simply, providing a range of features such authentication, error handling, serialization and full CRUD  (Create Replace Update Delete) based operations to your database. Within this article will look at how to create a very basic API. The API will take in a … Read more

Connecting to a SOCKS Proxy within Python

The SocksiPy python module provides a simple way to connect via a SOCKS proxy. Within this article we will show you 2 examples on how to use SocksiPy. General Below allows you to establish a connection via a SOCKS proxy[1]. import socks socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, “”, 8080) socket.socket = socks.socksocket import urllib2 print urllib2.urlopen(‘’).read() URLLIB2 Only Should … Read more

How to install a Git Repo using Pip

Pip is a package management system used to install and manage software packages written in Python [1]. Its easy to use and provides an excellent way to deploy your code with minimal fuse. Within this article we will show you how to install a git repo [2] directly via pip. First of all add … Read more

Django+MongoEngine Update_or_Create Action

BuiltIn ORM Django provides a convenient method when needing to update a model instance, but create if it does not exist. The method is shown below, update_or_create(defaults=None, **kwargs) However MongoEngine replaces the builtin object-relational mapper (ORM). Because of this an alternative is required. MongoEngine Within MongoEngine the modify method can be used to achieve the … Read more

Python – Packing and Unpacking Dictionaries

Today I will explain the concept of unpacking and packing within Python. Unpacking Unpacking allows us to pass keyword arguments (i.e dictionary) to a function via the use of the ** syntax. We can then access the values within the function like so, >>> def do_something(**kwargs): … print kwargs[‘a’] … print kwargs[‘b’] … print kwargs[‘c’] … Read more

How to Configure Celery within Django

Celery is an open source asynchronous task queue/job queue based on distributed message passing[1]. Within this article we will provide the configuration steps requiring for installing celery within Django. Our tutorial Example Broker Within this example we will use Redis as the broker. Celery uses a broker to pass messages between your application and Celery … Read more

Django Application Design Framework


Components MODULES Modules should be installed via pip, including modules from github. To install modules from github the following article describes the steps involved. Structure projectx |– app1 | |– | |– | |– |– app2 | |– | |– | ‘– |– appx | |– | |– … Read more

Python – What is TDD (Test-Driven Development) ?

What is TDD ? TDD (Test-driven development) is software design approach where your code is written around your tests. With TDD the test is first created, this test initially fails. The minimum amount of code is then written to ensure the test passes. This approach provides the following benefits, promotes the creation of more efficient … Read more

Python – No module named MySQLdb

Issue When trying to import MySQLdb you may find that the module is not available. And experience an error such as, django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb Solution The solution is to install MySQL-python i.e pip-2.7 install MySQL-python PIP INSTALL Error However, when trying to install MySQL-python you may then get the following … Read more

Python – Show differences between 2 Lists

Below shows you how to compare and show the differences between 2 lists by using the set command, >>> set([1563, 1564, 1565, 1566, 1567]).symmetric_difference([1563, 1564, 1565, 1566, 157]) set([1567, 157])

Python – Split a String into a Dictionary

To split a string into key value pairs (i.e dict) the following can be used, >>> string = “abc=123,xyz=456” >>> dict(x.split(‘=’) for x in string.split(‘,’)) {‘xyz’: ‘456’, ‘abc’: ‘123’}

JQuery – Hide id if Class is Visible

In order to hide a class is a class is visable the following is used. Below will hide the div id #bannerad is the class .back is visible. $(document).ready(function(){ if ($(‘.back’).is(“:visible”) == true) $( “#bannerad” ).hide(); });

Python – Check for Items across Sets

Within this example we will check if the same item exists across 2 sets. If so then a boolean is returned, >>> s1 = set([1, 2, 3])>>> s2 = set([3, 4, 5])>>> bool(set(s1) & set(s2))True

How to Print the File Location of a Python Module

The are times were you may need to print the location of a python module. There are a number of ways to achieve this. However the most simplistic method  have found is to use ‘inspect’. Below shows you an a example, >>> import inspect>>> import urllib2>>>>>> print inspect.getfile(urllib2)/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.pyc

Python – Create a Dictonary using List Items as Keys

Below shows you how to create a dictionary using keys from list items using list comprehension. From this we can also set a default value. >>> keys = [‘a’,’b’,’c’,’d’]>>> { x:False for x in keys }{‘a’: False, ‘c’: False, ‘b’: False, ‘d’: False}

How to Build a TCP Connection in Scapy

Scapy is a packet manipulation program written in Python by Philippe Biondi. Within this article I will show you the code required to build a 3WHS within Python using Scapy. Prevent RST At the point you send the SYN from Scapy and the SYN-ACK is returned. Because the Linux kernel receives the SYN-ACK but didn’t … Read more

Python – How do I merge 2 dictionaries ?

Below shows you how to merge 2 dictionaries. It is also worth noting that any items will be overwritten by the 2nd dictionary should they exist in both. This is also shown below via the bananas items. >>> x = {‘apples’: 1, ‘bananas’: 2}>>> y = {‘bananas’:3 , ‘coconuts’: 4}>>> dict(x.items() + y.items()){‘coconuts’: 4, ‘apples’: … Read more

Python – Filtering a dictionary against a list of values

This short Python snippet shows you how to filter a dictionary against a list of values via the use of a list comprehension. >>> d = {“apples”:1,”bananas”:2,”pears”:3} >>> {x:y for x,y in d.iteritems() if x in [“apples”,”pears”]}{‘apples’: 1, ‘pears’: 3}

Django Quick Reference

Quick Reference Models Query Description Event.objects.filter(appid=”example”) filter for appid eq example Event.objects..exclude(username=”rick”) show everything not excluding username eq rick Event.objects.filter(appid=”example”).exclude(user__in=[“bob”,”fred”]) include appid eq example and exclude user bob or fred Upgrade.objects.filter(device_number=’device_numberooo’).values() Display as dict() Management Commands Commands Description  ./ dumpdata updowngrade –indent 2 

Python 2.7.5 : ImportError: No module named _sqlite3

After compiling Python 2.7.5 you may find yourself being unable to to import sqlite3 and receiving the following error message, ImportError: No module named _sqlite3 Solution Install sqlite-devel via ‘yum install sqlite-devel’ Recompile Python. Note : Details on how to compile Python can be found within the following article.    

TCL – The difference between the eq and == operators

TCL Background Unlike many programming languages (such as Python) TCL stores all values as strings. By using operators or commands these values can be interpreted as different data types (such as integers, binary etc). ‘eq’ vs ‘==’ Though, on the surface, the 2 TCL operators ‘eq’ and ‘==’ appear similar, ie  both return a boolean … Read more

How to install easy_install-2.7 and pip-2.7

Within this quick tutorial we will show you the steps required to install easy_install-2.7 and pip-2.7. Install  wget –no-check-certificate tar xf distribute-0.6.35.tar.gzcd distribute-0.6.35python2.7 install easy_install-2.7 pip Confirm [root@server]# easy_install-2.7error: No urls, filenames, or requirements specified (see –help) [root@server]# pip-2.7 -Vpip 1.3.1 from /usr/local/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg (python 2.7)

How do I compile mod_wgsi for Python 2.7

Recently I found myself in a situation where I needed to recompile mod_wgsi against a newer version of Python. This involves recompiling Python with the correct flags, then recompiling mod_wsgi using the newly compiled Python. Below shows the steps, Check Version First of all check what version of Python mod_wsgi was compiled with. [root@server]# ldd … Read more

Create a Multiline Cell Based CSV File Within Python

Within this short tutorial we will show you the steps required to create a csv file that includes multi-line cells within Python. In order to create a mutliline cell within Excel (2010/2013) the following is required: newlines are represented with a carriage return/newline, the string should be wrapped in quotes. One of the great things … Read more

Django 1.5 – ‘url’ requires a non-empty first argument.

Issue When running Django 1.5.1 you may observe the following error, NoReverseMatch at /‘url’ requires a non-empty first argument. The syntax changed in Django 1.5, see the docs. Solution This issue can occur due to changes in the url tag syntax. More information on this can be found at The correct syntax for url … Read more

Django – How do I create a custom login page ?

Within this article we will look at how to permit only authenticated users to a view via the use of a custom login form. SETTINGS First of all a few changes need to be made to the file. Such as + ‘django.contrib.auth.middleware.AuthenticationMiddleware’ to MIDDLEWARE_CLASSES + ‘django.contrib.auth’ and ‘django.contrib.contenttypes’to INSTALLED_APPS Once done update your database by … Read more

Python – List Comprehensions

List comprehensions provide an more Pythonic and alternative way (i.e instead of using map and filter) in which to express a list. There are 3 components to a list comprehension. The expression, the for loop and the optional condition. As you can see below, by changing the expressions and enclosing brackets to your expression you … Read more

Python – What does ‘if __name__ == “__main__”‘ mean ?

Within a Python program you may see the following syntax, if __name__ == “__main__”:    …(your code)… What does this mean ? When a Python program is run directly it runs within the __main__ namespace. However when a python script is imported as a module it runs within its own namespace. This statement checks the namespace … Read more

Python – Decorators

A decorator provides a simplified way to pass one callable object to another (i.e a class or function). The main benefit of decorators is that it allows you to clearly state where and what objects are being passed to each other. Typically this can be achieved by the following. Without Decorators As you can see, … Read more

Django – How can I pass a string from a URL to a view ?

Within Django the are 2 ways of using a URL parameter within a view. They are via URLConf or by using request.GET. URLConf With this method the URLConf file is configured to define your URL parameter via the use of regex. Say that we have a URL that is ‘’ and we want to grab … Read more

How do I use AJAX along side Django ?

Introduction Within this example we will show you a simple example of how to integrate AJAX with Django. AJAX (Asynchronous JavaScript and XML) is a technique that provides the ability to update parts of a web page, without reloading the whole page. Now days,  typically JSON is the preferred method over XML due to JSON`s … Read more

How do I import a python module from another folder ?

Within this article we will show you how to import a python module that is located within a different folder. This example will be based upon your folder structure including a folder named ‘module’ and the path ‘/opt/django/myproject/’ already being within your python system path. Example Folder Structure Below shows you a quick example of … Read more

How do I configure Django to serve my Robots.txt file ?

Within this article we will look at how to configure Django to serve your ‘robots.txt’ file. Though there are a number of methods available to achieve this, this example we will only look at the Django method. In that only the the file within your Django project will need to be changed. Example … Read more

Serve Multiple Domains from a Single Django Project

Introduction Within this article we will be showing you the necessary steps required to serve multiple domains from within a single Django project. This example will based upon a project named ‘myproject’ and 2 domains named ‘domain1’ and ‘domain2’. Below shows the file structure. /opt/ `– django     |     `– myproject         |– … Read more

Joomla – JFolder::create: Could not create directory

When running Joomla 2.5 you may observe the following error : JFolder::create: Could not create directory Solution This error is typically related to permissions. To resolve the issue run the following commands (replacing the path with the path of your Joomla installation). cd /var/www/html/joomla-sitefind . -type f -exec chmod 644 {} \;find  . -type d … Read more

How do I configure Apache to serve my Django website ?

Summary In order for Apache to serve your Django website WSGI is configured. The Web Server Gateway Interface (WSGI) defines a simple and universal interface between web servers and web applications or frameworks for the Python programming language (wikipedia). Note : The following steps are based on a Linux Centos based distro. The following steps within … Read more

Django – Static Files

Static Files is a Django app that helps with serving static content. This tutorial is meant as a short and quick guide on how to configure your Django project to serve static based content.To achieve this we will configure Django (via and Apache. Our example will be based on serving static content from the … Read more

Django – CSRF verification failed. Request aborted.

Issue When trying to access your Django site within CSRF configured you receive the following via a Forbidden (403) HTTP error message: CSRF verification failed. Request aborted.No CSRF or session cookie. Solution In my scenario I found that the order of settings.MIDDLEWARE_CLASSES was incorrect. Below shows you an example MIDDLEWARE_CLASSES = (    ‘django.middleware.csrf.CsrfViewMiddleware’,    ‘django.middleware.common.CommonMiddleware’,    … Read more

Tool – SSLReport

SSLReport provides the ability to scan a network and determine which hosts are running SSL/TLS based services and then query each of these servers/ports to determine which ciphers are supported. The output of this is then outputted within a CSV based format. Usage [root@william images]# bash sslreport.txt home Checking for Binaries …..  *Successful execution … Read more

Joomla – How to add a custom field

Within this tutorial, I will show you the necessary steps required to add a custom field named ‘Version’ to your Joomla site. This field will be displayed within both the administrator console and the published article. 1. Configure Database Within phpmyadmin run the following SQL command ALTER TABLE `jos_content` ADD `vers` VARCHAR( 255 ) NOT … Read more

Python – Auto Width Function

Below is a python function that I created. The purpose of this function is to print correctly aligned columns using variable length items. The result is that you can pass the function a list (or list of lists), the same list is returned with each item padded to the maximum item length within the relating … Read more

How do I print the path of a Python module ?

To print the path of python module the command print [module].__file__. An example is shown below: [root@webserver1 ~]# pythonPython 2.4.3 (#1, Sep 21 2011, 19:55:41)[GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2Type “help”, “copyright”, “credits” or “license” for more information.>>> import pexpect>>> print pexpect.__file__/usr/lib/python2.4/site-packages/pexpect.pyc

Stream ripper bash script

This bash script allows you to download an audio stream via ASX (Advanced Stream Redirector) for a defined time period. The downloaded file (wma) is then converted to mp3. This provides the ability to schedule and download your favourite radio shows for later listening. Requirements There are 2 main binaries that this script requires. They … Read more

Python – Temperature Convertor

Below is a small script to convert temperatures between celcuis and fahrenheit (and vice versa). This article / script is meant as reference point rather than a full tutorial. #!/usr/bin/python import sys def convert(t,fc):        if t == “2f”:                print (fc * 9) / 5 + 32,”Degress Fahrenheit”        elif t == “2c”:                print (fc – 32) … Read more

How to perform a basic PHP Installation

Within this article we will be configuring a basic php installation using Apache.Note : The steps are based upon the CentOS 5 distro. Install Apache / PHP First of all you will need to install Apache and php via yum. yum install httpd php Edit php.ini Within /etc/php.ini ensure the following settings are configured by … Read more

SoundCloud Downloader BASH Script

SoundCloud allows artists and producers to upload and promote music across the internet. This article provides a Linux based script which downloads all tracks for a given artist. SCRIPT #!/bin/bash if [ -z “$1” ]; then echo “Usage: `basename $0` [URL]”; echo echo “Example:” echo ” `basename $0`”; exit fi page=`wget $1 -q –user-agent=’Mozilla/5.0′ … Read more

Want to become a programming expert?

Here is our hand-picked selection of the best courses you can find online:
Python Zero to Hero course
Python Pro Bootcamp
Bash Scripting and Shell Programming course
Automate with Shell Scripting course
The Complete Web Development Bootcamp course
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial