【问题标题】:request to api not working when running a (if request.method == 'POST'):运行时对 api 的请求不起作用(如果 request.method == 'POST'):
【发布时间】: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 答案

标签: python api flask


【解决方案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)

【讨论】:

    猜你喜欢
    • 2018-03-05
    • 2018-01-30
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多