I started off looking for a request time compiler of LESS for Django and initially found django-css which seems to serve the purpose great. Compressing static files on the fly is definitely a nice added bonus as well. It does so by containing a fork of django_compressor. But on further inspections, I jumped ship. The original project, django_compressor, sees a more regular update and is now Django 1.3 ready while the ‘successor’ isn’t. Funny thing is django_compressor supports compiling any CSS formats compilable via command line. With a better documentation overall, seems like the original has beat the sequel.
Tag Archives: Python
Django Log to File
In the official Django logging docs, it wasn’t very clear about how to log to files. As you can understand, Django can use any Python logging classes that are all listed here. One of them is FileHandler. To use it, just add this to your settings.py Continue reading
Validate and Format Addresses using Google API
Suppose you want to make some web app that lets users input addresses. I would be nice to
- Weed out minor misspelling
- Standardise format (proper capitalisation, abbreviated province/state or full name etc)
- Input in freeform but store civic number, street name, city etc separately
- Verify the address exists of course
Some governmental entities provide this information via public APIs but if you want a uniform service, why not use Google? Continue reading
Python Debug with ipdb
A quickie:
import ipdb; ipdb.set_trace()
This puts a breakpoint in the code using ipdb. It has the advantage of having better formatted output, tab completion etc over the vanilla pdb
PIL: Get RGB Value from GIF
If you load a GIF file with PIL via Image.open(‘giffile.gif’) and then try to look at its pixels, you would get integers instead of tuples since the GIF pixels refers to one of the 256 colours in the GIF colour palette. The palette would then contain the RGB value of the pixel.
To avoid all this hassle and just get RGB tuple directly:
gif = Image.open('giffile.gif') rgbimage = GIF.convert ('RGB') rgbimage.getpixel((0,0)) >>>(231, 10, 54)
Python Challenge Level 14: Italy – Code
Used a NumPy array. Doesn’t work if the diagonal+1s are white of course.
import Image from numpy import array, zeros, uint8 line = Image.open('wire.png') # third dimension is for colours a = zeros((100, 100, 3), dtype=uint8) step = array([0, 1]) position = array([0, 0]) count = 0 # continue until when the next spot expected to be unfilled is filled while not max(a[tuple(position)]): # paint colour a[tuple(position)] = array(line.getpixel((count, 0))) # if reached a wall if max(position + step) > 99 or min(position + step) < 0 or max(a[tuple(position + step)]): # change direction step = (abs(step) ^ 1) * (-step[0] if step[0] else step[1]) # advance position += step count += 1 # convert to image Image.fromarray(a).save('swirl.jpeg')
How to Convert Numpy Array to Tuple
a = array((1, 2, 3)) print a >>> array([1, 2, 3]) tuple(a) >>> (1, 2, 3)
Pretty lame right?
Python Convert ISO8601/UTC to Local Time
Ok, I looked this up twice now… once too many
Suppose you have a datetime of the form “2010-05-08T23:41:54.000Z” and you want a local datetime object
import pytz, dateutil.parser utctime = dateutil.parser.parse("2010-05-08T23:41:54.000Z") localtime = utctime.astimezone(pytz.timezone("Canada/Eastern"))
Boom
Python’s Function Static Variable
So you want a variable that stays between different calls of a function. Not the sexiest thing ever but always handy in small programs.
There’s tons of ways of doing this. You can embark on a quest to find the meaning of Pythonic or take this method that’s relatively simple:
def a(): if not hasattr(a, "b"): a.b = 0 a.b += 1 print a.b
Calling a(), you’ll get 1, 2, 3, …
Note attribute ‘b’ of ‘a’ does not exist until you declare it for a first time. My main preference here is that ‘static’ variables used this way does not spill onto the rest of your code. Also, it’s clean, no classes, no data structures.
Suppress Scapy IPv6 Warning
When you run Scapy without a default IPv6 routing gateway, Scapy will display this annoying warning:
WARNING: No route found for IPv6 destination :: (no default route?)
You definitely don’t want to see it every time you run the script you built with Scapy. To get rid of it, simply add
import logging logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
before importing Scapy to suppress all messages below error messages
Python Log Stdout to File
Python has the ability to alter its sys.stdout as to redirect its print commands to pretty much anything.
If, for instance, you want to print to both standard output and to a log file, you can create a class to handle the stdout like such:
class MyOutput(): def __init__(self, logfile): self.stdout = sys.stdout self.log = open(logfile, 'w') def write(self, text): self.stdout.write(text) self.log.write(text) self.log.flush() def close(self): self.stdout.close() self.log.close() sys.stdout = MyOutput("log.txt") print "blah blah blah"
PyQt and Snow Leopard
There are some 64-bit related issues when using PyQt and Snow Leopard. There’s the way to resolve it by reverting to 32-bits:
- Get the latest versions of PyQt and SIP. You need Qt installed of course.
- Configure SIP using
- Configure PyQt using
- Finally, make sure your python is running in 32-bit mode because current Qt doesn’t support 64-bit mode. Add
export VERSIONER_PYTHON_PREFER_32_BIT=yes
to your .bash_profile in your home directory
- If your Python still refuses to run in 32 bit mode, try
arch -i386 python
python configure.py --arch i386python configure.py --use-arch=i386