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
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
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
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
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
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, “127.0.0.1”, 8080) socket.socket = socks.socksocket import urllib2 print urllib2.urlopen(‘http://www.google.com’).read() URLLIB2 Only Should … Read more
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. Setup.py First of all add … Read more
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
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
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
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
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
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])
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’}
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(); });
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
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
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}
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
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
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}
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 ./manage.py dumpdata updowngrade –indent 2 http://stackoverflow.com/questions/14115318/create-django-model-or-update-if-exists
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 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
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 setup.py 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)
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
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 https://docs.djangoproject.com/en/dev/releases/1.5/. The correct syntax for url … Read more
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
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 settings.py 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
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
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
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
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 ‘www.domain.co.uk/user=value’ and we want to grab … Read more
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
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
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 urls.py method. In that only the the urls.py file within your Django project will need to be changed. Example … Read more
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 |– __init__.py … Read more
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
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
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 settings.py) and Apache. Our example will be based on serving static content from the … Read more
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 settings.py MIDDLEWARE_CLASSES = ( ‘django.middleware.csrf.CsrfViewMiddleware’, ‘django.middleware.common.CommonMiddleware’, … Read more
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 10.1.1.0/23 home Checking for Binaries ….. *Successful execution … Read more
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
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
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
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
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
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 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` http://soundcloud.com/disco-dave”; exit fi page=`wget $1 -q –user-agent=’Mozilla/5.0′ … Read more