【问题标题】:Flask: cannot import name 'app'烧瓶:无法导入名称'app'
【发布时间】:2016-03-11 00:50:32
【问题描述】:

尝试运行我的 python 文件 updater.py 以通过 SSH 连接到服务器,并每隔几个设置的时间间隔运行一些命令。我正在使用 APScheduler 从__init__.py 运行函数update_printer()。最初我得到了一个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.py 中进行相对导入(例如 from .import app)
  • 同样的错误:Traceback (most recent call last): File "app.py", line 1, in &lt;module&gt; from queue_app import app File "/Users/name/queue/queue_app/__init__.py", line 3, in &lt;module&gt; from queue_app.updater import update_printer File "/Users/name/queue/queue_app/updater.py", line 3, in &lt;module&gt; from . import app ImportError: cannot import name 'app'
  • 哦..你有一个循环引用...app.py->__init__.py->updater.py->__init__.py

标签: python python-3.x flask


【解决方案1】:

这是一个循环依赖,因为您在 __init__.py 文件中导入 updater。在我的 Flask 设置中,app 是在 app.py 中创建的。

【讨论】:

    猜你喜欢
    • 2020-12-06
    • 1970-01-01
    • 2018-09-16
    • 2015-12-24
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    相关资源
    最近更新 更多