基于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工程师面试题 与Python基础语法相关

希望通过本文能够帮助大家顺顺利利通过Python面试,之后还有一篇关于Python Web相关的文章欢迎大家阅读。 1、Python中pass语句的作用是什么? pass语句什么也不做,...

python下载微信公众号相关文章

python下载微信公众号相关文章

本文实例为大家分享了python下载微信公众号相关文章的具体代码,供大家参考,具体内容如下 目的:从零开始学自动化测试公众号中下载“pytest"一系列文档 1、搜索微信号文章关键字搜索...

Python 实现删除某路径下文件及文件夹的实例讲解

Python 实现删除某路径下文件及文件夹的脚本 #!/usr/bin/env python import os import shutil delList = [] delDir...

调试Django时打印SQL语句的日志代码实例

这篇文章主要介绍了调试Django时打印SQL语句的日志代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 设置里面添加如下代码:...

Django 使用Ajax进行前后台交互的示例讲解

本文要实现的功能是:根据下拉列表的选项将数据库中对应的内容显示在页面,选定要排除的选项后,提交剩余的选项到数据库。 为了方便前后台交互,利用了Ajax的GET和POST方法分别进行数据的...