2

I implemented API in Flask and working correctly. (Get some data from other API endpoint and store into database)
I also want to call this API as a cron job.
Thus, I am using apscheduler to execute the function for API but got following error.
Could anyone explain why "calling this function through API call works but doesnt work for calling the function from apscheduler"?
And how to fix this problem?

@app.route('/stats/calc',methods=['GET'])
def stats_calc():
    arguments={
        "General": {
            "keyword": "list",
            "cols": [],
            "new_cols": [],
            "processor": "basic",
            "row": 0
        },
        "Lift": {
            "keyword": "load",
            "cols": [],
            "new_cols":["Lift_Power"],
            "processor": "lift",
            "row": "Design_Level"
        }
               }
    new_summary = Summary(created_date=datetime.now())
    db.session.add(new_summary)
    db.session.commit()
    summary_id = getSummaryId()

    for key,obj in arguments.items():
        instance=parse_summary("127.0.0.1", obj["keyword"])
        instance.convert2df(cols=obj["cols"],processor=obj["processor"])

        df=instance.make_onedf(obj["row"])

        if df is None:
            #print ("No data in "+ key)
            dataset=""
            count=0
            stat_numbers=""
        else:
            # update column name
            if len(obj["new_cols"])==0:
                pass
            else:
                df.columns=obj["new_cols"]
            try:
                dataset=df.to_json()
                count=len(df.index)
                stat_numbers={}
                for col in df.columns:
                    stat_json=stats.calc_stats(df,col)
                    stat_numbers[col]=stat_json

                df.to_csv(key + ".csv")
            except:
                print (key)

        new_stat=Stat(category=key,
                          dataset=dataset,
                          count=count,
                        stat_numbers=json.dumps(stat_numbers),
                        summary_id=summary_id
                          )
        db.session.add(new_stat)
        db.session.commit()

    return "Finished to process"

scheduler = BackgroundScheduler({'apscheduler.timezone': 'Asia/Hong_Kong'},daemon=True)
scheduler.add_job(stats_calc,"interval",minutes=1)
scheduler.start()

Error

Job "stats_calc (trigger: interval[0:01:00], next run at: 2020-01-28 11:40:01 HKT)" raised an exception
Traceback (most recent call last):
  File "/Users/katsuya/.pyenv/versions/EBworker/lib/python3.6/site-packages/sqlalchemy/util/_collections.py", line 1030, in __call__
    return self.registry[key]
KeyError: 123145354907648

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/katsuya/.pyenv/versions/EBworker/lib/python3.6/site-packages/apscheduler/executors/base.py", line 125, in run_job
    retval = job.func(*job.args, **job.kwargs)
  File "/Users/katsuya/Documents/EBworker/analytics/views.py", line 153, in stats_calc
    db.session.add(new_summary)
  File "/Users/katsuya/.pyenv/versions/EBworker/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 162, in do
    return getattr(self.registry(), name)(*args, **kwargs)
  File "/Users/katsuya/.pyenv/versions/EBworker/lib/python3.6/site-packages/sqlalchemy/util/_collections.py", line 1032, in __call__
    return self.registry.setdefault(key, self.createfunc())
  File "/Users/katsuya/.pyenv/versions/EBworker/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 3234, in __call__
    return self.class_(**local_kw)
  File "/Users/katsuya/.pyenv/versions/EBworker/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 136, in __init__
    self.app = app = db.get_app()
  File "/Users/katsuya/.pyenv/versions/EBworker/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py", line 982, in get_app
    'No application found. Either work inside a view function or push'
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.
Katsuya Obara
  • 903
  • 3
  • 14
  • 30

0 Answers0