3

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

  • 1
    Hello Harshit soni, welcome to SO! Almost great first question, just a bit of guidance to make it even better (and then get better answers): try to be a little bit more elaborate. What exactly are you trying to achieve? How have you already tried resolving your issue? Do you get any error messages? If yes, could you include those? If you put extra effort to your question then the answers will come quickly - and with extra value! – Andrew Adam Sep 25 '20 at 21:02
  • Take a look at this https://stackoverflow.com/questions/11556958/sending-data-from-html-form-to-a-python-script-in-flask , and this https://opentechschool.github.io/python-flask/core/form-submission.html – Akib Rhast Sep 25 '20 at 21:27
  • Hello, Andrew Thank you for the feedback I tried to make it as easy to understand as I could now – Harshit soni Sep 26 '20 at 18:41
  • hello, Akib thank you for the example and I have made some changes – Harshit soni Sep 26 '20 at 18:44

1 Answers1

2

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.

oschlueter
  • 2,596
  • 1
  • 23
  • 46