def update_jsapi_ticket(): try: wx_access_token = WxAccessToken.get(WxAccessToken.appid == WX_APP_ID) except DoesNotExist: raise Exception('Need to get access token before request for jsapi ticket') jsapi_ticket_url = create_jsapi_ticket_url(wx_access_token.token) ret_text = urlopen(jsapi_ticket_url).read().strip().decode('utf8', 'ignore') ret_data = json.loads(ret_text) if u'ticket' not in ret_data: raise Exception('Error occurs when trying to get jsapi ticket') ticket, expire = ret_data[u'ticket'], ret_data[u'expires_in'] wx_jsapi_ticket, _ = WxJsapiTicket.get_or_create(appid=WX_APP_ID) wx_jsapi_ticket.ticket = ticket wx_jsapi_ticket.expires_in = expire if not wx_jsapi_ticket.save(): raise Exception('Error occurs when saving jsapi ticket to database') print('Get jsapi ticket %s which will expire in %s seconds' % (ticket, expire)) return ticket, int(expire)
ticket, expire = ret_data[u'ticket'], ret_data[u'expires_in'] wx_jsapi_ticket, _ = WxJsapiTicket.get_or_create(appid=WX_APP_ID) wx_jsapi_ticket.ticket = ticket wx_jsapi_ticket.expires_in = expire if not wx_jsapi_ticket.save(): raise Exception('Error occurs when saving jsapi ticket to database') print('Get jsapi ticket %s which will expire in %s seconds' % (ticket, expire)) return ticket, int(expire) if __name__ == '__main__': # 确保数据表已经创建 WxAccessToken.create_table(fail_silently=True) WxJsapiTicket.create_table(fail_silently=True) # 设置定时器 scheduler = BlockingScheduler() # 第一次运行,根据返回值设置任务间隔 access_token, expires_in = update_access_token() scheduler.add_job(update_access_token, 'interval', seconds=(expires_in // 2)) ticket, expires_in = update_jsapi_ticket() scheduler.add_job(update_jsapi_ticket, 'interval', seconds=(expires_in // 2)) logger = logging.getLogger('apscheduler.executors.default') logger.setLevel(logging.DEBUG) steam_handler = logging.StreamHandler() logger.addHandler(steam_handler)