Saturday, July 11, 2020

Weather app using api in flask python

Weather App




server.py



#need to know flask as prerequisites
#importing flask
from flask import Flask, render_template, request 

# import json to load JSON data to a python dictionary 
import json 

# urllib.request to make a request to api 
import urllib.request 


app = Flask(__name__

@app.route('/'methods =['POST''GET']) 
def weather(): 
    if request.method == 'POST'
        city = request.form['city'
    else 
        city = 'bengaluru'

    # your API key will come here 
    api = 'your_api_key'


    # source contain json data from api 
    source = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+city+'&appid='+api).read() 

    # converting JSON data to a dictionary 
    list_of_data = json.loads(source) 

    # data for variable list_of_data 
    data = { 
        "country_code"str(list_of_data['sys']['country']), 
        "cityname":str(list_of_data['name']),
        "coordinate"str(list_of_data['coord']['lon']) + ' '
                    + str(list_of_data['coord']['lat']), 
        "temp"str(list_of_data['main']['temp']) + 'k'
        "pressure"str(list_of_data['main']['pressure']), 
        "humidity"str(list_of_data['main']['humidity']), 
    } 
    print(data) 
    return render_template('main.html'data = data) 



if __name__ == '__main__'
    app.run(debug = True

main.html


<html>
<head>
  <title>weather</title>
</head>

<body>
    <h1><center>weather</center></h1>
  <br />
  <br />
  <center class="row">
    <form method="post" class="col-md-6 col-md-offset-3">
      <div class="input-group">
        <input type="text" class="form-control" name="city" placeholder="Search" default="bengaluru">
        <div class="input-group-btn">
          <button class="btn btn-primary" type="submit">
            <i class="glyphicon glyphicon-search"></i>
          </button>
        </div>
        <form>
  </center>
  <div class="row">
    {% if data.country_code and data.coordinate and data.temp and data.pressure and data.humidity %}
    <div class="col-md-6 col-md-offset-3">
      <h3>country code : {{data.country_code}}</h1>
        <h5>City name : {{data.cityname}}</h5>
        <h5>coordinate : {{data.coordinate}}</h5>
        <h5>temp (in kelvin) : {{data.temp}}</h5>
        <h5>pressure : {{data.pressure}} </h5>
        <h5>humidity : {{data.humidity}}</h5>
    </div>
    {% endif %}
  </div>
</body>
</html>


Follow my github account : Sharath Hebbar

follow my blog : Delta

No comments:

Post a Comment