尝试将我的python文件updater.py
运行到SSH到服务器,并每隔几个设定的时间间隔运行一些命令。我正在使用APScheduler从update_printer()
运行功能__init__.py
。最初我有一个working outside of application context error
,但有人建议我只是从__init__
.py导入应用程序。但是效果不是很好。我不断收到cannot import name 'app'
错误。
app.py
from queue_app import app
if __name__ == '__main__':
app.run(debug=True)
__init__.py
from flask import Flask, render_template
from apscheduler.schedulers.background import BackgroundScheduler
from queue_app.updater import update_printer
app = Flask(__name__)
app.config.from_object('config')
@app.before_first_request
def init():
sched = BackgroundScheduler()
sched.start()
sched.add_job(update_printer, 'interval', seconds=10)
@app.route('/')
def index():
return render_template('index.html')
updater.py
import paramiko
import json
from queue_app import app
def update_printer():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(app.config['SSH_SERVER'], username = app.config['SSH_USERNAME'], password = app.config['SSH_PASSWORD'])
...
档案结构
queue/
app.py
config.py
queue_app/
__init__.py
updater.py
错误
Traceback (most recent call last):
File "app.py", line 1, in <module>
from queue_app import app
File "/Users/name/queue/queue_app/__init__.py", line 3, in <module>
from queue_app.updater import update_printer
File "/Users/name/queue/queue_app/updater.py", line 3, in <module>
from queue_app import app
ImportError: cannot import name 'app'
如果从APScheduler运行,我需要怎么做才能从updater.py转到app.config并避免“在应用程序上下文错误之外工作”?
最佳答案
当您在updater
文件中导入__init__.py
时,这是一个循环依赖性。在我的Flask设置中,在app
中创建了app.py
。