Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to connect python backend with flask and html&css

''' app.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 file '''

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

'''

I need to get the form info(search) from HTML to the backend(city_name) and then to the flask(cityname)
I can get a message from the backend if try to get it but I can't get HTML form to the backend for processing The problem I'm facing is that I can't get the form data from my HTML file to my backend for processing basically, I need the cityname to the backend for getting my weather description

like image 580
Harshit soni Avatar asked Mar 01 '26 00:03

Harshit soni


1 Answers

Short answer:

Because your form submission uses a get request, you can use request.args to get parsed contents of query string (see also):

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

Long answer:

I'm sure you're asking for more than just this piece of code. I took the code you provided and added the missing pieces in-line (please don't do this for production code) and also passed cityname to 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

I created a minimalistic 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>    

Starting the application via flask run allows me to input a city name into the form field and view the results (for example 'Berlin'):

rendered result of dress.html for city_name=Berlin

In order to show the weather description for the chosen city, you could create a function that accepts the city name and retrieves the information from the web (just a rough sketch):

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

Extract the relevant data from the result of weather_for_city and pass it to render_template like you did for the other variables.

like image 69
oschlueter Avatar answered Mar 03 '26 12:03

oschlueter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!