S
S
Secret_dungeon2020-10-11 16:11:57
Flask
Secret_dungeon, 2020-10-11 16:11:57

How to make two databases in Flask?

I have a problem can not create a second database, I use SQLAlchemy
Here is the code:

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///blog.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
app2 = Flask(__name__)
app2.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///message.db'
app2.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db2 = SQLAlchemy(app2)






class Article(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    intro = db.Column(db.String(300), nullable=False)
    text = db.Column(db.Text, nullable=False)
    date = db.Column(db.DateTime, default=datetime.utcnow)



    def __repr__(self):
        return '<Article %r>' % self.id


class Messages(db2.Model):
    Name = db2.Column(db2.Text, nullable=False)
    Surname = db2.Column(db2.Text, nullable=False)
    text = db2.Column(db2.Text, nullable=False)
    date = db2.Column(db2.DateTime, default=datetime.utcnow)



    def __repr__(self):
        return '<Messages %r>' % self.id

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Yakushenko, 2020-10-11
@Secret_dungeon

Minimum working option:

from datetime import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'
app.config['SQLALCHEMY_BINDS'] = {
    'messages': 'sqlite:///message.db'
}

db = SQLAlchemy(app)


class Article(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    intro = db.Column(db.String(300), nullable=False)
    text = db.Column(db.Text, nullable=False)
    date = db.Column(db.DateTime, default=datetime.utcnow)


    def __repr__(self):
        return '<Article %r>' % self.id


class Message(db.Model):

    __bind_key__ = 'messages'

    id = db.Column(db.Integer, primary_key=True)
    Name = db.Column(db.Text, nullable=False)
    Surname = db.Column(db.Text, nullable=False)
    text = db.Column(db.Text, nullable=False)
    date = db.Column(db.DateTime, default=datetime.utcnow)


    def __repr__(self):
        return '<Message %r>' % self.Name


@app.route('/add_message')
def add_message():
    message = Message(Name='name', Surname='surname', text='foo')
    db.session.add(message)
    db.session.commit()
    return 'True'


db.create_all()
db.create_all(bind='messages')


if __name__ == '__main__':
    app.run(debug=1)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question