How to access Flask session variables in HTML?

被刻印的时光 ゝ 提交于 2021-01-29 19:05:50

问题


I am trying to build a JavaScript function that will build the appropriate embed link for a specified user playlist in Spotify.

As of now, I have a session variable in my Flask app title 'playlist_id' that holds the Spotify playlist ID I want and a JavaScript function that should update the src attribute in the iframe element for embedded Spotify playlists.

@app.route("/playlist/build", methods=['GET', 'POST'])
def build():

    if request.method == 'GET':
        print(request.method)
        return render_template("loading.html")

    elif request.method == 'POST':
        print(request.method)
        # Twython
        OAUTH_TOKEN = session.get('auth_oauth_token')
        OAUTH_TOKEN_SECRET = session.get('auth_token_secret')
        OAUTH_VERIFIER = session.get('oauth_verifier')

        auth_client = Twython(consumer_key, consumer_secret, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
        auth_creds = auth_client.get_authorized_tokens(OAUTH_VERIFIER)

        twitter = Twython(consumer_key, consumer_secret, auth_creds['oauth_token'], auth_creds['oauth_token_secret']) # Authenticated Twython instance (used to access user Twitter account information)

        # Spotipy
        access_token = session.get("spotify_access_token")
        sp = spotipy.Spotify(auth=access_token) # Authenticated Spotipy instance (used to access user Spotify account information)

        # Collecting and filtering posted statuses from user's Twitter account for Spotify links
        t_screename = twitter.get_account_settings()['screen_name']
        statuses = get_user_statuses(t_screename, twitter)
        spotify_urls = filter_statuses(statuses)

        # Using found Spotify tracks to build a tracklist
        s_screename = sp.current_user()['display_name']
        tracks = build_track_uri_list(convert_url_to_track(sp, spotify_urls))

        # Creating playlist and adding found tracks (Note: Only adds most recent 100 songs ~ issues with limits on the Spotify API)
        playlist_id = create_spotify_playlist(sp, s_screename)
        add_tracks(sp, s_screename, playlist_id, tracks)

        session['playlist_id'] = playlist_id

        return 'done'
<iframe id="playlist-embed" src="getPlaylistLink()" width="300" height="380" frameborder="0" allowtransparency="true" allow="encrypted-media"></iframe>

    <script>
     function getPlaylistLink() {
         var playlist_id = {{ session['playlist_id'] }};
         var pid_string = playlist_id.toString();

         var embedUrlPrefix = "https://open.spotify.com/embed/playlist/";

         var src = embedUrlPrefix.concat(pid_string);
         // var src = 'https://open.spotify.com/embed/playlist/' + String(playlist_id);
         console.log(src);
         return src
      }
      document.onload = function() {
      document.getElementById('playlist-embed').src=getPlaylistLink();
      };
    </script>

I keep getting a 404 error for the URL returned from this function even though it seems to be correct when I post it in my browser. The console also seems to be catching the string as well so I'm just really confused on why the function is not working correctly.

An example of the console on a run of this app:

<script>
     function getPlaylistLink() {
         var playlist_id = 3n6Sa0lMIl4Dr293oUYspr;
         var pid_string = playlist_id.toString();

         var embedUrlPrefix = "https://open.spotify.com/embed/playlist/";

         var src = embedUrlPrefix.concat(pid_string);
         // var src = 'https://open.spotify.com/embed/playlist/' + String(playlist_id);
         console.log(src);
         return src
      }
      document.onload = function() {
      document.getElementById('playlist-embed').src=getPlaylistLink();
      };
</script>

回答1:


<iframe src="getPlaylistLink()"> - you can't put JavaScript there.

You have two options:

  • Don't specify a src initially (or use about:blank etc.) and set the src from your JavaScript code
  • Don't use JavaScript for it. You don't need it! You can just generate the src on the server:

    <iframe src="https://open.spotify.com/embed/playlist/{{ session.playlist_id }}">
    



回答2:


@ThiefMaster is right. You don't need to use javascript for this type of "custom" queries. Except if you want to perform updates of the link without reloading the page (for this it will loop on a GET request).

More : The value of the variable javascript "playlist_id" is a string, so it must be declared with var playlist_id = "{{ session['playlist_id'] }}";, so "pid_string" is not needed.



来源:https://stackoverflow.com/questions/58683671/how-to-access-flask-session-variables-in-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!