【发布时间】:2016-02-26 04:14:43
【问题描述】:
我正在使用imgur api。我正在使用没有数据库的 Flask。
我正在尝试访问一个专用帐户,因此此应用中不会有多个用户帐户(因此我只需手动授权一次,然后使用 tokens the service gives to me 完成其余操作,无需对于数据库)。 一旦在帐户上授权了应用程序,Imgur 就会给我两个令牌:一个小时后过期的 access_token 和一个不会过期且可用于请求新 access_token 的 refresh_token。
我想不出有什么不同的方法可以使用这两个令牌向服务器发送正确的请求并仅在需要时刷新访问权限:
from flask import Flask
from foobar import foo, bar
import config
app = Flask(__name__)
app.config.from_object(config)
#I initialize the access_token with the value hardcoded in the config file
access_token = config.access_token
@app.route('/',methods=['POST'])
def home():
#I access the value i initialized when starting the server
global access_token
if request.method == 'POST':
#I send the access_token to a method that contacts Imgur servers and checks if it's still valid. If not it will request and return a new one.
access_token = foo(access_token)
#I send the token, now sure it's always a valid one, to the rest of the logic that uses it to do actual requests
bar(access_token)
这行得通。只要我不重新启动服务器,它只会在需要时才需要一个新的 access_token,但它看起来并不是一个很好的做事方式。硬编码一个小时后过期的令牌的想法听起来真的很愚蠢,我真的不知道使用该全局变量是否有一个好的做法,也不知道在我目前忽略的某些情况下它是否会从配置文件重新初始化.我怎样才能避免这种情况?我应该将新刷新的 access_token 写入文件并从那里加载到配置中?这会产生安全问题吗?
另外,refresh_token 不会过期,所以我认为将它存储在 cofing 文件中没有问题,但是每次我请求 access_token 时,它也会给我一个新的 refresh_token,我是否也应该更新它?似乎没有必要,旧的仍然有效,但也许我错过了一些东西。
【问题讨论】:
标签: python api flask oauth-2.0 access-token