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 (将#修改为@)