简体   繁体   中英

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://api.openweathermap.org/data/2.5/weather?q={city},{state}&appid={API_KEY}') ) 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: {{info}}
    </p>
</body>

try this

import requests, json

# Enter your API key here
api_key = "Your_API_Key"

# base_url variable to store url
base_url = "http://api.openweathermap.org/data/2.5/weather?"

# Give city name
city_name = input("Enter city name : ")

# complete_url variable to store
# complete url address
complete_url = base_url + "appid=" + api_key + "&q=" + city_name

# get method of requests module
# return response object
response = requests.get(complete_url)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM