當前位置: 首頁>>代碼示例>>Python>>正文


Python models.Playlist類代碼示例

本文整理匯總了Python中models.Playlist的典型用法代碼示例。如果您正苦於以下問題:Python Playlist類的具體用法?Python Playlist怎麽用?Python Playlist使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Playlist類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: create_playlist

def create_playlist():
    playlist_json = request.json
    playlist = Playlist(request.json['name'])
    playlist.user_id = session['user_id']
    playlist.save()
    
    g.user.add_playlist(playlist)

    return ""
開發者ID:mcherkassky,項目名稱:listen,代碼行數:9,代碼來源:__init__.py

示例2: add

def add(request, animation):
    dajax = Dajax()
    dajax.remove_css_class('#movie-inspector label', 'error')

    animation = json.loads(animation)
    animation.update({
        'type': 'm',
        'user': request.user is None and '' or request.user.id,
    })

    if int(animation['max_duration']) > 60:
        animation['max_duration'] = 60

    movie_duration = 0
    for frame in animation['data']:
        frame['duration'] = int(frame['duration'])
        if frame['duration'] > 2000:
            frame['duration'] = 2000
        movie_duration += frame['duration']

    if movie_duration > 60000:
        dajax.script('MessageWidget.msg("Animation darf insgesamt nicht laenger als 60 Sekunden sein! Bitte Frames loeschen oder kuerzer anzeigen lassen!")')
        return dajax.json()
    
    form = AnimationForm(animation)

    if form.is_valid():
        a = form.save()

        p = Playlist(
            title = 'stub \'%s\' playlist' % form.cleaned_data['title'],
            user = User.objects.all()[0]
        )
        p.save()
        
        ai = AnimationInstance(
            playlist = p,
            animation = a
        )
        ai.save()

        # queue playlist
        sj = SpoolJob(
            playlist = p,
            priority = 2,
            added = datetime.now()
        )
        sj.save()

        dajax.script('MessageWidget.msg("Great success! Animootion mit ID %s gespeichert!")' % p.id)
    else:
        for error in form.errors:
            dajax.add_css_class('#movie-inspector label[for="%s"]' % error, 'error')
        dajax.script('MessageWidget.msg("Bitte fehlende Felder ausfuellen.")')

    return dajax.json()
開發者ID:alx,項目名稱:acabed,代碼行數:56,代碼來源:ajax.py

示例3: test_add_song_to_playlist

    def test_add_song_to_playlist(self):
        with gillard.app.app_context():
            song = Song()
            playlist = Playlist()

            playlist.songs = [song]

            playlist = test_utils.save_and_refresh(gillard.db.session, playlist)

            assert len(playlist.songs) == 1

            # cascading add
            assert playlist.songs[0].id is not None
開發者ID:spncrlkt,項目名稱:gillard,代碼行數:13,代碼來源:playlist_model_tests.py

示例4: generate_playlist

def generate_playlist(request):
    print(request.POST.keys())
    artists = request.POST.get("artists").replace('/', '\n').split('\n')
    if artists:
        client = soundcloud.Client(access_token=request.COOKIES['access_token'])
        print(artists)
        all_tracks = []
        for artist in artists:
            artist = artist.strip()
            print artist
            tracks = client.get('/tracks', q=artist, limit=20)
            short_tracks = []
            count = 0
            for track in tracks:
                max_tracks = int(request.POST.get("max_tracks"))
                if count > max_tracks:
                    break
                max_length = int(request.POST.get("max_length"))
                if max_length == 0 or track.duration < (max_length * 60 * 1000):
                    #Skip ones longer than max_length mins
                    count += 1
                    short_tracks.append(track)
            all_tracks.extend(track.id for track in short_tracks)
            print len(all_tracks)

        if request.POST.get("randomize"):
            print("Randomize = true")
            random.shuffle(all_tracks)

        # create an array of track ids
        all_tracks_ids = map(lambda id: dict(id=id), all_tracks)

        # create the playlist
        # FIXME: timeout more than ~400 sounds in total
        print("Creating Playlist...")
        ret = client.post('/playlists', playlist={
            'title': request.POST.get("title"),
            'sharing': "public", #TODO: cutomize this viw a tickbox
            'tracks': all_tracks_ids
        })
        try:
            user = client.get('/me')
            plst = Playlist(name=ret.title, author=user.username, author_id=user.uri, url=ret.permalink_url)
            plst.save()
        except Exception as exc:
            print("++ ERROR while trying to save the playlist: %s" % exc)
        print("Created %s available at: %s!" % (ret.title, ret.permalink_url))
        return HttpResponse(simplejson.dumps({"link": ret.permalink_url, "title": ret.title}), content_type="application/json")
    else:
        print("no artists found!")
        return HttpResponseServerError()
開發者ID:browniebroke,項目名稱:festilist,代碼行數:51,代碼來源:views.py

示例5: get_playlist

def get_playlist(user, name):
    """
    Checks to see if the user has a playlist named name
    If not, create the playlist
    :param user: User object
    :param name: String of name of playlist
    :return: Playlist owned by user, named name
    """
    search = Playlist.objects.filter(name=name, owner=user)
    if search.exists():
        return search[0]
    else:
        playlist = Playlist(owner=user, name=name)
        playlist.save()
        return playlist
開發者ID:ianhblakley,項目名稱:steazy-server,代碼行數:15,代碼來源:spotifyviews.py

示例6: createPlaylist

def createPlaylist(request, track_id, playlist_name, owner_id):
	created_by = User.objects.get(id=owner_id)
	new_list = Playlist(
		name = playlist_name,
		owner = created_by,
		pub_date = timezone.now(),
	)
	new_list.save()
	track = Track.objects.get(id=track_id)
	new_list.tracks.add(track)
	context = {
		'track' : track,
		'playlist' : new_list,
		'msg' : "has been added into the new playlist! "
	}
	return HttpResponseRedirect('/playlist/')
開發者ID:Jmq14,項目名稱:Back-End-Web,代碼行數:16,代碼來源:views.py

示例7: add_playlist

def add_playlist(request):
    postdata = request.POST.copy()
    track_slug = postdata.get('track_slug', '')
    p = get_object_or_404(Track, link = track_slug)
    playlist_list = get_playlist(request)
    track_in_playlist = False

    for list in playlist_list:
        if list.track.id == p.id :

            track_in_playlist = True
        if not track_in_playlist:
            ci = Playlist()
            ci.track = p
            ci.playlist_id = _playlist_id(request)
            ci.save()
開發者ID:param107,項目名稱:music_album,代碼行數:16,代碼來源:playlist.py

示例8: playlist_title_dicts

def playlist_title_dicts():
    return map(lambda playlist: {
        "title": playlist.title,
        "key": str(playlist.key()),
        "ka_url": playlist.relative_url, # remove once js clients update
        "url": playlist.relative_url
    }, Playlist.all())
開發者ID:KhanWorld,項目名稱:KhanAcademy,代碼行數:7,代碼來源:autocomplete.py

示例9: add_video

def add_video():
    playlist_id = request.form.get("playlist_id")
    if playlist_id.strip() == "":
        return jsonify({'error': "You must specify a playlist ID for this video."})

    playlist = Playlist.query.get(playlist_id)
    if playlist == None:
        return jsonify({'error': "Playlist not found"})

    slug = request.form.get("slug")
    if slug.strip() == "":
        return jsonify({'error': "You must specify a slug for this video."})

    thumbnail_url = request.form.get("thumbnail_url")
    if thumbnail_url.strip() == "":
        return jsonify({'error': "You must specify a thumbnail for this video."})

    title = request.form.get("title")
    if title.strip() == "":
        return jsonify({'error': "You must specify a title for this video."})

    v = Video(playlist_id, slug, thumbnail_url, title)
    db_session.add(v)
    db_session.commit()    

    # Publish to Redis so that all clients update playlist
    data = {
        "action": "update_playlist",
        "playlist": Playlist.get_videos(playlist_id)
    }

    redis.publish(playlist_id, json.dumps(data))

    return jsonify({"success": True})
開發者ID:camerongray1515,項目名稱:HackDee-2015,代碼行數:34,代碼來源:api.py

示例10: get_all_tracks_in_playlist

 def get_all_tracks_in_playlist(self, playlist_id):
     try:
         playlist = Playlist.get(playlist_id)
     except ValueError as e:
         raise
     tracks = playlist.get_all_tracks()
     ret = [track.__dict__ for track in tracks]
     return ret
開發者ID:estock,項目名稱:dogvibes,代碼行數:8,代碼來源:dogvibes.py

示例11: create_playlist

 def create_playlist(self, request):
     """ Creates a playlist for the user """
     # TODO: Max amount of playlists at 20 for a user
     user = Account.find_by_id(request.userid)
     if user is None:
         print "User not found" 
         return PlaylistResponse(errmsg="User ID not found")
     new_pl = Playlist.add_new_playlist(user.key, request.name)
     return PlaylistResponse(pid=new_pl.key.id())
開發者ID:chris-womack,項目名稱:Party-Queue,代碼行數:9,代碼來源:party_queue_api.py

示例12: playlist

def playlist(user_id):
    if request.method == 'GET':
        playlists = Playlist.objects().filter(user_id=user_id)
        return playlists.to_json()
    if request.method == 'POST':
        playlist = Playlist()
        playlist.user_id = user_id
        playlist.name = 'New Playlist'
        playlist.song_ids = []
        playlist.save()
        return playlist.to_json()
開發者ID:mcherkassky,項目名稱:listen,代碼行數:11,代碼來源:views.py

示例13: playlist_content_html

def playlist_content_html():
    """" Returns the HTML for the structure of the playlists as they will be
    populated ont he homepage. Does not actually contain the list of video
    names as those are filled in later asynchronously via the cache.
    
    """
    
    # No cache found -- regenerate HTML
    smart_history = getSmartHistoryContent()

    dict_playlists_by_title = {}
    all_playlists = []

    for playlist in Playlist.all():
        if playlist.title in topics_list:
            dict_playlists_by_title[playlist.title] = playlist

    for topic in topics_list:
        if topic in dict_playlists_by_title:
            playlist = dict_playlists_by_title[topic]
            video_count = playlist.get_video_count() 
            # 3 columns, 18px per row. This must be updated in conjunction
            # with code in homepage.js
            height = math.ceil(video_count / 3) * 18

            playlist_data = {
                             'title': topic,
                             'topic': topic,
                             'playlist': playlist,
                             'list_height': height,
                             'next': None,
                             }

            all_playlists.append(playlist_data)

    playlist_data_prev = None
    for playlist_data in all_playlists:
        if playlist_data_prev:
            playlist_data_prev['next'] = playlist_data
        playlist_data_prev = playlist_data

    timestamp = time.time()
    template_values = {
        'App' : App,
        'all_playlists': all_playlists,
        'smart_history': smart_history,
        
        # convert timestamp to a nice integer for the JS
        'timestamp': int(round(timestamp * 1000)),
        }

    html = shared_jinja.get().render_template("library_playlist_template.html",
                                              **template_values)
    Setting.cached_playlist_content_date(
            str(datetime.datetime.fromtimestamp(timestamp)))
    return html
開發者ID:KhanWorld,項目名稱:KhanAcademy,代碼行數:56,代碼來源:library.py

示例14: test_playlist_updated_at

    def test_playlist_updated_at(self):
        with gillard.app.app_context():
            playlist = Playlist()

            playlist = test_utils.save_and_refresh(
                gillard.db.session, playlist
            )

            # updated_at starts empty
            assert playlist.updated_at is None

            playlist.display_id = 'NEWTESTDISPID'

            playlist = test_utils.save_and_refresh(
                gillard.db.session, playlist
            )

            # on update, updated_at gets set to now-ish
            assert (datetime.datetime.now() - playlist.updated_at).\
                total_seconds() < 2
開發者ID:spncrlkt,項目名稱:gillard,代碼行數:20,代碼來源:playlist_model_tests.py

示例15: get_playlist

def get_playlist():
    playlist_id = request.args.get("playlist_id")

    # Now get the updated playlist and send it to the client
    videos = Video.query.filter(Video.playlist_id==playlist_id).order_by("rank desc")

    data = {
        "playlist": Playlist.get_videos(playlist_id)
    }

    return jsonify(data)
開發者ID:camerongray1515,項目名稱:HackDee-2015,代碼行數:11,代碼來源:api.py


注:本文中的models.Playlist類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。