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

yipeiwu_com5年前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设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

python中argparse模块用法实例详解

本文实例讲述了python中argparse模块用法。分享给大家供大家参考。具体分析如下: 平常在写命令行工具的时候,经常会带参数,所以用python中的argparse来实现。 #...

全面了解python字符串和字典

很多序列的方法字符串同样适用, 但是,字符串是不可变的,所以一些试图改变字符串的方法是不可用的 1 字符串格式化 1)用元组或者字典格式化字符串 format = "hello,%s.s...

Python输出由1,2,3,4组成的互不相同且无重复的三位数

题目:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少? 程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去 掉不满足条件的排...

CentOS下使用yum安装python-pip失败的完美解决方法

以前用Ubuntu的时候感觉很简单的事到ContOS上却变得很头痛,在执行以下命令安装python-pip居然什么也没执行。 yum install python-pip 后来go...

PyQt5利用QPainter绘制各种图形的实例

PyQt5利用QPainter绘制各种图形的实例

这个例子我做了好几天: 1)官网C++的源码,改写成PyQt5版本的代码,好多细节不会转化 2)网上的PyQt的例子根本运行不了 填了无数个坑,结合二者,终于能完成了一个关于绘图的东西。...