如何解决Flask错误:ImportError无法从“ app”中导入名称“ app”
我刚刚开始学习Flask,并且正在构建我的第一个应用程序。 我的想法是制作一个简单的应用程序,以便将其存储在SQLite的学生,班级和教师中。
为此,我只做了两个python文件: app.py->创建应用程序并定义路由 models.py->创建数据库模型以进行存储
以某种方式,当我尝试将应用程序导入模型时,出现此错误:
Traceback (most recent call last):
File "/Users/thiago/coding/eu-decidi/lib/python3.7/site-packages/flask/cli.py",line 240,in locate_app
__import__(module_name)
File "/Users/thiago/coding/eu-decidi/app.py",line 6,in <module>
from models import Student,Teacher,Meeting,stud_identifier
File "/Users/thiago/coding/eu-decidi/models.py",line 1,in <module>
from app import app
ImportError: cannot import name 'app' from 'app' (/Users/thiago/coding/eu-decidi/app.py)
只需将代码放在这里:
app.py:
from flask import Flask,render_template,request,url_for,redirect,flash
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField
from wtforms.validators import DataRequired
from models import Student,stud_identifier
app = Flask(__name__) #application instance
app.config['SECRET_KEY']= 'my_secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///myDB.db' #path to database and its name
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False #supress warning of changes on database
db = SQLAlchemy(app) #database instance
@app.route('/')
@app.route('/index')
def index():
return render_template("index.html")
@app.route('/students')
def students():
return "Here are all our students"
@app.route('/teachers')
def teachers():
return "Here are all our teachers"
@app.route('/classes')
def classes():
return "Here are all our classes"
# app name
@app.errorhandler(404)
def not_found(e):
return "Page not found"
models.py:
from app import app
from app import db
stud_identifier = db.Table('stud_ident',db.Column('student',db.Integer,db.ForeignKey('student.student_id')),db.Column('meeting',db.ForeignKey('meeting.meeting_id'))
)
class Student(db.Model):
#__tablename__ = 'student'
student_id = db.Column(db.Integer,primary_key = True) #primary Key column,automatically generated IDs
student_name = db.Column(db.String(80),index = True,unique = False) #name of student
student_surname = db.Column(db.String(100),unique = False) #surname of student
student_phone = db.Column(db.Integer,index=True,unique = True) #student phone number
student_email = db.Column(db.String(200),unique = True) #student email
#RELATIONSHIPS
meetings = db.relationship('Meeting',secondary=stud_identifier,backref=db.backref('students',lazy='dynamic'))
def __repr__(self):
return "Aluno: {} {},telefone: {}".format(self.student_name,self.student_surname,self.student_phone)
class Meeting(db.Model):
#__tablename__='meeting'
meeting_id = db.Column(db.Integer,primary_key =True)
meeting_date = db.Column(db.Date,unique=False) #date of the meeting
meeting_subject = db.Column(db.String(80),unique=False) #subject of the meeting (Aula 1,Aula 2,Aula 3)
#RELATIONSHIPS
teacher_id = db.Column(db.Integer,db.ForeignKey('teacher.teacher_id'))
#meeting.students.append(student) -> vai somar um aluno na tabela de identificação
class Teacher(db.Model):
#__tablename__='teacher'
teacher_id = db.Column(db.Integer,primary_key =True)
teacher_name = db.Column(db.String(80),unique = False) #name of Teacher
teacher_surname = db.Column(db.String(100),unique = False) #surname of teacher
teacher_phone = db.Column(db.Integer,unique = True) #teacher phone number
teacher_email = db.Column(db.String(200),unique = True) #Teacher email
#RELATIONSHIPS
meetings = db.relationship('Meeting',uselist=False,backref='teacher')
以下是存储库: Repository
解决方法
创建一个主文件夹,将除“ app.py”文件之外的所有文件和文件夹移动到该主文件夹中。保存,然后运行。
,乍一看,我想这可能是循环导入,因为models
在定义app
之前需要尝试导入app
。但是,我确实想指出您的应用程序结构可以进行改进,以使应用程序更易于理解。这通常是我构建烧瓶应用程序的方式:
run.py
(应用程序入口点)
venv
(虚拟环境)
decidi
(您的应用程序包,其中的每个.py文件都可以作为该包的模块导入)
----- __init__.py
(Python会看到此文件名,并将整个文件夹视为包)
----- models.py
----- templates
---------- index.html
----- static
(提供CSS和图像等静态文件)
在run.py
中,这非常简单。它从应用程序包(在您的情况下为decidi
)中导入应用程序。
from decidi import app
if __name__ == '__main__':
app.run(debug=True)
在decidi/__init__.py
中,将您拥有的东西放入app.py中。请注意,必须在初始化db
之后执行模型的导入,否则将导致循环导入。某些编辑器可能会自动移动导入,在这种情况下,您需要关闭该功能。
from flask import Flask,render_template,request,url_for,redirect,flash
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__) #application instance
app.config['SECRET_KEY']= 'my_secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///myDB.db' #path to database and its name
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False #supress warning of changes on database
db = SQLAlchemy(app) #database instance
from decidi.models import Student # DO NOT PUT THIS AT THE TOP
@app.route('/')
@app.route('/index')
def index():
return render_template("index.html")
在decidi/models.py
中,您可以直接从应用程序包中导入db
,因为它位于程序包的__init__.py
中。
from decidi import db
class Student(db.Model):
#__tablename__ = 'student'
student_id = db.Column(db.Integer,primary_key = True) #primary Key column,automatically generated IDs
student_name = db.Column(db.String(80),index = True,unique = False) #name of student
student_surname = db.Column(db.String(100),unique = False) #surname of student
student_phone = db.Column(db.Integer,index=True,unique = True) #student phone number
student_email = db.Column(db.String(200),unique = True) #student email
def __repr__(self):
return "Aluno: {} {},telefone: {}".format(self.student_name,self.student_surname,self.student_phone)
要运行该应用程序,请将CD插入run.py
所在的目录,激活虚拟环境,然后简单地python3 run.py
。
为简单起见,我只保留了大部分代码。但是要旨在那里。随时问我是否引起混乱。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。