【发布时间】:2021-06-26 20:06:17
【问题描述】:
我正在尝试从 api 获取信息,但是在发出请求时 (. response = requests.get(f'https://api.openweathermap.org/data/2.5/weather?q={city}, {state}&appid={API_KEY}') ) 内的
(如果 request.method == 'POST' ) 它不起作用。使用“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>
【问题讨论】:
-
“有错误信息 [原文如此]” 你没有给我们看?
-
我已经更新了我的 cmets 答案