使用Flask_SQLAlchemy连接多个数据库

#!/usr/bin/env python
#-*- coding: utf-8 -*-


from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

# 配置多个数据库连接
SQLALCHEMY_BINDS = {
    'users': 'sqlite:///users.db',
    'appmeta': 'sqlite:///appmeta.db'
}

app.config['SQLALCHEMY_DATABASE_URI'] =  'sqlite:///test.db' # 默认数据库引擎
app.config['SQLALCHEMY_BINDS'] = SQLALCHEMY_BINDS
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)


class News(db.Model):
    __tablename__ = 'news' # 未设置__bind_key__,则采用默认的数据库引擎

    id = db.Column(db.Integer, primary_key=True)
    news_title = db.Column(db.String(80), unique=True)
    news_content = db.Column(db.String(120), unique=True)

    def __init__(self, news_title, news_content):
        self.news_title = news_title
        self.news_content = news_content

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

class User(db.Model):
    __bind_key__ = 'users' # 已设置__bind_key__,则采用设置的数据库引擎
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.username

class Article(db.Model):
    __bind_key__ = 'appmeta'
    __tablename__ = 'article'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80), unique=True)
    content = db.Column(db.String(120), unique=True)

    def __init__(self, title, content):
        self.title = title
        self.content = content

    def __repr__(self):
        return '<Title %r>' % self.title


db.create_all() # 未指定bind,则使用默认的数据库引擎
db.create_all(bind='users') # 指定bind,则使用指定的数据库引擎
db.create_all(bind='appmeta')

news = News('ha','hahahhahaha') # 自动关联到相对应的ORM模型,进而使用相关联的数据库引擎
db.session.add(news) # 插入一条数据
db.session.commit()

admin = User('admin', 'admin@example.com')
guest = User('guest', 'guest@example.com')
db.session.add_all([admin,guest]) # 插入多条数据
db.session.commit()

title = Article('title1', 'content1')
db.session.add(title)
db.session.commit()

"""
执行该文件,会自动生成三个数据库文件:appmeta.db,users.db,test.db
每个数据库中插叙的有相对应的数据
"""
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值