Home >  > 天气网站

天气网站

0

一、申请API
https://home.openweathermap.org/api_keys

二、建立环境

pip install virtualenv
virtualenv weathervenv
cd weathervenv/Scripts/
activate
cd..
cd..

三、建立django项目

1. 安装指定版本django

pip install django==2.0

2.建立django APP
进入到项目文件夹,执行

django-admin startproject the_wedather

再进入这个the_wedather文件夹。

python manage.py startapp weather

然后在settings.py下面,新增这个app.

2.建立superuser

python manage.py migrate
python manage.py createsuperuser
python manage.py runserver

然后runserver看一下是否能看到首页。

四、模板文件
1.在weather文件夹下面建立一个templates文件夹。
2.在templates文件夹下面建立一个weather文件夹,和app的名称一样。
3.将weather.html文件复制到这个文件夹。
weather

4. 修改url.py

from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('weather.urls')),
]

小提示:
这里原教程也有问题,weather.urls不加引号的话,会出现“NameError: name 'weather' is not defined”的出错提示。

5.在weather文件夹下面,建立一个urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('',views.index),
]

6.修改weather文件夹下面的views.py

def index(request):
    return render(request,'weather/weather.html')

最后的文件夹结构是这样的:

成果展示:

五、从API取数
1.测试API
修改views.py

import requests
from django.shortcuts import render

# Create your views here.
def index(request):
    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=这里填你的API key'
    city = 'New york'
    r = requests.get(url.format(city))
    print(r.text)
    return render(request,'weather/weather.html')

然后可以从终端看到取到的数。

2.取数

    r = requests.get(url.format(city)).json()
    
    city_weather = {
        'city':city,
        'temperature':r['main']['temp'],
        'description':r['weather'][0]['description'],
        'icon':r['weather'][0]['icon'],

    }
    print(city_weather)

然后可以在终端看到已经取到了数:

3.将数据传到模板

    content = {'city_weather':city_weather}
    return render(request,'weather/weather.html',content)

4.修改模板

<div class="box">
    <article class="media">
        <div class="media-left">
            <figure class="image is-50x50">
                <img src="http://openweathermap.org/img/w/{{ city_weather.icon }}.png" alt="Image">
            </figure>
        </div>
        <div class="media-content">
            <div class="content">
                <p>
                    <span class="title">{{ city_weather.city }}</span>
                    <br>
                    <span class="subtitle">{{ city_weather.temperature }}° F</span>
                    <br> {{ city_weather.description }}
                </p>
            </div>
        </div>
    </article>
</div>

成果展示:

六、添加多城市功能

1.修改models.py
添加以下代码:

class city(models.Model):
    name = models.CharField(max_length = 25)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'cities'

2.执行以下命令

python manage.py makemigrations
python manage.py migrate

3.修改admin.py,在后台注册citys

from django.contrib import admin
from .models import city

admin.site.register(city)

然后进入后台就可以看到citys了。

4.添加几个城市

5.修改views.py

import requests
from django.shortcuts import render
from .models import City

# Create your views here.
def index(request):
    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=你的API'
    cities = City.objects.all()

    weather_data = []

    for city in cities:
        r = requests.get(url.format(city)).json()

        city_weather = {
            'city':city.name,
            'temperature':r['main']['temp'],
            'description':r['weather'][0]['description'],
            'icon':r['weather'][0]['icon'],

        }
        weather_data.append(city_weather)
    content = {'weather_data':weather_data}
    return render(request,'weather/weather.html',content)

6.在模板文件中加以下代码:

{% for city_weather in weather_data %}

{% endfor %}

成果展示:

七、添加“add city”功能
1.建立文件
在weather文件夹下面建立一个forms.py文件。

from django.forms  import ModelForm,TextInput
from .models import City

class Cityform(ModelForm):
    class Meta:
        model = City
        fields = ['name']

2.修改views.py

from .forms import Cityform
    if request.method =='POST':
        pass

    form = Cityform()
content = {'weather_data':weather_data,'form':form}
widgets = {'name':TextInput(attrs={'class':'input','placeholder':'City Name'})}

3.修改模板文件:

    </section>
    <section class="section">
        <div class="container">
            <div class="columns">
                <div class="column is-offset-4 is-4">
                    <form method="POST">
                        {% csrf_token %}
                        <div class="field has-addons">
                            <div class="control is-expanded">
                                {{ form.name }}
                            </div>
                            <div class="control">
                                <button type="submit" class="button is-info">
                                    Add City
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>

4.修改views.py,保存添加的城市。
最终的views.py代码如下:

import requests
from django.shortcuts import render
from .models import City
from .forms import Cityform

# Create your views here.
def index(request):
    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=你的API'
    cities = City.objects.all()

    if request.method =='POST':
        form = Cityform(request.POST)
        form.save()

    form = Cityform()

    weather_data = []

    for city in cities:
        r = requests.get(url.format(city)).json()

        city_weather = {
            'city':city.name,
            'temperature':r['main']['temp'],
            'description':r['weather'][0]['description'],
            'icon':r['weather'][0]['icon'],

        }
        weather_data.append(city_weather)
    content = {'weather_data':weather_data,'form':form}
    return render(request,'weather/weather.html',content)

这时就可以通过“add city”按钮添加城市了。

https://www.youtube.com/watch?v=qCQGV7F7CUc

本文暂无标签

发表评论

*

*