我正在尝试从 api 获取信息,但是在提出请求时 (. response = requests.get(f'https://api.openweathermap.org/data/2.5/weather?q={city}, {state}&appid={API_KEY}') ) 内部
( 如果 request.method == 'POST' ) 它不起作用。有错误消息,但在渲染带有“信息”的模板时没有任何显示。
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>
答案 0 :(得分:-1)
试试这个
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)