Skip to content

Instantly share code, notes, and snippets.

@0atman
Created November 1, 2011 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0atman/1330824 to your computer and use it in GitHub Desktop.
Save 0atman/1330824 to your computer and use it in GitHub Desktop.
"tracks to json playlist" rewrite
"""
Python features bingo.
I hope you enjoy reading this as much as I enjoyed writing it!
"""
import json
def tracks_to_json_playlist(tracks, playlist=None):
'''
Takes a queryset of tracks and returns a json playlist
'''
#create the function without the requirement for published tracks
track_to_dict = track_to_dict_published(False)
playlist_tracks = [track_to_dict(track) for track in tracks\
if track_to_dict(track)]
track_id = playlist.id if playlist else -1
name = playlist.name if playlist else "new"
tracks = playlist_tracks
return json.dumps({
"id" : track_id,
"name" : name,
"tracks" : playlist_tracks
})
def track_to_dict_published(published_required=True):
"""
closure wrapping track_to_dict with published optionality.
The returned function requires the track to be published if published_required
"""
def track_to_dict(track):
"""
accepts a track queryset and returns a dictionary representation,
minus some fudge.
Essentially, rebuilding a track into a serialisable Dictionary.
"""
track_dict = track.__dict__
del track_dict["_state"], track_dict["_artist_cache"]
track_dict["artist"] = str(track.artist)
#read this twice and you'll get it
return None if published_required and not track.published\
else track_dict
return track_to_dict
@0atman
Copy link
Author

0atman commented Nov 1, 2011

Global evaluation

Your code has been rated at 10.00/10 (previous run: 9.33/10)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment