Приложение погоды с использованием Django | Python
В этом руководстве мы узнаем, как создать приложение Weather, использующее Django в качестве бэкэнда. Django предоставляет веб-фреймворк на основе веб-фреймворка Python, который обеспечивает быструю разработку и чистый, прагматичный дизайн.
Базовая настройка -
Сменить каталог на погоду -
cd погода
Запускаем сервер -
сервер запуска python manage.py
To check whether the server is running or not go to a web browser and enter http://127.0.0.1:8000/
as URL. Now, you can stop the server by pressing
ctrl-c
Implementation :
python manage.py startapp main
Перейдите в главную / папку, выполнив:
cd main
and create a folder with index.html
file: templates/main/index.html
Откройте папку проекта с помощью текстового редактора. Структура каталогов должна выглядеть так:
Now add main app in settings.py
Edit urls.py
file in weather :
from django.contrib import admin from django.urls import path, include urlpatterns = [ path( "admin/" , admin.site.urls), path(" ", include(" main.urls")), ] |
edit urls.py
file in main :
from django.urls import path from . import views urlpatterns = [ path("", views.index), ] |
edit views.py in main :
from django.shortcuts import render # import json to load json data to python dictionary import json # urllib.request to make a request to api import urllib.request def index(request): if request.method = = "POST" : city = request.POST[ "city" ] """ api key might be expired use your own api_key place api_key in place of appid ="your_api_key_here " """ # source contain JSON data from API source = urllib.request.urlopen( + city + "&appid = your_api_key_here" ).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" ]), "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/index.html" , data) |
You can get your own API key from : Weather API
Navigate to templates/main/index.html
and edit it: link to index.html file
Make migrations and migrate it:
python manage.py makemigrations python manage.py migrate
now let’s run the server to see your weather app.
python manage.py runserver
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course