2021-06-27

request to api not working when running a (if request.method == 'POST'):

I'm trying to get information from an api but when putting the request (. response = requests.get(f'https://ift.tt/2T0CAjL) ) inside of a

( if request.method == 'POST' ) and it doesn't work. There are error message but nothing shows up when rendering the template with "info".

app.py

import requests
from flask import Flask, render_template, request, url_for, jsonify

app = Flask(__name__)

API_KEY = 'cf1ba5705d163229bc037029fc311718'


@app.route('/', methods=['POST', 'GET',])
def home():
    if request.method == 'POST':
        state = (request.form['state-location'])
        city = (request.form['city-location'])
        response = requests.get(f'https://api.openweathermap.org/data/2.5/weather?q={city},{state}&appid={API_KEY}')
        info = response.json()['main']
        return render_template('index.html', info=info)
    else:
        return render_template('index.html')

index.html

<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8">
    <title>Home</title>
</head>
<body>
    <h1>Home</h1>
    <form>
        <label for="state-location">State</label>
        <label for="city-location">City</label>
        <input type="text" name="state-location" id="state-location" placeholder="state">
        <input type="text" name="city-location" id="city-location" placeholder="city">
        <input type="submit" name="submit-btn" value="submit" id="submit-btn">
    </form>
    <p>
        INFO: 
    </p>
</body>


from Recent Questions - Stack Overflow https://ift.tt/3h7F3AH
https://ift.tt/eA8V8J

No comments:

Post a Comment