如何在 HTML 中显示来自 python 的变量 JSON 数据

问题描述 投票:0回答:1

我一直在使用 Spotify 的 API 开发播放列表管理器。现在我有一个 python 脚本,它从 API 获取数据并返回一个 json 文件,但我想将数据导入到 html 表中,以便对其进行样式设置并使其具有交互性。 本质上我需要这样做,但在Python中。 我尝试使用 json2html,但这只是返回 python 文件中的数据,我希望将数据放入 html 文件中进行样式设置。我对 python 中的 html 编码一无所知,因此对于我的情况可能有一个更简单的解决方案,但我找不到任何可以应用的东西。这是我的 python 脚本中的返回函数

def get_playlists():
    if 'access_token' not in session:
        return redirect('/login')

    if datetime.now().timestamp() > session['expires_at']:
        return redirect('/refresh-token')

    headers = {
        'Authorization': f"Bearer {session['access_token']}"
    }

    response = requests.get(f'{API_BASE_URL}/playlists', headers=headers)
    return response.json()

returns encoded json data of response

python html json python-3.x spotify
1个回答
0
投票

通过执行以下步骤,您可以创建一个 Python Flask 应用程序,该应用程序从外部源 (Spotify) 获取播放列表曲目并将其显示在网页上的 HTML 表格中。

此代码可以工作。

替换为您的设置

来自您的 Spotify 开发者仪表板。

CLIENT_ID = "your Client Id"
CLIENT_SECRET = "your Client Id"
PORT = 3000 # your callback port 
REDIRECT_URI = f'http://localhost:{PORT}/callback'
PLATLIST_ID = 'your play list ID'

Python 代码

另存为

app.py

from flask import Flask, redirect, request, session, send_from_directory
import requests
import json

app = Flask(__name__, static_url_path='', static_folder='')
app.secret_key = '1234' # OR your_secret_key

CLIENT_ID = "your Client Id"
CLIENT_SECRET = "your Client Id"
PORT = 3000 # your callback port 
REDIRECT_URI = f'http://localhost:{PORT}/callback'
PLATLIST_ID = 'your play list ID'

SCOPE = [
    'user-read-private',
    'playlist-read-private'
]

def format_duration(duration_ms):
    minutes = duration_ms // 60000
    seconds = (duration_ms % 60000) / 1000
    return f"{minutes}:{int(seconds):02d}"

def get_token(code):
    data = {
        'grant_type': 'authorization_code',
        'redirect_uri': REDIRECT_URI,
        'code': code,
    }
    auth = (CLIENT_ID, CLIENT_SECRET)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post('https://accounts.spotify.com/api/token', data=data, auth=auth, headers=headers)
    return response.json()['access_token']

def get_playlist_tracks(token, playlist_id):
    headers = {'Authorization': f'Bearer {token}'}
    response = requests.get(f'https://api.spotify.com/v1/playlists/{playlist_id}/tracks', headers=headers)
    tracks = response.json()['items']
    formatted_tracks = []
    for item in tracks:
        track = item['track']
        formatted_track = {
            'name': track['name'],
            'artist': ', '.join(artist['name'] for artist in track['artists']),
            'album': track['album']['name'],
            'album_image_url': track['album']['images'][2]['url'],
            'external_url': track['external_urls']['spotify'],
            'duration': format_duration(track['duration_ms']),
            'id': track['id']
        }
        formatted_tracks.append(formatted_track)
    return formatted_tracks

@app.route('/login')
def login():
    return redirect(f"https://accounts.spotify.com/authorize?response_type=code&client_id={CLIENT_ID}&scope={' '.join(SCOPE)}&state=123456&redirect_uri={REDIRECT_URI}&prompt=consent")

@app.route('/callback')
def callback():
    code = request.args.get('code')
    session['access_token'] = get_token(code)
    session['playlist_tracks'] = get_playlist_tracks(session['access_token'], PLATLIST_ID)
    return redirect('/')

@app.route('/')
def index():
    return send_from_directory(app.static_folder, 'index.html')


@app.route('/playlist')
def playlist():
    playlist_tracks = session.get('playlist_tracks', [])
    return json.dumps(playlist_tracks)

if __name__ == '__main__':
    app.run(port=PORT)

HTML 代码

另存为

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Playlist Tracks</title>
    <style>
        table {
            border-collapse: collapse;
            width: 80%;
            margin: 20px auto;
        }
        th, td {
            border: 1px solid #dddddd;
            text-align: left;
            padding: 8px;
        }
        th {
            background-color: #f2f2f2;
        }
        .album-image-container {
            display: flex;
            justify-content: center;
        }
        .album-image {
            max-width: 50px;
        }
    </style>
</head>
<body>
    <h1>Playlist Tracks</h1>
    <table>
        <tr>
            <th>Album Image</th>
            <th>Name</th>
            <th>Artist</th>
            <th>Album</th>
            <th>External URL</th>
            <th>Duration</th>
            <th>ID</th>
        </tr>
        <!-- Playlist tracks will be dynamically inserted here -->
    </table>
    <script>
        fetch('/playlist')
            .then(response => response.json())
            .then(tracks => {
                const table = document.querySelector('table');
                tracks.forEach(track => {
                    const row = table.insertRow();
                    const albumImageCell = row.insertCell();
                    const albumImageContainer = document.createElement('div');
                    albumImageContainer.className = 'album-image-container';
                    albumImageCell.appendChild(albumImageContainer);
                    if (track.album_image_url) {
                        const img = document.createElement('img');
                        img.src = track.album_image_url;
                        img.alt = 'Album Image';
                        img.className = 'album-image';
                        albumImageContainer.appendChild(img);
                    } else {
                        albumImageCell.textContent = 'N/A';
                    }
                    row.insertCell().textContent = track.name;
                    row.insertCell().textContent = track.artist;
                    row.insertCell().textContent = track.album;
                    row.insertCell().innerHTML = `<a href="${track.external_url}" target="_blank">External URL</a>`;
                    row.insertCell().textContent = track.duration;
                    row.insertCell().textContent = track.id;
                });
            })
            .catch(err => console.error('Error fetching playlist tracks:', err));
    </script>
</body>
</html>

安装依赖项

pip install Flask
pip install requests

运行它

python app.py

通过浏览器登录

使用您的 Spotify 帐户凭据

http://localhost:3000/login

结果

它是模仿 Spotify 官方 UI 的版本

© www.soinside.com 2019 - 2024. All rights reserved.