阿里云的云市场提供大量的免费接口,并且可以使用多种语言调用接口,如:python,java,php等。

使用接口前,需要购买接口,然后就可以使用阿里云提供的AppCode去请求对应的接口。
一、python简单实现接口
下面开始使用python调用天气预告接口,查询想要的城市的近十几天的天气情况:
-
使用的包
import json import requests -
使用接口
调用接口需要重要的三个参数,其中AppCode最重要,在点击购买接口后会得到属于你自己的AppCode。- 接口url
- 接口使用到的参数
- AppCode
url = 'http://saweather.market.alicloudapi.com/day15' Header = { # "Authorization":"APPCODE 自己的AppCode", "Authorization": "APPCODE 7b9862e5b4bc4906a1d6f87e0f417ebd", "Type":"application/json; charset=utf-8", } payload = { 'area': "深圳" } response = requests.get(url, params=payload, headers=Header) print(response)执行上面代码后,就是完成接口的调用。需要注意打印的
response的结果,通过此结果可以知道访问是否成功。若返回的结果位<Response [200]>,则接口调用成功,否则失败。失败原因可能是:
- 1、需要的包文件没有导入;
- 2、传入的参数
area拼写错误; - 3、没有购买接口,使用的AppCode出错。
-
获取到的数据:(可复制到纯文本文件查看完整的数据)
{ "showapi_res_error": "", "showapi_res_id": "e3b0d76a3ecf426f9a11e65b9c9d941c", "showapi_res_code": 0, "showapi_res_body": { "ret_code": 0, "area": "深圳", "showapi_fee_code": -1, "areaid": "101280601", "dayList": [ { "night_weather_code": "00", "day_weather": "多云", "night_weather": "晴", "night_wind_power": "0-3级", "areaid": "101280601", "day_wind_power": "3-4级", "day_weather_code": "01", "daytime": "20190911", "area": "深圳", "day_weather_pic": "http://app1.showapi.com/weather/icon/day/01.png", "night_air_temperature": "28", "day_air_temperature": "33", "day_wind_direction": "西南风", "night_wind_direction": "无持续风向", "night_weather_pic": "http://app1.showapi.com/weather/icon/night/00.png" }, { "night_weather_code": "04", "day_weather": "晴", "night_weather": "雷阵雨", "night_wind_power": "0-3级", "areaid": "101280601", "day_wind_power": "0-3级", "day_weather_code": "00", "daytime": "20190912", "area": "深圳", "day_weather_pic": "http://app1.showapi.com/weather/icon/day/00.png", "night_air_temperature": "28", "day_air_temperature": "34", "day_wind_direction": "无持续风向", "night_wind_direction": "无持续风向", "night_weather_pic": "http://app1.showapi.com/weather/icon/night/04.png" }, { "night_weather_code": "04", "day_weather": "雷阵雨", "night_weather": "雷阵雨", "night_wind_power": "0-3级", "areaid": "101280601", "day_wind_power": "0-3级", "day_weather_code": "04", "daytime": "20190913", "area": "深圳", "day_weather_pic": "http://app1.showapi.com/weather/icon/day/04.png", "night_air_temperature": "28", "day_air_temperature": "35", "day_wind_direction": "无持续风向", "night_wind_direction": "无持续风向", "night_weather_pic": "http://app1.showapi.com/weather/icon/night/04.png" }, { "night_weather_code": "04", "day_weather": "雷阵雨", "night_weather": "雷阵雨", "night_wind_power": "0-3级", "areaid": "101280601", "day_wind_power": "0-3级", "day_weather_code": "04", "daytime": "20190914", "area": "深圳", "day_weather_pic": "http://app1.showapi.com/weather/icon/day/04.png", "night_air_temperature": "27", "day_air_temperature": "34", "day_wind_direction": "无持续风向", "night_wind_direction": "无持续风向", "night_weather_pic": "http://app1.showapi.com/weather/icon/night/04.png" }, { "night_weather_code": "03", "day_weather": "雷阵雨", "night_weather": "阵雨", "night_wind_power": "0-3级", "areaid": "101280601", "day_wind_power": "0-3级", "day_weather_code": "04", "daytime": "20190915", "area": "深圳", "day_weather_pic": "http://app1.showapi.com/weather/icon/day/04.png", "night_air_temperature": "27", "day_air_temperature": "33", "day_wind_direction": "无持续风向", "night_wind_direction": "无持续风向", "night_weather_pic": "http://app1.showapi.com/weather/icon/night/03.png" }, { "night_weather_code": "03", "day_weather": "阵雨", "night_weather": "阵雨", "night_wind_power": "0-3级", "areaid": "101280601", "day_wind_power": "0-3级", "day_weather_code": "03", "daytime": "20190916", "area": "深圳", "day_weather_pic": "http://app1.showapi.com/weather/icon/day/03.png", "night_air_temperature": "27", "day_air_temperature": "33", "day_wind_direction": "无持续风向", "night_wind_direction": "无持续风向", "night_weather_pic": "http://app1.showapi.com/weather/icon/night/03.png" }, { "night_weather_code": "03", "day_weather": "阵雨", "night_weather": "阵雨", "night_wind_power": "0-3级", "areaid": "101280601", "day_wind_power": "0-3级", "day_weather_code": "03", "daytime": "20190917", "area": "深圳", "day_weather_pic": "http://app1.showapi.com/weather/icon/day/03.png", "night_air_temperature": "27", "day_air_temperature": "32", "day_wind_direction": "无持续风向", "night_wind_direction": "无持续风向", "night_weather_pic": "http://app1.showapi.com/weather/icon/night/03.png" }, { "night_weather_code": "301", "day_weather": "阵雨", "night_weather": "雨", "night_wind_power": "0-3级", "areaid": "101280601", "day_wind_power": "0-3级", "day_weather_code": "03", "daytime": "20190918", "area": "深圳", "day_weather_pic": "http://app1.showapi.com/weather/icon/day/03.png", "night_air_temperature": "26", "day_air_temperature": "33", "day_wind_direction": "无持续风向", "night_wind_direction": "西风", "night_weather_pic": "http://app1.showapi.com/weather/icon/night/301.png" }, { "night_weather_code": "02", "day_weather": "雨", "night_weather": "阴", "night_wind_power": "0-3级", "areaid": "101280601", "day_wind_power": "0-3级", "day_weather_code": "301", "daytime": "20190919", "area": "深圳", "day_weather_pic": "http://app1.showapi.com/weather/icon/day/301.png", "night_air_temperature": "25", "day_air_temperature": "31", "day_wind_direction": "东南风", "night_wind_direction": "北风", "night_weather_pic": "http://app1.showapi.com/weather/icon/night/02.png" }, { "night_weather_code": "02", "day_weather": "阴", "night_weather": "阴", "night_wind_power": "0-3级", "areaid": "101280601", "day_wind_power": "0-3级", "day_weather_code": "02", "daytime": "20190920", "area": "深圳", "day_weather_pic": "http://app1.showapi.com/weather/icon/day/02.png", "night_air_temperature": "24", "day_air_temperature": "31", "day_wind_direction": "北风", "night_wind_direction": "西北风", "night_weather_pic": "http://app1.showapi.com/weather/icon/night/02.png" }, { "night_weather_code": "01", "day_weather": "雨", "night_weather": "多云", "night_wind_power": "0-3级", "areaid": "101280601", "day_wind_power": "0-3级", "day_weather_code": "301", "daytime": "20190921", "area": "深圳", "day_weather_pic": "http://app1.showapi.com/weather/icon/day/301.png", "night_air_temperature": "26", "day_air_temperature": "29", "day_wind_direction": "北风", "night_wind_direction": "北风", "night_weather_pic": "http://app1.showapi.com/weather/icon/night/01.png" }, { "night_weather_code": "301", "day_weather": "多云", "night_weather": "雨", "night_wind_power": "0-3级", "areaid": "101280601", "day_wind_power": "0-3级", "day_weather_code": "01", "daytime": "20190922", "area": "深圳", "day_weather_pic": "http://app1.showapi.com/weather/icon/day/01.png", "night_air_temperature": "26", "day_air_temperature": "29", "day_wind_direction": "北风", "night_wind_direction": "北风", "night_weather_pic": "http://app1.showapi.com/weather/icon/night/301.png" }, { "night_weather_code": "01", "day_weather": "雨", "night_weather": "多云", "night_wind_power": "0-3级", "areaid": "101280601", "day_wind_power": "0-3级", "day_weather_code": "301", "daytime": "20190923", "area": "深圳", "day_weather_pic": "http://app1.showapi.com/weather/icon/day/301.png", "night_air_temperature": "24", "day_air_temperature": "29", "day_wind_direction": "北风", "night_wind_direction": "北风", "night_weather_pic": "http://app1.showapi.com/weather/icon/night/01.png" }, { "night_weather_code": "301", "day_weather": "雨", "night_weather": "雨", "night_wind_power": "0-3级", "areaid": "101280601", "day_wind_power": "0-3级", "day_weather_code": "301", "daytime": "20190924", "area": "深圳", "day_weather_pic": "http://app1.showapi.com/weather/icon/day/301.png", "night_air_temperature": "24", "day_air_temperature": "25", "day_wind_direction": "北风", "night_wind_direction": "北风", "night_weather_pic": "http://app1.showapi.com/weather/icon/night/301.png" }, { "night_weather_code": "301", "day_weather": "雨", "night_weather": "雨", "night_wind_power": "0-3级", "areaid": "101280601", "day_wind_power": "0-3级", "day_weather_code": "301", "daytime": "20190925", "area": "深圳", "day_weather_pic": "http://app1.showapi.com/weather/icon/day/301.png", "night_air_temperature": "24", "day_air_temperature": "26", "day_wind_direction": "北风", "night_wind_direction": "北风", "night_weather_pic": "http://app1.showapi.com/weather/icon/night/301.png" } ] } }
通过上面的步骤,已经能实现简单的接口访问,若想要任意输入城市进行查询,并且获得查询到的所有结果,还需要进一步完善代码。
二、渲染查询结果
- 说明:以下代码通过tornado框架实现,在不同的请求方式,以及访问指定的路由地址的时候,可以执行对应的类视图的功能。
- 需要使用的包
import tornado - 创建一个tornado项目(MyTornadoPro)
# 项目的文件结构 MyTornadoPro ├─App │ └─__init__.py │ └─ settings.py │ └─ urls.py │ └─ views.py ├─templates │ └─ weather.html └─manage.py __init__.pyimport tornado.web from App.urls import patterns from App.settings import app_settings # 创建应用,并设置了路由规则 def make_app(): return tornado.web.Application( handlers=patterns, **app_settings, )settings.pyimport tornado.web from App.urls import patterns from App.settings import app_settings # 创建应用,并设置了路由规则 import os from tornado.options import define, options BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) define('port', default=8080, type=int) define('debug', default=True, type=bool) app_settings = { "debug": options.debug, "template_path": os.path.join(BASE_DIR, 'templates'), "static_path": os.path.join(BASE_DIR, 'static'), } ```urls.py# urls.py: 存放路由配置 from tornado.web import url from App.views import * patterns = [ url(r'/weather/', WeatherIndex), url(r'/weatherinfo/', WeatherHandler, name="wea"), ]views.pyclass WeatherIndex(tornado.web.RequestHandler): def get(self): self.render("weather.html") class WeatherHandler(tornado.web.RequestHandler): def get(self): url = 'http://saweather.market.alicloudapi.com/day15' Header = { "Authorization": "APPCODE 7b9862e5b4bc4906a1d6f87e0f417ebd", "Type": "application/json; charset=utf-8", } city = self.get_argument("city") payload = {'area': '{}'.format(city)} response = requests.get(url, params=payload, headers=Header) cityinfo_dict = json.loads(response.content)['showapi_res_body'] self.write(json.dumps(cityinfo_dict))- 渲染的前端页面:存放在
tempalte文件夹中<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>天气查询</title> <script type="text/javascript" src="https://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script> <style> * { margin: 0; padding: 0; font-size: 14px; } h1 { font-size: 38px; margin-bottom: 10px; margin-top: 4px; } #all { text-align: center; width: 100%; background-color: white; /*height: 800px;*/ /*border: 1px solid black;*/ } li { list-style: none; height: 40px; } .city_title { font-size: 35px; line-height: 40px; margin-right: 50px; } #weatherList { margin: 0 auto; width: 500px; height: 260px; border: 1px solid gray; border-radius: 4px; mso-border-shadow: yes; } input { width: 300px; height: 28px; } button { width: 60px; height: 32px; } .point { position: relative; width: 40px; height: 40px; border-radius: 5px; border: 1px solid gainsboro; font-size: 30px; top: 60px; display: none; } .point label { font-size: 30px; margin: -6px -4px 0px 0px; } .point_left { float: left; } .point_right { float: right; } </style> </head> <body> <div id="all"> <h1>天气查询</h1> <input type="text" name="city" placeholder="请输入查询城市名称"> <button>确定</button> <br> <br> <div id="weatherList" style="z-index: 2"> <br> <br> <div class="point point_right" onclick="rightpoint()"> <label>></label> </div> <div class="point point_left" onclick="leftpoint()"> <label><</label> </div> <p></p> <br> <ul id="day"> </ul> <ul id="night"> </ul> </div> </div> <script> //查询城市的近十天天气信息 var days = []; var day_num = 0; //点击提交后,使用ajax与后台数据交互,succss参数是后天返回的结果 $("button").click(function () { //对输入的内容进行判断 let city_content = document.getElementsByName("city")[0].value; var re = "^[/u4e00-/u9fa5]+$"; //只允许输入中文 if (city_content === "") { alert("请填写查询城市!") } else if (re.match(city_content)) { alert("城市名字有误!") } else { //使用ajax提交数据到后台,并接收返回的数据 $.ajax( { type: "get", dataType: "json", url: "/weatherinfo/", data: {"city": $("input")[0].value}, //提交到后台的数据 success: function (data) { //data是后台返回数据 if (data['ret_code'] == -1) { //查找不到时执行 alert("城市查看不到!") } else { days = data['dayList']; change(day_num); document.getElementsByName("city")[0].value = ""; // console.log(data); } } } ); } } ); //切换日期的天气 function change(num) { //白天 var day_air = days[num]['day_air_temperature']; //气温 var day_weather = days[num]['day_weather']; //天气 var day_wind_power = days[num]['day_wind_power']; //风力 var day_wind_direction = days[num]['day_wind_direction']; //风向 //夜晚 var night_air = days[num]['night_air_temperature']; //气温 var night_weather = days[num]['night_weather']; //天气 var night_wind_power = days[num]['night_wind_power']; //风力 var night_wind_direction = days[num]['night_wind_direction']; //风向 //创建对象 let day = $("#day"); let label = $("label"); let night = $("#night"); let p = $("p"); let list = $("#weatherList"); //清空节点内容 p.empty(); day.empty(); night.empty(); //添加节点时,需要先清楚指定节点中的内容 //添加内容 var date = days[num]['daytime']; var date_text = " " + date.slice(0, 4) + " 年 " + parseInt(date.slice(4, 6)) + " 月<label style='color: red'> " + parseInt(date.slice(6, 8)) + " </label>日"; var text = night_air + "~" + day_air; var text_line2 = "<li><b>白天:</b> " + day_weather + " 风向: " + day_wind_direction + " 风力等级: " + day_wind_power + "</li>"; var text_line3 = "<li><b>夜晚:</b> " + night_weather + " 风向: " + night_wind_direction + " 风力等级: " + night_wind_power + "</li>"; //添加节点 p.append("<label class='city_title'>" + days[num]['area'] + "</label>"); p.append("<label>日期: " + date_text + "</label>"); day.append("<li>气温: " + text + "℃" + " 温差: " + (day_air - night_air) + "℃</li>"); day.append(text_line2); day.append(text_line3); } //右侧按钮的点击事件 function leftpoint() { if ($("li").length > 0) { if (day_num == 0) { alert("已经是最新天气信息!") } else { console.log(day_num); day_num -= 1; change(day_num) } } }; //左侧按钮的点击事件 function rightpoint() { if ($("li").length > 0) { if (day_num + 1 == days.length) { alert("暂无可查询天气信息!") } else { console.log(day_num); day_num += 1; change(day_num) } } }; //按钮的效果,是否显示按钮 $("#weatherList").hover(function () { if ($('li').length > 0) { $(".point").show("normal"); } }, function () { if ($('li').length > 0) { $(".point").hide("normal"); } }); </script> </body> </html>
按照上面的项目结构创建文件后,便完成实现接口后处理数据的后台代码,在Pycharm中打开控制台,输入python manage.py执行tornado框架。在后台获取到响应数据后,通过ajax传到前端显示数据。
三、浏览器访问
- 打开浏览器访问
http://localhost:8080/weather/,便可以看到weather.html的页面内容。

weather.html实现一些jquery的方法,主要是为了使页面更加好看一些。- 若访问失败,可能是tornado服务的端口被占用,打开服务失败。处理方法:在启动命令后面加上
--port=端口号重新启动tornado服务。
本文介绍如何使用Python调用阿里云的天气预报接口,包括获取AppCode、构造请求及解析响应数据。同时,通过Tornado框架实现了动态查询城市天气并渲染结果。

3024

被折叠的 条评论
为什么被折叠?



