使用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 每個數據庫中插敘的有相對應的數據 """

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM