如何解决Heroku 时钟进程和 Oauthlib
我的应用程序的上下文是用户通过 requests_oauthlib 库登录到第三方服务,例如 Xero,该库工作正常。
我需要实现的是,在此登录后,每天运行一次的计划作业使用授权的 Oauth2Session 来获取交易等数据。
我无法让时钟进程工作,因为它不断给我错误:
Working outside of request context. This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem.
下面是我的 app.py 文件
from requests_oauthlib import OAuth2Session
@app.route("/login")
def login():
auth= OAuth2Session(client_id,redirect_uri=redirect_uri,scope=scope)
authorization_url,state = auth.authorization_url(authorization_base_url)
return redirect(authorization_url)
@app.route("/callback",methods=["GET"])
def callback():
state = request.args.get('state')
code = request.args.get('code')
scope = request.args.get('scope')
request_url_rebuild = f'{redirect_uri}?code={code}&scope={scope}&state={state}'
auth = OAuth2Session(client_id,state=state) #
token = auth.fetch_token(token_url,code=code,body=f'client_id={client_id}&client_secret={client_secret}&redirect_uri={redirect_uri}')
session['oauth_token'] = token
return redirect(url_for('.profile'))
@app.route("/profile",methods=["GET","POST"])
def profile():
try:
auth= OAuth2Session(client_id,token=session['oauth_token'])
tennant_id = auth.get('https://api.xero.com/connections').json()[0]['tenantId']
response = auth.get("https://api.xero.com/api.xro/2.0/BankTransactions",headers={'xero-tenant-id':tennant_id,'Content-Type':'application/json','Accept': 'application/json'})
transactions = response.json()['BankTransactions']
return {'results':transactions}
和clock.py文件
from apscheduler.schedulers.blocking import BlockingScheduler
from app import app,profile
sched = BlockingScheduler()
@sched.scheduled_job('interval',minutes=2)
def scheduled_task():
try:
with app.app_context():
profile()
except Exception as e:
print(e)
sched.start()
我认为 with app.app_context() 会在时钟过程中设置上下文(请原谅我的术语)。任何帮助将不胜感激。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。