如何在python Flask中获取下拉菜单

时间:2021-01-21 12:39:23

标签: python html flask openweathermap

所以,基本上,如果我在城市名称中出现拼写错误,则会出现错误 404/200

所以我想通过提供下拉菜单来消除错误

或任何其他解决方案都会有帮助

我正在使用 openweatherapi 获取天气数据并使用 Flask 来运行它

HTML 内容

<div class="forecast-table">
<div class="container">
    <div class="forecast-container">
        <div class="today forecast">
            <div class="forecast-header">
                <div class="day">Today</div>
            </div>
            <div class="forecast-content">
                <div class="location">{{ cityname }}</div>
                <div class="degree">
                <div class="num">{{ temp }}<sup>o</sup>C</div>
                <div class="forecast-icon">
                    <img src="{{ url_for('static', filename='images/icons/icon-1.svg') }}" alt="icon-1" width=90>
                </div>  
            </div>
            <span><img src="{{ url_for('static', filename='images/icon-water.png') }}" height="23" width="21"alt="">{{ humid }}</span>
            <span><img src="{{ url_for('static', filename='images/icon-wind.png') }}" alt="">{{ wind_speed }}km/h</span>
            <span><img src="{{ url_for('static', filename='images/icon-compass.png') }}" alt="">{{ wind_direction }}</span>
        </div>
    </div>

python app.py(路由内容)

    from flask import Flask, render_template, request, redirect
    from weather_backend import get_weather, get_attire
    import csv

    @app.route("/", methods=['GET','POST'])
    @app.route("/landing_page", methods=['GET','POST'])
    def dress():
        city_name = request.form.get("city_name")
        app.logger.info(f'city name={city_name}')
        result = get_weather(city_name)
        humid = result["humidity"]
        wind_speed = result["wind_speed"]
        wind_direction = result["wind_direction"]
        temp = int(result["temperature"])
        feels = result["feels_temperature"]
        description = result["weather_description"]
        icon = result["icons"]
        message = str(get_attire(result))
        email = request.form.get("email")
        if email is not None:
            with open('user_data/sub_email.csv', mode='a') as file_:
                file_.write("Email:{}".format(email))
                file_.write("\n")

        return render_template("landing_page.html", wind_speed=wind_speed, wind_direction=wind_direction, cityname=city_name, message=message, temp=temp, humid=humid,feels=feels, weather_description=description, icon = icon)

python weather_backend.py

def get_weather(city_name):
base_url = "http://api.openweathermap.org/data/2.5/weather?"
complete_url = base_url + "appid=" + keys.api_key + "&q=" + str(city_name) + "&units=metric" 
api_response = (requests.get(complete_url)).json()

print("api_response", api_response)

try:
    weather_values = api_response["main"]
    current_temperature = weather_values["temp"]# [] is keys() method to call/add something
    current_pressure = weather_values["pressure"] 
    current_humidity = weather_values["humidity"]
    feels_temperature = weather_values["feels_like"]

    wind = api_response["wind"]
    wind_speed = wind["speed"]
    wind_direction = wind["deg"]

    weather_desc = api_response["weather"] 
    weather_description = weather_desc[0]["description"]
    ids = weather_desc[0]["id"]
    icons = weather_desc[0]["icon"]
    print(f' Temperature (in celsius unit) = {current_temperature} '
        f'Feels like(in celsisu unit) =  {feels_temperature}'
        f'atmospheric pressure (in Pa unit) = {current_pressure}'
        f'humidity (in percentage) = {current_humidity}'
        f'description = {weather_description}'
        f'wind_speed(in meters/sec) = {wind_speed}'
        f'wind_direction(in deg) = {wind_direction}'
        f'id of des = {ids}'
        f'icon = {icons}')

except requests.exceptions.HTTPError as e:
    if e.response.cod == 400:
        print(e)
        pass  
return {
    "wind_speed":wind_speed,
    "wind_direction":wind_direction,
    "ids":ids,
    "temperature":current_temperature,
    "feels_temperature":feels_temperature,
    "pressure":current_pressure,
    "humidity":current_humidity,
    "weather_description":weather_description,
    "icons":icons,
}

0 个答案:

没有答案