Я реализовал API в Flask и работает правильно. (Получить некоторые данные из другой конечной точки API и сохранить в базе данных)
Я также хочу назвать этот API как задание cron.
Таким образом, я использую apscheduler для выполнения функции для API, но получил следующую ошибку.
Может ли кто-нибудь объяснить, почему "вызов этой функции через вызов API работает, но не работает для вызова функции из apscheduler"?
И как решить эту проблему?
@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()
Ошибка
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/.