Geek7 commited on
Commit
6b6ca30
·
verified ·
1 Parent(s): 9fe15fd

Create myapp.py

Browse files
Files changed (1) hide show
  1. myapp.py +54 -0
myapp.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify, redirect, render_template
2
+ import requests
3
+ import os
4
+ from flask_cors import CORS
5
+
6
+ # Change the app instance name to myapp
7
+ myapp = Flask(__name__)
8
+ CORS(myapp)
9
+
10
+ # Access the secrets from environment variables in Hugging Face
11
+ CLIENT_ID = os.getenv('v1') # Your Client ID
12
+ CLIENT_SECRET = os.getenv('v2') # Your Client Secret
13
+ REDIRECT_URI = 'http://127.0.0.1:5000/callback'
14
+ SPOTIFY_AUTH_URL = "https://accounts.spotify.com/authorize"
15
+ SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token"
16
+ SPOTIFY_API_URL = "https://api.spotify.com/v1"
17
+
18
+ # Home route
19
+ @myapp.route('/')
20
+ def home():
21
+ return render_template('index.html')
22
+
23
+ # Get Spotify authorization URL
24
+ @myapp.route('/login')
25
+ def login():
26
+ scopes = "user-read-private user-read-email"
27
+ auth_url = f"{SPOTIFY_AUTH_URL}?response_type=code&client_id={CLIENT_ID}&scope={scopes}&redirect_uri={REDIRECT_URI}"
28
+ return redirect(auth_url)
29
+
30
+ # Callback to handle the access token
31
+ @myapp.route('/callback')
32
+ def callback():
33
+ code = request.args.get('code')
34
+ auth_response = requests.post(SPOTIFY_TOKEN_URL, data={
35
+ "grant_type": "authorization_code",
36
+ "code": code,
37
+ "redirect_uri": REDIRECT_URI,
38
+ "client_id": CLIENT_ID,
39
+ "client_secret": CLIENT_SECRET,
40
+ })
41
+ response_data = auth_response.json()
42
+ access_token = response_data.get("access_token")
43
+ return jsonify({"access_token": access_token})
44
+
45
+ # Fetch data from Spotify API
46
+ @myapp.route('/api/podcasts')
47
+ def get_podcasts():
48
+ token = request.args.get('token') # Pass access_token as a query param
49
+ headers = {"Authorization": f"Bearer {token}"}
50
+ response = requests.get(f"{SPOTIFY_API_URL}/browse/categories/podcasts", headers=headers)
51
+ return jsonify(response.json())
52
+
53
+ if __name__ == '__main__':
54
+ myapp.run(debug=True)