【问题标题】:How to access Flask session variables in HTML?如何在 HTML 中访问 Flask 会话变量?
【发布时间】:2019-11-03 19:06:20
【问题描述】:

我正在尝试构建一个 JavaScript 函数,该函数将为 Spotify 中的指定用户播放列表构建适当的嵌入链接。

截至目前,我的 Flask 应用程序标题“playlist_id”中有一个会话变量,其中包含我想要的 Spotify 播放列表 ID,以及一个 JavaScript 函数,该函数应该更新 iframe 元素中嵌入 Spotify 播放列表的 src 属性。

@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>

我不断收到从该函数返回的 URL 的 404 错误,即使当我在浏览器中发布它时它似乎是正确的。控制台似乎也正在捕获字符串,所以我真的很困惑为什么该功能无法正常工作。

运行此应用程序的控制台示例:

<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>

【问题讨论】:

  • 不要在会话中放置 oauth 机密 - 默认情况下,会话存储在 cookie 中,虽然用户无法修改它(已签名),但他们可以查看其内容(它只是 base64-编码的 JSON)。
  • var playlist_id = {{ session['playlist_id'] }}; 生成无效的 JS。添加 |tojson 过滤器将其转换为正确的 JS 字符串。当然,后面的toString() 电话就可以消失了。

标签: javascript html flask


【解决方案1】:

&lt;iframe src="getPlaylistLink()"&gt; - 你不能把 JavaScript 放在那里。

你有两个选择:

  • 最初不要指定 src(或使用 about:blank 等)并从 JavaScript 代码设置 src
  • 不要为此使用 JavaScript。你不需要它!您可以在服务器上生成 src:

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

【讨论】:

    【解决方案2】:

    @ThiefMaster 是对的。对于这种类型的“自定义”查询,您不需要使用 javascript。除非您想在不重新加载页面的情况下执行链接更新(为此它将在 GET 请求上循环)。

    更多:变量javascript“playlist_id”的值是一个字符串,所以必须用var playlist_id = "{{ session['playlist_id'] }}";声明,所以不需要“pid_string”。

    【讨论】:

    • 我之前尝试将 playlist_id 设置为 "{{ session['playlist_id'] }}",它读取的是实际字符串 "{{ session['playlist_id'' }}" 而不是变量包含的实际字符序列!
    • 如果是 jinja 模板并且你有 {{ ... }} 将被替换为内部表达式的结果。
    猜你喜欢
    • 2017-06-20
    • 2015-06-29
    • 2017-06-09
    • 2015-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    相关资源
    最近更新 更多