Flask ImportError:无法导入名称(对于__init__.py中的应用程序)

时间:2019-01-17 10:52:15

标签: python flask

我是Flask和REST-API /服务器端脚本的新手。尝试执行run_app.py

时,出现错误“ ImportError:无法导入名称'flask_app'”

这是我的目录结构。

my_project
        - webapp
              - __init__.py
              - helpers.py
              - c_data.py 

        - run_app.py

每个文件的内容:

__ init __。py

"""This is init module."""

from flask import Flask
from webapp import c_data

# Place where webapp is defined
flask_app = Flask(__name__)

c_data.py

"""This module will serve the api request."""

from app_config import client
from webapp import flask_app
from webapp import helpers
from flask import request, jsonify

# Select the database
db = client.newDB
# Select the collection
collection = db.collection


@flask_app.route("/")
def get_initial_response():
    """Welcome message for the API."""
    # Message to the user
    message = {
        'apiVersion': 'v1.0',
        'status': '200',
        'message': 'Welcome to the Flask API'
    }
    # Making the message looks good
    resp = jsonify(message)
    # Returning the object
    return resp

run_app.py

# -*- coding: utf-8 -*-

from webapp import flask_app

if __name__ == '__main__':
    # Running webapp in debug mode
    flask_app.run(debug=True)

我在做什么错?

1 个答案:

答案 0 :(得分:1)

这是因为您在 init .py中导入了c_data,因此可以进行递归导入 为了更清楚,您导入c_data并在__init__中定义flask_app,但晚于c_data导入尚未定义的flask_app

from webapp import c_data # Remove it, it makes recursive import

# Place where webapp is defined
flask_app = Flask(__name__)


尝试将其删除。或更改导入c_data的方式。

可能的解决方案,请更改您的run_app.py 记住要删除from webapp import c_data

中的__init__.py

from webapp import flask_app
from webapp import c_data  # New import

if __name__ == '__main__':
    # Running webapp in debug mode
    flask_app.run(debug=True)
相关问题