首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >从零搭建一个django项目-2-第一个接口天气预报(下)

从零搭建一个django项目-2-第一个接口天气预报(下)

作者头像
怪盗LYL
发布2022-06-13 13:16:19
发布2022-06-13 13:16:19
6010
举报
文章被收录于专栏:测试开发真货测试开发真货

上一章我们写好了天气类,今天将其合到django接口里。

01

添加url

一个web程序当然要有url入口。django的url设置在

urls.py里。这里设置了两个请求url,分别是api/get_weatherinfo_base和api/get_weatherinfo_all/,后面是一个变量参数以便于获取地市。

代码语言:javascript
复制
from django.contrib import admin
from django.urls import path, re_path
from myapp.views import get_weatherinfo_base, get_weatherinfo_all
urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^api/get_weatherinfo_base/(?P<city>.*)/$',get_weatherinfo_base.as_view(), name="api"),
    re_path(r'^api/get_weatherinfo_all/(?P<city>.*)/$',get_weatherinfo_all.as_view(), name="api"),
]

写好了入口就可以实现写视图类了,视图类写在myapp下面的views.py文件里。

我们先写个模拟返回将输入的地市返回看看有没有问题。

代码语言:javascript
复制
from rest_framework.response import Response
from rest_framework.views import APIView
class get_weatherinfo_base(APIView):
    # authentication_classes = [JwtAuthorizationAuthentication, ]
    def get(self, request, *args, **kwargs):
        city = self.kwargs['city']
        return Response({"datas":city})
class get_weatherinfo_all(APIView):
    # authentication_classes = [JwtAuthorizationAuthentication, ]
    def get(self, request, *args, **kwargs):
        city = self.kwargs['city']
        return Response({"city":city})

运行以后输入地址:

代码语言:javascript
复制
http://127.0.0.1:8000/api/get_weatherinfo_base/北京/

可以看到成功返回了,说明从入口到视图类到返回是通的,接下来就可以实现视图类具体获取天气。

02

添加实现视图类

代码语言:javascript
复制
from rest_framework.response import Response
from rest_framework.views import APIView
from myapp.utils.weatherInfo_utils import Gaode_tianqi
class get_weatherinfo_base(APIView):
    # authentication_classes = [JwtAuthorizationAuthentication, ]
    def get(self, request, *args, **kwargs):
        city = self.kwargs['city']
        tianqi = Gaode_tianqi(city).get_weatherinfo_base()
        return Response({"datas":tianqi})
class get_weatherinfo_all(APIView):
    # authentication_classes = [JwtAuthorizationAuthentication, ]
    def get(self, request, *args, **kwargs):
        city = self.kwargs['city']
        tianqi = Gaode_tianqi(city).get_weatherinfo_all()
        return Response({"datas":tianqi})

两个视图类分别调用了天气类的两个方法,重新运行看看。

成功返回了。天气获取接口结束,下一章讲解怎么将数据储存到数据库中,我使用的数据库是mysql,因为我之前的项目已经搭好了我就不讲解怎么搭数据库了搜索引擎都有。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-05-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 测试开发真货 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • urls.py里。这里设置了两个请求url,分别是api/get_weatherinfo_base和api/get_weatherinfo_all/,后面是一个变量参数以便于获取地市。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档