Tag Archives: python

Use “get” methods to help writing more testable code

Imagine you have the following code def do_something(): users = User.objects.filter(dob__gte='1980-01-01') for user in users: # do something to user If you were writing unit test against do_something(), you would need to do some complex mocking on User.objects.filter() to return some mock up data. But this can be easily prevented by refactoring into a separate… Read More »

Posting image to thumbor using requests package

Seems like there are not many code sample there, and the requests documentation was giving the wrong hint to use files={‘file’: open(‘image.jpg’)} which you will end up getting 415 response code. I think I will just share my working sample code here to save someone’s time import requests # local file with open(‘image.jpg’, ‘rb’) as… Read More »

Python OpenCV Facial Detection On OSX

Just a code snippet to demo Python script using OpenCV import cv2, time cap = cv2.VideoCapture(0) time.sleep(1) cascade = cv2.CascadeClassifier(“haarcascade_frontalface_alt.xml”) def detect(image): #faces = cascade.detectMultiScale(img, 1.1, 2, cv2.cv.CV_HAAR_SCALE_IMAGE, (20,20), (200,200)) faces = cascade.detectMultiScale(image) for _face in faces: cv2.rectangle(image, (_face[0], _face[1]), (_face[0]+_face[2], _face[1]+_face[3]), (255,255,255)) def repeat(): ret, image = cap.read() detect(image) cv2.imshow(“w1”, image) cv2.waitKey(1) while True:… Read More »

Django CMS Haystack 2.0 Search Index

Currently django-cms-search doesn’t support haystack 2.0 yet, so here is my modified version to work on haystack 2.0 based on import datetime from haystack import indexes from cms.models.managers import PageManager from cms.models.pagemodel import Page from cms.models.pluginmodel import CMSPlugin class PageIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=False) pub_date = indexes.DateTimeField(model_attr=’publication_date’, null=True) login_required = indexes.BooleanField(model_attr=’login_required’) url = indexes.CharField(model_attr=’get_absolute_url’)… Read More »

Django admin UnicodeEncodeError

Don’t we all get confused by unicode encoding sometimes? Especially you wouldn’t expect this kind of error to happen in django admin. The problem is actually not in the admin section, the culprit is __unicode__ method in your model. when you have a unicode function like this: def __unicode__(self): return “{0}”.format(self.field_one) It is actually returning… Read More »