Skip to content

Instantly share code, notes, and snippets.

@ficapy
Created July 31, 2015 04:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ficapy/06d423f6f2e8d930cfed to your computer and use it in GitHub Desktop.
Save ficapy/06d423f6f2e8d930cfed to your computer and use it in GitHub Desktop.
函数参数不应该使用可变变量,只是也不是完全没有作用,比如可以缓存结果啊Orz,把以前写的一个函数改写了下 直观了一些
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Ficapy
# Create: '15/7/31'
# https://docs.python.org/3/faq/programming.html#why-are-default-values-shared-between-objects
import requests
import time
session = requests.Session()
APP_ID = '---------'
APP_SECRET = '-----------'
def get_token():
"""
统一调用生成访问微信API需要的token,对访问结果进行存储,快过期自动重新获取
:return: str
"""
if get_token.result:
get_token.result['expires_in'] -= time.time() - get_token.result.get('last_time')
if get_token.result['expires_in'] > 1000:
get_token.result['last_time'] = time.time()
return get_token.result.get('access_token')
req = session.get(
'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}'
.format(APPID=APP_ID, APPSECRET=APP_SECRET), timeout=3).json()
req = dict(req)
req.update({
'last_time': time.time()
})
get_token.result.update(req)
return get_token.result.get('access_token')
get_token.result = {}
print get_token()
print get_token()
# --------------------------------------------------------------------------
def get_token2(_cache={}):
"""
统一调用生成访问微信API需要的token,对访问结果进行存储,快过期自动重新获取
:return: str
"""
if _cache:
_cache['expires_in'] -= time.time() - _cache.get('last_time')
if _cache['expires_in'] > 1000:
_cache['last_time'] = time.time()
return _cache.get('access_token')
req = session.get(
'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}'
.format(APPID=APP_ID, APPSECRET=APP_SECRET), timeout=3).json()
req = dict(req)
req.update({
'last_time': time.time()
})
_cache.update(req)
return _cache.get('access_token')
print get_token2()
print get_token2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment