app.py文件
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from database import CreateQuestions
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "postgres://jim:password@localhost:5433/exquizdb"
db = SQLAlchemy(app)
@app.route('/questions')
def post_question():
q = 'hey'
a = 'hi'
CreateQuestions.Create_questions(q, a)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
database.py
# database.py
from app import db
class Questions(db.Model):
question_id = db.Column(db.Integer, primary_key=True)
question = db.Column(db.Text)
class Answers(db.Model):
answer_id = db.Column(db.Integer, primary_key=True)
answer = db.Column(db.Text)
question_id = db.Column(db.Integer, db.ForeignKey('questions.question_id'))
class CreateQuestions:
def create_questions(self, q, a):
ques = Questions(question=q)
ans = Answers(answer=a)
db.create_all()
db.session.add(ques)
db.session.add(ans)
db.session.commit()
当我运行应用程序时,崩溃并显示“ ImportError:无法从'应用程序'导入名称'db'。我不知道我在做什么错。当我在同一个文件上执行这些操作时,它将起作用。当我从app.py文件中取出数据库模型时,它不再起作用。谢谢您的帮助
答案 0 :(得分:1)
实例化数据库后,导入数据库。
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "postgres://jim:password@localhost:5433/exquizdb"
db = SQLAlchemy(app)
from database import CreateQuestions