【问题标题】:how to connect python backend with flask and html&css如何将python后端与flask和html&css连接起来
【发布时间】:2021-01-12 03:19:57
【问题描述】:

''' 应用程序.py

from flask import Flask, render_template, request
from weather_backend import temperature_condition,clothes,feels_temperature,weather_description

app = Flask(__name__)
app.config["SECRET_KEY"] = "Secret-key"

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/dress")
def dress():
    cityname = request.form.get("city_name")

    temp = str(temperature_condition())
    message = str(clothes())
    feels = feels_temperature
    description= weather_description
    return render_template("dress.html", message=message, temp=temp, feels_temperature=feels, 
    weather_description=description )

if __name__ == "__main__":
    app.run(debug=True)

''' ''' weather_backend.py

import requests, json 
import weatherMappingMessage
from app import dress
from keys import *

base_url = "http://api.openweathermap.org/data/2.5/weather?"
city_name = 

complete_url = base_url + "appid=" + api_key + "&q=" + city_name + "&units=metric" 
response = requests.get(complete_url) 

''' HTML 文件 '''

<body>
<div class="head">
    <form action= "{{ url_for('dress') }}" class="form" method="GET">
        <h1>Get Weather and Dresses according to the Weather</h1>
        <div class = "form-box">
            <input type="text" class="search-field location" name= "city_name" placeholder="Location...">
            <button class="search-btn" type="button">Search</button>
        </div>
    </form>
</div>
</body>

'''

我需要将表单信息(搜索)从 HTML 获取到后端(城市名称),然后到烧瓶(城市名称)
如果尝试获取它,我可以从后端收到一条消息,但我无法将 HTML 表单发送到后端进行处理 我面临的问题是我无法将表单数据从我的 HTML 文件获取到我的后端进行处理 基本上,我需要后端的城市名称来获取我的天气描述

【问题讨论】:

  • 你好 Harshit soni,欢迎来到 SO!几乎很棒的第一个问题,只是一点指导使它变得更好(然后得到更好的答案):尝试更详细一点。你到底想达到什么目的?您如何尝试解决您的问题?您收到任何错误消息吗?如果是,你能包括那些吗?如果您为您的问题付出额外的努力,那么答案将很快出现 - 并且具有额外的价值!
  • 你好,Andrew 谢谢你的反馈,我尽量让它更容易理解
  • 你好,Akib 谢谢你的例子,我做了一些改变

标签: python html css flask


【解决方案1】:

简答:

由于您的表单提交使用get请求,您可以使用request.args获取查询字符串(see also)的解析内容:

cityname = request.args.get("city_name")

长答案:

我确定您要求的不仅仅是这段代码。我采用了您提供的代码并在线添加了缺失的部分(请不要对生产代码执行此操作)并将cityname 传递给render_template

import logging
from datetime import datetime

from flask import render_template, request

from app import app, forms


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/dress")
def dress():
    cityname = request.args.get("city_name")

    # missing in example code
    def temperature_condition():
        return 'temp cond'

    # missing in example code
    def clothes():
        return 'clothes'

    feels_temperature = 'feels temp'  # missing in example code
    weather_description = 'weather desc'  # missing in example code

    temp = str(temperature_condition())
    message = str(clothes())
    feels = feels_temperature
    description = weather_description
    return render_template("dress.html", message=message, temp=temp, feels_temperature=feels,
                           weather_description=description, cityname=cityname)  # also pass cityname

我创建了一个简约的dress.html

<html>
    <body>
        <p>message = {{ message }}</p>
        <p>temp = {{ temp }}</p>
        <p>feels_temperature = {{ feels_temperature }}</p>
        <p>weather_description = {{ weather_description }}</p>
        <p>cityname = {{ cityname }}</p>
    </body>
</html>    

通过flask run 启动应用程序允许我在表单字段中输入城市名称并查看结果(例如“柏林”):

为了显示所选城市的天气描述,您可以创建一个接受城市名称并从网络检索信息的函数(只是一个粗略的草图):

import requests, json
import weatherMappingMessage
from app import dress
from keys import *

def weather_for_city(city_name):
    base_url = "http://api.openweathermap.org/data/2.5/weather?"

    complete_url = base_url + "appid=" + api_key + "&q=" + city_name + "&units=metric"
    response = requests.get(complete_url)

    if response.status_code == 200:
        return response.json()  # assumes your API returns a JSON response
    else:
        # perform some error handling here, maybe apply a retry strategy
        pass

weather_for_city 的结果中提取相关数据并将其传递给render_template,就像您对其他变量所做的那样。

【讨论】:

    猜你喜欢
    • 2019-08-28
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多