Snippet List
I don't like not having the `range()/xrange()` in JavaScript — particularly when working with [Underscore.js](http://documentcloud.github.com/underscore/) and other such libraries — so I wrote it.
It's not rocket science, but it might help make the world a slightly less annoying place for a couple of people.
- javascript
- python
- list
- generator
- array
- builtin
- xrange
Just like it says -- set it up and run. Use it for server migrations, for project handoffs, in cron jobs, you name it.
I have never had problems exporting models to individual fixtures in this way, and only one bout of trouble re-importing them (and that was, like, an impossible-triangle of OneToOneField dependencies anyway, and they were going from a sqlite file to a postgres schema that totally had inappropriate nullable columns in it). I find that the json files named for what they contain is helpful when and if manage.py does freak out during an import, as the output from `loaddata` command is so opaque it's autistic, basically.
A trivial refactoring effort could make it into a management command -- it already makes use of the builtin `dumpdata` command class internally. However I did not feel like overthinking it enough to set it up in a repository (doubtlessly padded with unrelated 'utilities' and explanatory .rst files) and then writing a blog post to sell it to you. That is why you are reading this code here, instead of on GitHub.
Don't get me wrong, GitHub is awesome, and like a consummate host... but not the way I love me some quick and dirty snippet code, these days. Whatever, you say lazy, I say productively relaxed, potato/potahto.
Erm. In any case please do enjoy this model fixture-exporter. Yes.
- django
- python
- json
- export
- data
- script
- command
- archive
- django1.1
- backup
- datestamp
- tar
- tarball
Requires [PyISBN](http://pypi.python.org/pypi/pyisbn/0.5.2). Use like so:
class Book(models.Model):
title = models.TextField()
isbn = ISBNField()
... the link in the widget can be changed to amazon, borders, you name it.
If the DB version is a 13-digit ISBN, the display box contains the 10-digit,
labeled; and vice-versa.
- django
- model
- python
- widget
- modelfield
- isbn
- books
This is what I use to send simple status emails from my sites. Instead of a django.core.mail.send_mail call, which can take an irrritatingly, nondeterministically long time to return (regardless of error state), you can stow the emails in the database and rely on a separate interpreter process send them off (using a per-minute cron job or what have you). You then also have a record of everything you've sent via email from your code without having to configure your outbound SMTP server to store them or anything like that.
Usage notes are in the docstring; share and enjoy.
- django
- python
- email
- mail
- database
- queue
- asynchronous
The popular [django-tagging](http://code.google.com/p/django-tagging/) app has, in its implementation and semantics, a highly usable and transparent elegance -- but then you have to call methods on a Tag instances' items collection. These classes let you inline the tag name in the chain of queryset filter methods instead.
TO USE:
### models.py
...
from tagging.fields import TagField
from tagging.models import Tag as Tag
class YourModel(models.Model):
...
yourtags = TagField()
objects = TaggedManager()
...
### and then elsewhere, something like--
...
ym = YourModel.objects.order_by("-modifydate")[0]
anotherym = YourModel.objects.get(id=7) ## distinct from ym
ym.yourtags = "tag1 tag2"
anotherym.yourtags = "tag1 othertag"
ym.save()
anotherym.save()
with_tag1 = YourModel.objects.tagged('tag1')
with_tag2 = YourModel.objects.tagged('tag2').order_by('-modifydate')
print ym in with_tag1 ## True
print anotherym in with_tag1 ## True
print ym in with_tag2 ## False
... since these are QuerySets, you can easily create unions (e.g. `with_tag1 | with_tag2` and othersuch) as you need and filter them to your hearts' content, without having to instantiate Tag all the time (which you can of course do as well).
- manager
- queryset
- django-tagging
- django1.1
- chainable
I am not sure what to say about the state of PyAWS, or its future, what with the multiple forks available and lack of recent updates. The best version I've found is [http://github.com/IanLewis/pyaws](this one), a spiffed-up version of 0.2.2 by Ian Lewis. I wrote this class on top of PyAWS so I could have more pythonic/django-y calling conventions, and to isolate the calls in case I have to swap libraries or versions down the road.
You may want to familiarize yourself with PyAWS before using this. You'll definately need Amazon web service login credentials and keys -- they're available [here](http://aws.amazon.com/) for free.
personally I use it with [these monkeypatching and decorator-decorators](http://www.djangosnippets.org/snippets/1888/) -- at the top of my personal version of the file containing this snippet I use the two (non-silly) examples from that snippet, to make the PyAWS internal Bag collection class work for me.
EXAMPLE USE:
# search Amazon's product database (returns a list of nested dicts)
from amazon import aws
books = aws.search(q='raymond carver')
lenses = aws.search(q='leica summicron', idx='Photo')
# get the data for a specific ASIN/ISBN/EAN/etc ID number
what_we_talk_about_when_we_talk_about_love = aws.fetch(qid='0679723056', idtype='ASIN')
- decorator
- amazon
- amazonapi
- aws
- pyaws
as with all things related to monkeypatching, the caveat is to use things like these for good, and not for evil.
I wrote these decorators because I did not want to rewrite all of [PyAWS](http://github.com/IanLewis/pyaws) -- instead I use these to add some standard/useful methods to the Bag collection that PyAWS uses internally.
AN EXAMPLE:
class PatchMyMonkey:
pass
@monkeypatch(PatchMyMonkey)
def throwfecesat(self, who="nobody"):
print "Throwing Feces At: %s" % who
@monkeypatch(PatchMyMonkey)
def nicoderm(self, why="no reason"):
print "Trying To Quit Because: %s" % why
return {'why':str(why)}
trampstamp = PatchMyMonkey()
trampstamp.throwfecesat(who="another monkey")
print trampstamp.nicoderm(why="cigarettes are pricey")
A LESS SILLY EXAMPLE:
from pyaws import ecs
@monkeypatch(ecs.Bag, fname='get')
def get(self, param, *args, **kw):
return self.__dict__.get(param, *args, **kw)
@monkeypatch(ecs.Bag, fname='clearurls')
def clearurls(self, *args, **kw):
for k, v in self.__dict__.items():
if isinstance(self.__dict__[k], ecs.Bag):
self.__dict__[k].clearurls(*args, **kw)
if type(v) == type([]):
[ii.clearurls() for ii in self.__dict__[k]]
if type(v) == type(u''):
if self.__dict__[k].count(u'http://') > 0:
self.__dict__[k] = "<URL>"
(amazon's URLs are extremely long, and can muddle your test/log output, hence that last function.)
based on sample code from [here](http://pypi.python.org/pypi/decorator) and [here](http://mail.python.org/pipermail/python-dev/2008-January/076194.html).
- decorator
- monkeypatch
- decoratordecorator
- functionalprogramming
- usewithcare
fish2000 has posted 7 snippets.