简体   繁体   English

如何访问 HTML 中的 Flask session 变量?

[英]How to access Flask session variables in HTML?

I am trying to build a JavaScript function that will build the appropriate embed link for a specified user playlist in Spotify.我正在尝试构建一个 JavaScript function ,它将为 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. 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.我不断收到从这个 function 返回的 URL 的 404 错误,即使我在浏览器中发布它似乎是正确的。 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.控制台似乎也在捕捉字符串,所以我真的很困惑为什么 function 不能正常工作。

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>

<iframe src="getPlaylistLink()"> - you can't put JavaScript there. <iframe src="getPlaylistLink()"> - 你不能把 JavaScript 放在那里。

You have two options:你有两个选择:

  • Don't specify a src initially (or use about:blank etc.) and set the src from your JavaScript code最初不要指定 src(或使用 about:blank 等)并从 JavaScript 代码中设置 src
  • Don't use JavaScript for it.不要为此使用 JavaScript。 You don't need it: You can just generate the src on the server:你不需要它:你可以在服务器上生成 src:

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

@ThiefMaster is right. @ThiefMaster 是对的。 You don't need to use javascript for this type of "custom" queries.对于这种类型的“自定义”查询,您不需要使用 javascript。 Except if you want to perform updates of the link without reloading the page (for this it will loop on a GET request).除非您想在不重新加载页面的情况下执行链接更新(为此它将在 GET 请求上循环)。

More: The value of the variable javascript "playlist_id" is a string, so it must be declared with var playlist_id = "{{ session['playlist_id'] }}";更多:变量javascript "playlist_id" 的值是一个字符串,所以必须用var playlist_id = "{{ session['playlist_id'] }}"; , so "pid_string" is not needed. ,因此不需要“pid_string”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM