In this tutorial, we will learn how to create a weather application using Django as the backend.Django provides a web framework based on the Python web framework that allows for rapid development and a clean, pragmatic design.
Basic settings
Change Catalog to Weather
cd weather
Start the server
python runserver
To check if the server is running, go to your web browser and type in the URL. you can now stop the server by pressing the following commandhttp://127.0.0.1:8000/
ctrl-c
realization
python startapp main
Go to the main/folder by doing:
cd main
and create a folder containing the files:templates/main/
Open the project folder using a text editor. The directory structure should be as shown below:
Now add the main application
Edit the file in Weather:
from import admin from import path, include urlpatterns = [ path('admin/', ), path('', include('')), ]
Edit the file in the master file:
from import path from . import views urlpatterns = [ path('', ), ]
Edit in the `master file :
from import render # Import json to load json data into python dictionary import json # Make a request to the api import def index(request): if == 'POST': city = ['city'] ''' api key may be expired, please use your own api key Replace api_key with appid="your_api_key_here" '''' # Contains JSON data from the API source = ( '/data/2.5/weather?q =' + city + '&appid = your_api_key_here').read() # Convert JSON data to dictionary list_of_data = (source) # data for variable list_of_data data = { "country_code": str(list_of_data['sys']['country']), "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) else: data ={} return render(request, "main/", data)
You can get your own API key from it:Weather API
Navigate and edit it:Link to index.html filetemplates/main/
Perform migration and migrate:
python makemigrations python migrate
Now, let's run the server to see the weather app.
python runserver
This article on Python Django tutorials on the realization of the weather application is introduced to this article, more related Python Django weather application content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future!