[英]Flask ImportError: cannot import name (for app in __init__.py)
我是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)
我究竟做錯了什么?
這是因為您在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 c_data
中刪除
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.