基于python 微信小程序之获取已存在模板消息列表

yipeiwu_com6年前Python基础

前言:

为了获取一定高级操作,如:微信模板消息(xiao,xin)推送,把消息推送给用户,或者是获取用户授权信息都需要用到access token,有效期为两个小时?

过了两个小时怎么办?重新获取,来,代码撸起走,啥女朋友没有?

获取小程序对应的access token

def get_wx_token():
  url = "https://api.weixin.qq.com/cgi-bin/token?"
  try:
    respone = requests.get(url, params=payload, timeout=50)
    access_token = respone.json().get("access_token")
    res = respone.json()
    res["time"] = stamp
    print(u'token过期,重新写入文件的内容>>>', res)
    with open(token_file, "w+") as f:
      f.write(json.dumps(res))
    return access_token
  except Exception as e:
    msg = traceback.format_exc()
    print('get token error', msg)
    return

并判断是否过期

def get_access_token():

try:
  with open(token_file, "r") as f:
    content = f.read()
    data_dict = content
    # 如果缓存内容为空,直接重新获取token
    if (content == ''):
      print("token文件为空,重新获取并写入文件")
      result = get_wx_token()
      return result
    else:
      data_dict = re.sub('\'', '\"', data_dict)
      token_time = int(json.loads(data_dict)['time'])
      if (stamp - token_time) > 7100:
        # print("token过期,重新获取并写入文件")
        get_wx_token()
      else:
        return json.loads(data_dict)['access_token']
except Exception as e:
  msg = traceback.format_exc()
  print("access token express time", msg)

根据access token 获取模板列表

def get_templates_list(access_token):
  url = "https://api.weixin.qq.com/cgi-bin/wxopen/template/list?access_token={}".format(access_token)
  data = {
   "offset": 0,
   "count": 20
  }
  r = requests.post(url,data=json.dumps(data)).json()
  tpl_list = r.get('list')
  for tpl in tpl_list:
    print(tpl)
  # print(r.get('list'))

返回数据示例

{
 "errcode": 0,
 "errmsg": "ok",
 "list": [
  {
   "template_id": "wDYzYZVxobJivW9oMpSCpuvACOfJXQIoKUm0PY397Tc",
   "title": "购买成功通知",
   "content": "购买地点{{keyword1.DATA}}\n购买时间{{keyword2.DATA}}\n物品名称{{keyword3.DATA}}\n",
   "example": "购买地点:TIT造舰厂\n购买时间:2016年6月6日\n物品名称:咖啡\n"
  }
 ]
}

总结

以上所述是小编给大家介绍的基于python 微信小程序之获取已存在模板消息列表,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

利用Anaconda完美解决Python 2与python 3的共存问题

前言 现在Python3 被越来越多的开发者所接受,同时让人尴尬的是很多遗留的老系统依旧运行在 Python2 的环境中,因此有时你不得不同时在两个版本中进行开发,调试。 如何在系统中同...

Python实现查找系统盘中需要找的字符

本文实例讲述了Python实现查找系统盘中需要找的字符。分享给大家供大家参考。具体如下: ''' Created on 2011-7-13 @author: 123 ''' impo...

python可视化实现代码

python可视化实现代码

python可视化 #导入两个库 import numpy as np import matplotlib.pyplot as plt #第一个参数就是x轴的初始值 #第二个参数是...

详解Django+uwsgi+Nginx上线最佳实战

什么是uwsgi? uWSGI是一个Web服务器,它实现了WSGI协议、uwsgi、http等协议。Nginx中HttpUwsgiModule的作用是与uWSGI服务器进行交换。WSG...

python list数据等间隔抽取并新建list存储的例子

原始数据如下: ['e3cd', 'e547', 'e63d', '0ffd', 'e39b', 'e539', 'e5be', '0dd2', 'e3d6', 'e52e', 'e...