app.py file
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()
when I run the app, the crashes with 'ImportError: cannot import name 'db' from 'app''. I don't know what I am doing wrong. When I do them on the same file it works. when I takeout the database Model from the app.py file it doesnt work anymore. Thank you for your help
import database after you instantiate your db.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.