首页 > 解决方案 > 烧瓶错误:ImportError 无法从“app”导入名称“app”

问题描述

我刚开始学习 Flask,并且正在构建我的第一个应用程序。这个想法是制作一个简单的应用程序,我可以在其中存储 SQLite 学生、班级和教师。

为了实现这一点,我只做了两个 python 文件:app.py -> 创建应用程序并定义路由 models.py -> 创建 db 模型以存储它们

不知何故,当我尝试将应用程序导入模型时,出现此错误:

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)

只是将代码放在这里:

应用程序.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, Teacher, Meeting, 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"

模型.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.Integer, 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), index = True, 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), index=True, 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, index = True, unique=False) #date of the meeting
    meeting_subject = db.Column(db.String(80), index = True, 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), index = True, unique = False) #name of Teacher
    teacher_surname = db.Column(db.String(100), index = True, unique = False) #surname of teacher
    teacher_phone = db.Column(db.Integer, index=True, unique = True) #teacher phone number
    teacher_email = db.Column(db.String(200), index=True, unique = True) #Teacher email
    #RELATIONSHIPS
    meetings = db.relationship('Meeting', uselist=False, backref='teacher')

这里也是存储库: 存储库

标签: pythonsqliteflask

解决方案


乍一看,我会说这可能是一个循环导入的东西,因为在定义之前需要models尝试导入。但是,我确实想指出您的应用程序结构可以改进以使应用程序更易于理解。以下是我通常如何构建我的烧瓶应用程序:appapp


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), index = True, 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), index=True, 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.

为了简单起见,我只保留了大部分代码。但要点就在那里。如果这引起了混乱,请随时在评论中问我。


推荐阅读