簡體   English   中英

運行時請求 api 不起作用(如果 request.method == 'POST'):

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

我正在嘗試從 api 獲取信息,但是在提出請求時 (. response = requests.get(f'https://api.openweathermap.org/data/2.5/weather?q={city},{state} &appid={API_KEY}') ) 內

(如果 request.method == 'POST' )並且它不起作用。 有錯誤消息,但在使用“信息”渲染模板時沒有任何顯示。

應用程序

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')

索引.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>

試試這個

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM