Skip to content

Instantly share code, notes, and snippets.

@shazow
shazow / gist:240045
Created November 21, 2009 07:41
Ported John Resig's Javascript pretty_date function to Python.
from datetime import datetime
import time
import math
def pretty_date(t):
"""
Take a datetime object or epoch time int, return a string representing
how long ago the date was.
Inspired by: http://ejohn.org/files/pretty.js
@shazow
shazow / gist:250137
Created December 6, 2009 08:59
Clever dumb object for faux proxy purposes.
class DumbObject(object):
def __init__(self, len=1):
self.len = len
def __call__(self, *args, **kw):
return self
def __getattr__(self, name):
return self
@shazow
shazow / meta.py
Created December 17, 2009 00:59
BaseModel object for SQLAlchemy declarative object abstractions (with query statistics tracking and JSON decoder).
"""SQLAlchemy Metadata and Session object"""
from sqlalchemy import MetaData
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.orm.session import Session as SessionBase
from sqlalchemy.interfaces import ConnectionProxy
from datetime import datetime
import time
__all__ = ['Session', 'metadata', 'BaseModel']
@shazow
shazow / gist:258443
Created December 17, 2009 01:44
Insane idea to let plain function actions and more complex callable class actions co-exist. (Now with less profanity.)
class AccountController(BaseController):
class login(BaseAction):
def __call__(self):
if 'username' in request.params:
return self.do_login
# Otherwise...
return self.draw_login
@shazow
shazow / grate.py
Created December 17, 2009 11:35
Silly but effective migration framework for small-ish datasets. Row-by-row re-insert between arbitrary database dialects supported by SQLAlchemy.
#!/usr/bin/env python
"""
Really silly schema migration framework, built for SQLAlchemy.
Example:
./grate.py "mysql://foo:bar@localhost/baz" "sqlite:///:memory:" \
--metadata model.meta:metadata --verbose
"""
import sqlalchemy
import sys
@shazow
shazow / apihandler.py
Created May 11, 2010 22:04
Google AppEngine API controller base.
from django.utils import simplejson
from google.appengine.ext.webapp import RequestHandler
import logging
log = logging.getLogger(__name__)
class APIException(Exception):
def __init__(self, msg, code=400):
self.msg = msg
@shazow
shazow / gist:411284
Created May 23, 2010 21:56
More concise handling of request parameters.
def get_many(d, required=[], optional=[], one_of=[]):
"""
Returns a predictable number of elements out of `d` in a list for auto-expanding.
Keys in `required` will raise KeyError if not found in `d`.
Keys in `optional` will return None if not found in `d`.
Keys in `one_of` will raise KeyError if none exist, otherwise return the first in `d`.
Example usage:
@shazow
shazow / gist:416755
Created May 28, 2010 04:36
Inspect whether a path of properties is eagerloaded or not. (Hack)
# Helper methods for an SQLAlchemy declarative base class.
def _is_loaded(self, key):
return key in self.__dict__
def _is_loaded_all(self, path):
"""
Check if the given path of properties are eager-loaded.
`path` is similar to sqlalchemy.orm.eagerload_all, checking happens
by inspecting obj.__data__.
@shazow
shazow / gist:418658
Created May 30, 2010 00:31
Pylons API base controller
API_METHOD_MAP = {}
def expose_api(name):
def decorator(fn):
API_METHOD_MAP[name] = fn
return fn
return decorator
class ApiController(BaseController):
@shazow
shazow / deprecated-routes.py
Created July 11, 2010 05:00
Hack for logging a deprecation warning when a deprecated route is visited.
# ...
import logging
log = logging.getLogger(__name__)
def warn_deprecated(environ, result):
log.warn("Deprecated route used: %s" % environ['PATH_INFO'])
return True
def make_map(config):