Skip to content

Instantly share code, notes, and snippets.

@jsatt
jsatt / gist:b6fcbd40a8330996449a
Last active April 28, 2016 16:25
Fudge Mock Magic Method
mo = fudge.Fake().expects_call()
mf = mo.returns_fake()
mf.expects_call('read').returns('test')
setattr(fudge.Fake, '__enter__', fudge.Fake().is_callable().returns(mf))
setattr(fudge.Fake, '__exit__', fudge.Fake().is_callable())
# https://github.com/jsatt/mock/blob/master/mock.py#L1867
@jsatt
jsatt / paginate.py
Created December 30, 2013 16:07
A more powerful Django queryset paginator. Sets up common boilerplate for pagination, including page number validity checking. It also provides a range of "neighbor" page numbers and find what page a specific object is on. `object_list` can be a queryset or iterable of objects, (not just Django models). Setting `page_range` arg will adjust numbe…
from django.core.paginator import Paginator, InvalidPage, EmptyPage
def paginate(request, object_list, limit=10, page_range=10, object_pk=None):
paginator = Paginator(object_list, limit)
page = None
if object_pk:
if hasattr(object_list, 'values_list') and callable(
object_list.values_list):
object_list = list(object_list.values_list('pk', flat=True))
@jsatt
jsatt / gist:7414231
Created November 11, 2013 14:47
Select by row
SELECT * FROM [table name] LIMIT [row id], 1;
date = now().replace(hour=0, minute=0, second=0, microsecond=0)
@jsatt
jsatt / rand_string.py
Created August 30, 2013 16:38
Generate a random string in python
import random
import string
rand_string = ''.join(random.choice(string.ascii_letters + string.digits)
for i in xrange(random.randint(6, 20)))
@jsatt
jsatt / gist:6391787
Created August 30, 2013 16:36
Access Redis from pyshell
from redis import Redis
r = Redis('host', db=1, password='pass')
r.keys(':1:cachekey*')
@jsatt
jsatt / gist:6391778
Created August 30, 2013 16:36
Build and upload Python package to pypi
python setup.py sdist bdist_egg upload
@jsatt
jsatt / gist:6391723
Last active April 13, 2016 13:31
stderr and stdout to file
# stdout to file
echo test > file.txt
# stdout append to file
echo test >> file.txt
# stderr to file
cmd 2> file.txt
# stderr to stdout
@jsatt
jsatt / venv_node
Last active December 21, 2015 07:38
A script for managing and installing nodejs within a Python virtualenv.
#!/bin/bash
TASK=$1
node_checksum() {
if [ "$1" = "$2" ]; then
return
elif [ -z $2 ]; then
echo 'Checksums empty' #missing in raspberry pi binary
return
@jsatt
jsatt / gist:6042104
Last active December 20, 2015 00:29
Class for dynamically generating a Django QuerySet from a list of Django objects of the same type.
from django.db.models.query import QuerySet
class QuerySetFromIter(QuerySet):
def __init__(self, objects=[], model=None, query=None, *args, **kwargs):
if model is None:
if len(objects):
model = type(objects[0])
else:
# TODO: find a better way to handle this