SoFunction
Updated on 2024-10-29

python get weather interface to send weather forecast to specified weibo friends

Let's look at the effect first:

Modules used:

  • PyMySQL
  • requests
  • threading
  • wxpy

To realize the above example, there are two major areas to begin with

  • Get weather information
  • Send weather information via WeChat

And getting weather information includes a few small things to keep in mind

Get weather information

  • Interface to get weather information
  • Cities with access to weather information
  • Get the city code of your city

If we send the weather to several people from different cities, we can't always type in the city name, look up the city code, and then access the interface to get the weather, which would be very troublesome, so we need to think about one-to-one correspondence between the city name and the city code. So we can store the information in a dictionary and then persist it to a file, which is much more convenient.

First we get the latest city table, which is a list type with the following general format:

[
 {
  "id": 1,
  "pid": 0,
  "city_code": "101010100",
  "city_name": "Beijing.",
  "post_code": "100000",
  "area_code": "010",
  "ctime": "2019-07-11 17:30:06"
 },
 {
  "id": 2,
  "pid": 0,
  "city_code": "",
  "city_name": "Anhui",
  "post_code": null,
  "area_code": null,
  "ctime": null
 }
]

We'll simply paste and copy it into an empty list, as shown below, and put all the city information into the list citycode

citycode = [
 {
  "id": 1,
  "pid": 0,
  "city_code": "101010100",
  "city_name": "Beijing.",
  "post_code": "100000",
  "area_code": "010",
  "ctime": "2019-07-11 17:30:06"
 },
...
...
...
...
...
...
 {
  "id": 2,
  "pid": 0,
  "city_code": "None",
  "city_name": "Anhui.",
  "post_code": "null",
  "area_code": "null",
  "ctime": "null"
 }
]

cityinfo = {}
#Write city name and city code to json file
with open('city_for_code.json','w',encoding='utf-8') as f:
  for i in citycode:
    name = i["city_name"]
    code = i["city_code"]
    cityinfo[name] = code
  (str(cityinfo))

#Test to see if it can be read
with open('city_for_code.json','r+',encoding='utf-8') as file:
  data_dst = ()
  d = eval(data_dst[0])

Then it's a process, just take out the city_name and city_code fields we need, and write them to the file. If you read it, follow the above method to read, it should be noted that the use of open() method to read the file, the content is a list, we need to through the eval() method into a dict type.

This is the way to put city_name and city_code into a file, or we can put them into a database, as in the case of MySQL, by installing the PyMySQL module.

import pymysql

db_parames = {
  'host': 'localhost',
  'user': 'root',
  'password': '123456',
  'database': 'city_code_info'
}
# Connect to the database
conn = (**db_parames)

# Create a cursor object on which additions, deletions, and modifications are made.
cursor = ()

# table exists, delete it
("DROP TABLE IF EXISTS city_code")

# table building statements
create_table_sql = """CREATE TABLE `city_code` (
 `city_name` varchar(20) DEFAULT NULL,
 `city_code` varchar(25) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
"""
#Build table
(create_table_sql)

#Insert data
with open('city_for_code.json','r+',encoding='utf-8') as f:
  origin_data = ()
  current_data = eval(origin_data[0])  # The read is a list and contains only one element
  #print(current_data.get('Beijing','Not Exists.'))
  for name, code in current_data.items():
    sql = """INSERT INTO city_code(city_name, city_code) VALUES ('%s', '%s')""" % (name, code)
    try:
      (sql)
    except:
      ()
  ()
  ()

Execute this python program to store the city name and city code in the file into the library. Of course, we can also directly get the city name and city code, and then skip the file persistence step, directly take out the two fields and store them in the library, but considering that the code should be practiced more and more often to write, it is redundant a little bit.

Below is the code block that gives you the city code by entering the city name:

import pymysql

def get_city_code(city_name):
  db_parames = {
  'host': 'localhost',
  'user': 'root',
  'password': '123456',
  'database': 'city_code_info'
  }
  # Connect to the database
  conn = (**db_parames)

  # Create a cursor object on which additions, deletions, and modifications are made.
  cursor = ()

  #Creating Query Statements
  select_sql = "SELECT * FROM city_code where city_name='%s'"%(city_name)
  try:
    (select_sql)
    result = ()
    for row in result:
      city_code = row[1]
    return city_code
  except:
    return "Error: unable fetch data!"

Then it's getting the weather based on the city code entered:

import requests

def get_weather(city_name,get_date_time=3):
  city_code = get_city_code(city_name)
  url = '/api/weather/city/%s'%(city_code)
  header = {
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
  }
  response = (url,header)
   = 'utf-8'
  weather = ()
  day = {1: 'Tomorrow', 2: 'The Day After Tomorrow', 3: 'The day after tomorrow'}
  weather_lst = []
  for num in range(get_date_time):
    City = weather["cityInfo"]["city"]
    Weatherganmao = weather["data"]["ganmao"]
    Weatherquality = weather["data"]["quality"]
    Weathershidu = weather["data"]["shidu"]
    Weatherwendu = weather["data"]["wendu"]
    Weatherpm25 = str(weather["data"]["pm25"])
    Weatherpm10 = str(weather["data"]["pm10"])
    Dateymd = weather["data"]["forecast"][num]["ymd"]
    Dateweek = weather["data"]["forecast"][num]["week"]
    Sunrise = weather["data"]["forecast"][num]["sunrise"]
    Sunset = weather["data"]["forecast"][num]["sunset"]
    Windfx = weather["data"]["forecast"][num]["fx"]
    Windf1 = weather["data"]["forecast"][num]["fl"]
    Weathertype = weather["data"]["forecast"][num]["type"]
    Weathernotice = weather["data"]["forecast"][num]["notice"]
    Weatherhigh = weather["data"]["forecast"][num]["high"]
    Weatherlow = weather["data"]["forecast"][num]["low"]
    if num == 0:
      result = 'Today's weather forecast' + '\n' \
        + 'Date: ' + Dateymd + ' ' + Dateweek + ' ' + City + '\n' \
        + 'Weather: ' + Weathertype + ' ' + Windfx + ' ' + Windf1 + ' ' + Weathernotice + '\n' \
        + 'Current temperature: ' + Weatherwendu + '℃' + '\n' \
        + ' Air humidity: ' + Weathershidu + '\n' \
        + ' Temperature range: ' + Weatherlow + '' + '~' + '' + Weatherhigh + '\n' \
        + 'pollution index: ' + 'PM2.5: ' + Weatherpm25 + ' ' + 'PM10: ' + Weatherpm10 + '\n' \
        + 'air quality: ' + Weatherquality + '\n' \
        + 'sunrise time: ' + Sunrise + '\n' \
        + 'time of sunset: ' + Sunset + '\n' \
        + 'hint: ' + Weatherganmao
    else:
      which_day = (num,'Out of range')
      result = '\n' + which_day + ' ' + 'Weather forecast' + '\n' \
        + 'Date: ' + Dateymd + ' ' + Dateweek + ' ' + City + '\n' \
        + 'Weather: ' + Weathertype + ' ' + Windfx + ' ' + Windf1 + ' ' + Weathernotice + '\n' \
        + ' Temperature range: ' + Weatherlow + '' + '~' + '' + Weatherhigh + '\n' \
        + 'sunrise time: ' + Sunrise + '\n' \
        + 'time of sunset: ' + Sunset + '\n' \
        + 'hint: ' + Weatherganmao
    weather_lst.append(result)
    weather_str = ''   # Because the default is to output three days of weather, we need to create an empty string and then splice the weather into the empty string with each iteration.
    for msg in weather_lst:
      weather_str += msg + '\n'

  return weather_str

Here's how to send a WeChat message

from wxpy import *

def send_wx(city_name, who):
  bot = Bot(cache_path=True)
  #bot = Bot(console_qr=2, cache_path='')
  my_friend = ().search(who)[0]
  msg = get_weather(city_name)
  try:
    my_friend.send(msg)
  except:
    my_friend = ().search('fei')[0]
    my_friend.send(u"Failed to send.")

Then we also need to write a timer that sends the

from threading import Timer

def auto_send():
  city_name = 'Set the city to send to'
  friend_list = ['The person to send it to']

  for who in friend_list:
    send_wx(city_name,who)
  global timer
  timer = Timer(1,auto_send)
  ()

Final implementation of the program

if __name__ == '__main__':
  timer = Timer(1,auto_send)
  ()

The above is python get weather interface to the specified WeChat friends to send weather forecast details, more information about python get weather interface please pay attention to my other related articles!