0

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.