Created
November 1, 2011 15:32
-
-
Save 0atman/1330824 to your computer and use it in GitHub Desktop.
"tracks to json playlist" rewrite
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Global evaluation
Your code has been rated at 10.00/10 (previous run: 9.33/10)