Monday, December 21, 2009

Source interface with Python and urllib2 - Stack Overflow

A monkey patch to change your source interface with python Source interface with Python and urllib2
import socket
true_socket = socket.socket
def bound_socket(*a, **k):
    sock = true_socket(*a, **k)
    sock.bind((sourceIP, 0))
    return sock
socket.socket = bound_socket

Tuesday, December 15, 2009

SplitSettings - Django

No sure why they don't set this up by default but the best way to setup your media and template paths is:
DIRNAME = os.path.abspath(os.path.dirname(__file__))
DATABASE_NAME = os.path.join(DIRNAME, 'project.db')
MEDIA_ROOT = os.path.join(DIRNAME,'media')
TEMPLATE_DIRS = (
    os.path.join(DIRNAME,'templates'),
)
SplitSettings - Django - Trac

Inlines support for Django generic views

Django generic views are missing one major feature, inline forms. This class is a drop in that adds the functionality. Wad of Stuff: Inlines support for Django generic views

Saturday, December 12, 2009

Lazy choices in Django form

A cool library that django has the doesn't seem to be documented very well
from django.utils.functional import lazy

class CarSearchForm(forms.Form):  
    # lots of fields like this
    bodystyle = forms.ChoiceField(choices=lazy(bodystyle_choices, tuple)())
Lazy choices in Django form - Stack Overflow

Thursday, December 10, 2009

Python get IP of interface

Recipe 439094: get the IP address associated with a network interface (linux only)

Simple Python ping method

def ping(host):
    result = subprocess.call(["ping","-c","1",host],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    if result == 0:
        return True
    elif result == 1:
        raise Exception('Host not found')
    elif result == 2:
        raise Exception('Ping timed out')
useage:
try:
    ping('192.168.100.100')
except Exception:
    print "Ping error"
    raise