尝试运行我的 python 文件updater.py
通过 SSH 连接到服务器并每隔几个设定的时间间隔运行一些命令。我正在使用 APScheduler 来运行该函数update_printer()
from __init__.py
。最初我得到了一个working outside of application context error
但有人建议我只导入应用程序__init__
.py。然而,效果并不那么好。我不断收到cannot import name 'app'
error.
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')
更新程序.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
Error
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 并避免“在应用程序上下文之外工作错误”?