#coding=utf-8
# 2022-3-6
# 基于百度地图API的天气数据查询服务。
# 参考文档：    https://lbsyun.baidu.com/index.php?title=webapi/weather
# 我的开发者密钥：ri6nDXi8KjQrAQp0Ym49ref3NnAGguMb
# GET请求方法： https://api.map.baidu.com/weather/v1/?district_id=<行政区划代码>&data_type=all&ak=<开发者密钥>

import requests
import json
import datetime

my_ak = "ri6nDXi8KjQrAQp0Ym49ref3NnAGguMb"

def get_weather(code):
    url = "https://api.map.baidu.com/weather/v1/?district_id={}&data_type=all&ak={}".format(code,my_ak)
    req = requests.get(url)
    req.encoding = 'utf-8'
    res = req.json()
    #print(json.dumps(res,indent=4,ensure_ascii=False))
    return res

def format_weather(res,header=False):
    loci = res['result']['location']
    prov = loci['province']
    city = loci['city']
    name = loci['name']
    w0   = res['result']['now'] # current weather infos
    wea0 = w0['text']
    tem0 = w0['temp']
    w1   = res['result']['forecasts']
    if(header): #打印表头
        hr = "{0:{1}^34}".format("-","-") # split line
        for i in range(0,foreca_day):
            hr += "{0:{1}^20}".format("-","-")
        print(hr.replace('-','='))

        print("{0:{3}^7}{1:{3}>6}{2:<8}".format("地区","今日","",chr(12288)),end='')
        for i in range(0,foreca_day):
            print("{0:{2}>6}{1:<8}".format("",w1[i]['date'][5:],chr(12288)),end='')
        
        print("")
        print(hr)
    
    print("{0:{3}^7}{1:{3}>6}{2:<8}".format("{},{}".format(prov[0:2],name),wea0," {}".format(tem0),chr(12288)),end='')
    for i in range(0,foreca_day):
        print("{0:{2}>6}{1:<8}".format(w1[i]['text_day']," {}/{}".format(w1[i]['low'],w1[i]['high']),chr(12288)),end='')
    print("")

# print(json.dumps(get_weather(340403),indent=4,ensure_ascii=False)) # for debug.

if __name__=="__main__":    
    print("+-----------------------------------+")
    print("|          Weather Get V6.0         |")
    print("|   modified by zwy at Mar 6,2022   |")
    print("+-----------------------------------+")
    print("Get today's weather from Baidu open API\n")
    print("Current date:",end="")
    print(datetime.datetime.now().strftime("%Y %m %d"))
    foreca_day = 3 #打印的预测天气的天数，取值范围为0~5

    city_list = [
        230100, #哈尔滨
        150100, #呼和浩特
        650100, #乌鲁木齐
        110101, #北京
        120104, #天津
        130100, #石家庄
        610100, #西安
        340400, #淮南
        411500, #信阳
        310101, #上海
        330300, #温州
        420100, #武汉
        422801, #恩施
        430100, #长沙
        500101, #重庆
        440100, #广州
        440800, #湛江
        460100  #海口
    ]
header = True
for city in city_list:
    res = get_weather(city)
    format_weather(res,header)
    if(header):header=False

print("\n")



