from flask import Flask, render_template, url_for, redirect, session, request
import json
import requests

app = Flask(__name__)

# access_token required
access_token = '503983410507122'

@app.route('/', methods=['POST','GET'])
def index():
    if request.method == 'POST':

        # getting the value from input field
        get_name = request.form['typehero']

        base_url = f'https://superheroapi.com/api/{access_token}/search/{get_name}'

        # storing the response generated by the base_url
        r = requests.get(base_url)
        data = r.json()

        # attributes of the data displayed
        results = data['results'][0]
        name = results['name']
        image = results['image']['url']
        biography = results['biography']
        powerstats = results['powerstats']
        if len(biography['aliases']) >= 5:
            alias = biography['aliases'][:5]
        else:
            alias = biography['aliases']
        # returning a render_template
        return render_template('index.html',name = name,image = image,biography = biography,powerstats = powerstats,alias = alias)
    else:
        return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)
