コード例 #1
0
def search():
    query = request.args.get('query')
    try:
        resp = spotify.get(f'/v1/search?q={query}&type=track&market=US').json()
    except TokenExpiredError:
        return Response(status=401)
    return resp
コード例 #2
0
def stream():
    #Makes sure the user is signed into spotify and if they are not takes them to the log in page.
    if not spotify.authorized:
        return redirect(url_for('spotify.login'))
    try:
        #Retrieves the data from the survey
        if request.method == 'POST':
            answers = request.form.to_dict()
            #Based on the answer sets the mode or key to major (1) or minor (0)
            if answers["4"] == "1" or answers["4"] == "2":
                mode = "0"
            else:
                mode = "1"
            #Creates the string containing the data that will be included in the Spotify get request
            search_string = ('seed_genres=' + answers["genre"] +
                             '&target_danceability=' + answers["3"] +
                             '&target_energy=' + answers["2"] +
                             '&target_instrumentalness=' + answers["5"] +
                             '&target_loudness=' + answers["0"] +
                             '&target_mode=' + mode + '&target_popularity=' +
                             answers["1"])
            resp = spotify.get(f'v1/recommendations?limit=1&{search_string}')

            return render_template('musicRecommendation_stream.html',
                                   data=(resp.json()["tracks"][0]))
    except (InvalidGrantError, TokenExpiredError) as e:
        return redirect(url_for('spotify.login'))
コード例 #3
0
ファイル: spotify.py プロジェクト: tannercyost/cst205team5
def index():
    if not spotify.authorized:
        return redirect(url_for('spotify.login'))
    search_string = urllib.parse.quote(
        'spotify:user:7q6bntim8y6tivg1730gd26k6:playlist:3cO8zP0McOaWbvDsOARPyE'
    )
    resp = spotify.get(
        search_string(f'v1/search?q={search_string}&type=playlist'))
    return render_template('home.html', data=resp.json())
コード例 #4
0
def index():
    if not spotify.authorized:
        # return {'url': url_for('spotify.login')}
        return redirect(url_for('spotify.login'))
    try:
        resp = spotify.get("/v1/me")
        assert resp.ok, resp.text
    except (InvalidGrantError, TokenExpiredError) as e:
        return redirect(url_for("spotify.login"))
    return redirect('http://localhost:3000/')
コード例 #5
0
ファイル: test_spotify.py プロジェクト: imfht/flaskapps
def test_context_local(make_app):
    responses.add(responses.GET, "https://google.com")

    # set up two apps with two different set of auth tokens
    app1 = make_app(
        "foo1",
        "bar1",
        redirect_to="url1",
        storage=MemoryStorage({"access_token": "app1"}),
    )
    app2 = make_app(
        "foo2",
        "bar2",
        redirect_to="url2",
        storage=MemoryStorage({"access_token": "app2"}),
    )

    # outside of a request context, referencing functions on the `spotify` object
    # will raise an exception
    with pytest.raises(RuntimeError):
        spotify.get("https://google.com")

    # inside of a request context, `spotify` should be a proxy to the correct
    # blueprint session
    with app1.test_request_context("/"):
        app1.preprocess_request()
        spotify.get("https://google.com")
        request = responses.calls[0].request
        assert request.headers["Authorization"] == "Bearer app1"

    with app2.test_request_context("/"):
        app2.preprocess_request()
        spotify.get("https://google.com")
        request = responses.calls[1].request
        assert request.headers["Authorization"] == "Bearer app2"
コード例 #6
0
def logged_in(blueprint: Blueprint, token: TokenDetails) -> None:
    logger.info(token)
    user_details = spotify.get("/v1/me").json()
    username = user_details["id"]

    user = User.get_by_username(username)
    if user is None:
        user = User.add(username=username)

    user.token_data = token

    session["spotify_username"] = username
    db.session.commit()
コード例 #7
0
ファイル: image.py プロジェクト: HelloRusk/spotify-wordcloud
def text_and_hash_generation(session):
    data = spotify.get("/v1/me/top/artists?limit=50").json()

    artists = []

    for i, item in enumerate(data["items"]):
        for _ in range((50 - i) // 10):
            artists.append(item["name"])

    random.shuffle(artists)
    text = " ".join(artists)
    session["spotify_wordcloud_text"] = text  # save text
    ha = hashlib.md5(text.encode("utf-8")).hexdigest()
    session["spotify_wordcloud_hash"] = ha  # save hash
コード例 #8
0
def get_and_update_db(most_recent):
    try:
        # resp = spotify.get(f'/v1/me/player/recently-played?limit=50&before={int(timestamp)}').json() use when API beta is over and fixed
        resp = spotify.get(f'/v1/me/player/recently-played?limit=50').json()

    except TokenExpiredError:
        raise TokenExpiredError

    # get the most recent songs to update db
    for played in resp['items']:
        try:
            date = played['played_at']

            if date <= most_recent:
                break
            name = played['track']['name']
            song_id = played['track']['uri'].split(':')[
                2]  # todo: change to ID
            artist = played['track']['artists'][0]['name'] if len(played['track']['artists']) <= 1 else \
                played['track']['artists'][0]['name'] + " and others"
            desc = ''
            image = played['track']['album']['images'][-1][
                'url']  # get link to smallest image
            preview = played['track']['preview_url']
            link = played['track']['external_urls']['spotify']
            # parse datetime ex. 2020-08-20T21:43:25.567Z
            year, month, *_ = date.split('-')

            # declare period
            period = SEASONS[int(month)]
            dbInterface.add_song(name=name,
                                 song_id=song_id,
                                 artist=artist,
                                 desc=desc,
                                 period=period,
                                 year=year,
                                 date=date,
                                 image=image,
                                 preview=preview,
                                 link=link)
        except AttributeError:
            print("ERROR when adding songs")  # skip this one
コード例 #9
0
def makeRequest(url):
    spotify.get(url).json()
コード例 #10
0
def topSongs():
    time_periods = ['medium_term', 'short_term'
                    ]  # , 'long_term'] todo: find where to add long term
    added_songs = set()
    try:
        today = datetime.now()
        for term in time_periods:
            resp = spotify.get(f'/v1/me/top/tracks?time_range={term}').json()
            for song in resp['items']:
                try:
                    song_id = song['id']
                    if song_id not in added_songs:
                        name = song['name']
                        artist = song['artists'][0]['name'] if len(
                            song['artists']
                        ) <= 1 else song['artists'][0]['name'] + " and others"
                        image = song['album']['images'][-1]['url']
                        year = (today - timedelta(
                            days=180 if term == 'medium_term' else 30)).year
                        preview = song['preview_url']
                        link = song['external_urls']['spotify']
                        date = '{}-{:02d}-{:02d}T00:00:00.000Z'.format(
                            year, 1, 1)  # 2020-08-26T00:25:10.291Z
                        added_songs.add(song_id)  # don't allow repeats
                        dbInterface.add_song(name=name,
                                             artist=artist,
                                             desc='',
                                             year=year,
                                             date=date,
                                             song_id=song_id,
                                             saved=True,
                                             image=image,
                                             preview=preview,
                                             link=link)
                except AttributeError:
                    print("ERROR with adding top song")  # skip

        # get from Your Top Songs playlist
        resp = spotify.get(
            f'/v1/search?q=your%20top%20songs&type=playlist').json()
        if resp:
            for item in resp.get('playlists', {'items': []}).get('items', []):
                try:
                    if item['owner']['id'] == 'spotify' and item[
                            'name'][:14] == 'Your Top Songs':
                        # add songs in this playlist to the specified year
                        year = int(item['name'][15:])
                        playlist_id = item['id']
                        songResp = spotify.get(
                            f'v1/playlists/{playlist_id}/tracks').json()
                        if songResp:
                            for song in songResp['items']:
                                try:
                                    song_id = song['track']['id']
                                    popularity = int(
                                        song['track']['popularity'])
                                    if song_id not in added_songs and popularity > 50:
                                        name = song['track']['name']
                                        artist = song['track']['artists'][0]['name'] if len(song['track']['artists']) <= 1 else \
                                            song['track']['artists'][0]['name'] + " and others"
                                        image = song['track']['album'][
                                            'images'][-1][
                                                'url']  # get link to smallest image
                                        preview = song['track']['preview_url']
                                        link = song['track']['external_urls'][
                                            'spotify']
                                        date = '{}-{:02d}-{:02d}T00:00:00.000Z'.format(
                                            year, 1,
                                            1)  # 2020-08-26T00:25:10.291Z
                                        dbInterface.add_song(name=name,
                                                             song_id=song_id,
                                                             artist=artist,
                                                             desc='',
                                                             year=year,
                                                             date=date,
                                                             image=image,
                                                             preview=preview,
                                                             link=link,
                                                             saved=True)
                                except AttributeError:
                                    print(
                                        "ERROR in adding playlist song top songs"
                                    )
                except AttributeError:
                    print('ERROR in adding playlist top songs')

    except TokenExpiredError:
        raise TokenExpiredError
コード例 #11
0
def spotify_logged_in(blueprint, token):
    session.clear()

    profile = spotify.get("v1/me").json()
    session["user_id"] = profile["id"]
コード例 #12
0
ファイル: app.py プロジェクト: ParksAaron/cst205
def index():
    if not spotify.authorized:
        return redirect(url_for('spotify.login'))
    search_string = urllib.parse.quote('The Birthday Party')
    resp = spotify.get(f'v1/search?q={search_string}&type=artist')
    return render_template('home.html', data=resp.json())
コード例 #13
0
ファイル: spotifyConfig.py プロジェクト: Ubishakha/team3revue
def index():
    if not spotify.authorized:
        return redirect(url_for("spotify.login"))
    resp = spotify.get("/user")
    assert resp.ok
    return "You are @{login} on Spotify".format(login=resp.json()["login"])