Skip to content

Instantly share code, notes, and snippets.

View kezabelle's full-sized avatar

Keryn Knight kezabelle

View GitHub Profile
@kezabelle
kezabelle / test1.py
Last active August 29, 2015 13:55
Testing various ways to test a dictionary (say, a wsgi environ) for an AJAX request
stmt = """
environ = {
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'
}
if 'HTTP_X_REQUESTED_WITH' in environ:
result = environ['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'
"""
timeit.timeit(stmt=stmt, number=10000000)
# yields 2.7133121490478516
@kezabelle
kezabelle / querystring.py
Created January 27, 2014 08:37
for waverider on #django IRC
from django.http import QueryDict
new_querystring = QueryDict('a=1&b=2', mutable=True)
new_querystring.update({'c': 3, 'a': 4})
new_querystring.urlencode() # outputs 'a=1&a=4&c=3&b=2'
new_querystring['a'] = 5
new_querystring.urlencode() # outputs 'a=5&c=3&b=2'
@kezabelle
kezabelle / hmmm.py
Created January 7, 2014 12:11
Django's SimpleLazyObject says: "Designed for compound objects of unknown type. For builtins or objects of known type, use django.utils.functional.lazy." ... but they don't behave the same :(
# I have a known type ... it is X. I should use lazy() then ...
# but SimpleLazyObject "just works", while lazy is obstinate.
from django.utils.functional import lazy, SimpleLazyObject
from collections import namedtuple
X = namedtuple('X', ['a', 'b'])
y = lazy(lambda: X(a=1, b=2), X)
z = SimpleLazyObject(lambda: X(a=1, b=2))
@kezabelle
kezabelle / semistatic.md
Last active January 2, 2016 09:29
Implement a semistatic handler app for Django?
  • Provide middleware;
    • If user is anonymous, look for file in BUILD_DIR
      • If it exists, return it immediately
      • If it doesn't exist, call the view
      • If it doesn't exist and it returns a 2xx, write it to the builder
      • If it doesn't exist and it returns a 3xx, write the 30x.html template to the builder, pointing at the redirect endpoint
      • If it doesn't exist and it returns a 404, write the 404.html to the builder
    • If the user is not anonymous, render the original view, including other middlewares etc.
    • Middleware has an inclusions regex -- see django-moreloaders for regex ideas.
  • Provide builders;
@kezabelle
kezabelle / deploying.sh
Created December 20, 2013 15:29
Using django-js-error-hook and django-statictemplate together, so that the hook can be minified by django-compressor ...
...
$ python manage.py statictemplate > a_static_dir/error_hook.js
...
@kezabelle
kezabelle / filters.py
Created December 4, 2013 15:17
Reminder to self; convert a Django request path into a bunch of targeted CSS classes
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter
@stringfilter
def pathcss(val):
parts = list(val.strip('/').split('/'))
results = []
@kezabelle
kezabelle / ohlazy.py
Created November 30, 2013 17:35
None as a lazy() result...
>>> from django.utils.functional import lazy
>>> lazy(lambda: None, None)()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "django/utils/functional.py", line 181, in __wrapper__
return __proxy__(args, kw)
File "django/utils/functional.py", line 83, in __init__
self.__prepare_class__()
File "django/utils/functional.py", line 95, in __prepare_class__
for type_ in reversed(resultclass.mro()):
@kezabelle
kezabelle / explain.py
Created November 28, 2013 15:16
For NBhosting in #django IRC.
def runme():
return 1
def dontrunme():
return 2
a = {
'key1': runme,
'key2': runme,
'key3': dontrunme,
@kezabelle
kezabelle / thoughts.md
Last active December 29, 2015 15:29
Thoughts on rules on working in Django.
  • If you type MyModel.<manager>.filter anywhere, you're doing it wrong.
    • Either create a Manager and do it there, or, better yet, use django-model-utils's PassThroughManager and write a proper, chainable queryset.
    • Possibly better than that would just be to have a queries module, which contains functions that return the correct querysets. Seriously, tracking down queries being made is much easier if there's only one place to look.
  • If you're doing MyInstance.<related_name>.filter, I still hate you. Fix your manager/queryset or do that queries module I mentioned.
  • If you want to do anything to a field on a Form, do it via self.fields[<fieldname>] in the __init__ method. Everything else is crap.
  • If you're using a context processor and it touches the database, you'd better make it lazy() or I'll mow you down.
    • Seriously, otherwise it'll do queries for every RequestContext using view, even if it doesn't get used.
  • Use django-pdb, django-debug-toolbar and `django-devs
@kezabelle
kezabelle / forms.py
Created November 24, 2013 15:06
For Reflow on #django IRC
class MyForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['myfield'].label = 'hello'
class Meta:
model = MyModel